source
stringlengths
3
92
c
stringlengths
26
2.25M
kClistNodeParallel.c
/* Info: Feel free to use these lines as you wish. This program iterates over all k-cliques. This is an improvement of the 1985 algorithm of Chiba And Nishizeki detailed in "Arboricity and subgraph listing". To compile: "gcc kClistNodeParallel.c -O9 -o kClistNodeParallel -fopenmp". To execute: "./kClistNodeParallel p k edgelist.txt". "edgelist.txt" should contain the graph: one edge on each line separated by a space. k is the size of the k-cliques p is the number of threads Will print the number of k-cliques. */ #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <time.h> #include <omp.h> #define NLINKS 100000000 //maximum number of edges for memory allocation, will increase if needed typedef unsigned long int Node; typedef unsigned long long int Edge; typedef unsigned long long int Clique; typedef unsigned char Kvalue; typedef struct { Node s; Node t; } edge; typedef struct { Node node; Node deg; } nodedeg ; typedef struct { Node n;//number of nodes Edge e;//number of edges edge *edges;//list of edges Node *rank;//ranking of the nodes according to degeneracy ordering //unsigned *map;//oldID newID correspondance NOT USED IN THIS VERSION } edgelist; typedef struct { Node n; Edge e; edge *edges;//ading this again here: TO IMPROVE Edge *cd;//cumulative degree: (starts with 0) length=n+1 Node *adj;//truncated list of neighbors Node core;//core value of the graph } graph; typedef struct { Node *n;//n[l]: number of nodes in G_l Node **d;//d[l]: degrees of G_l Node *adj;//truncated list of neighbors Kvalue *lab;//lab[i] label of node i Node **nodes;//sub[l]: nodes in G_l Node core; Node* new;//forgot what that is... Node* old; } subgraph; void free_edgelist(edgelist *el){ free(el->edges); free(el->rank); free(el); } void free_graph(graph *g){ free(g->cd); free(g->adj); free(g); } void free_subgraph(subgraph *sg, Kvalue k){ Kvalue i; free(sg->n); for (i=2;i<k;i++){ free(sg->d[i]); free(sg->nodes[i]); } free(sg->d); free(sg->nodes); free(sg->lab); free(sg->adj); free(sg); } //Compute the maximum of three unsigned integers. inline Node max3(Node a,Node b,Node c){ a=(a>b) ? a : b; return (a>c) ? a : c; } edgelist* readedgelist(char* input){ Edge e1=NLINKS; edgelist *el=malloc(sizeof(edgelist)); FILE *file; el->n=0; el->e=0; file=fopen(input,"r"); el->edges=malloc(e1*sizeof(edge)); while (fscanf(file,"%lu %lu", &(el->edges[el->e].s), &(el->edges[el->e].t))==2) {//Add one edge el->n=max3(el->n,el->edges[el->e].s,el->edges[el->e].t); el->e++; if (el->e==e1) { e1+=NLINKS; el->edges=realloc(el->edges,e1*sizeof(edge)); } } fclose(file); el->n++; el->edges=realloc(el->edges,el->e*sizeof(edge)); return el; } void relabel(edgelist *el){ Edge i; Node source, target, tmp; for (i=0;i<el->e;i++) { source=el->rank[el->edges[i].s]; target=el->rank[el->edges[i].t]; if (source<target){ tmp=source; source=target; target=tmp; } el->edges[i].s=source; el->edges[i].t=target; } } ///// CORE ordering ///////////////////// typedef struct { Node key; Node value; } keyvalue; typedef struct { Node n_max; // max number of nodes. Node n; // number of nodes. Node *pt; // pointers to nodes. keyvalue *kv; // nodes. } bheap; bheap *construct(Node n_max){ Node i; bheap *heap=malloc(sizeof(bheap)); heap->n_max=n_max; heap->n=0; heap->pt=malloc(n_max*sizeof(Node)); for (i=0;i<n_max;i++) heap->pt[i]=-1; heap->kv=malloc(n_max*sizeof(keyvalue)); return heap; } void swap(bheap *heap,Node i, Node j) { keyvalue kv_tmp=heap->kv[i]; Node pt_tmp=heap->pt[kv_tmp.key]; heap->pt[heap->kv[i].key]=heap->pt[heap->kv[j].key]; heap->kv[i]=heap->kv[j]; heap->pt[heap->kv[j].key]=pt_tmp; heap->kv[j]=kv_tmp; } void bubble_up(bheap *heap,Node i) { Node j=(i-1)/2; while (i>0) { if (heap->kv[j].value>heap->kv[i].value) { swap(heap,i,j); i=j; j=(i-1)/2; } else break; } } void bubble_down(bheap *heap) { Node i=0,j1=1,j2=2,j; while (j1<heap->n) { j=( (j2<heap->n) && (heap->kv[j2].value<heap->kv[j1].value) ) ? j2 : j1 ; if (heap->kv[j].value < heap->kv[i].value) { swap(heap,i,j); i=j; j1=2*i+1; j2=j1+1; continue; } break; } } void insert(bheap *heap,keyvalue kv){ heap->pt[kv.key]=(heap->n)++; heap->kv[heap->n-1]=kv; bubble_up(heap,heap->n-1); } void update(bheap *heap,Node key){ Node i=heap->pt[key]; if (i!=-1){ ((heap->kv[i]).value)--; bubble_up(heap,i); } } keyvalue popmin(bheap *heap){ keyvalue min=heap->kv[0]; heap->pt[min.key]=-1; heap->kv[0]=heap->kv[--(heap->n)]; heap->pt[heap->kv[0].key]=0; bubble_down(heap); return min; } //Building the heap structure with (key,value)=(node,degree) for each node bheap* mkheap(Node n,Node *v){ Node i; keyvalue kv; bheap* heap=construct(n); for (i=0;i<n;i++){ kv.key=i; kv.value=v[i]; insert(heap,kv); } return heap; } void freeheap(bheap *heap){ free(heap->pt); free(heap->kv); free(heap); } //computing degeneracy ordering and core value void ord_core(edgelist* el){ Node i, r=0, n=el->n; Edge j, e=el->e; keyvalue kv; bheap *heap; Node *d0=calloc(el->n,sizeof(Node)); Edge *cd0=malloc((el->n+1)*sizeof(Edge)); Node *adj0=malloc(2*el->e*sizeof(Node)); for (j=0;j<e;j++) { d0[el->edges[j].s]++; d0[el->edges[j].t]++; } cd0[0]=0; for (i=1;i<n+1;i++) { cd0[i]=cd0[i-1]+d0[i-1]; d0[i-1]=0; } for (j=0;j<e;j++) { adj0[ cd0[el->edges[j].s] + d0[ el->edges[j].s ]++ ]=el->edges[j].t; adj0[ cd0[el->edges[j].t] + d0[ el->edges[j].t ]++ ]=el->edges[j].s; } heap=mkheap(n,d0); el->rank=malloc(n*sizeof(Node)); for (i=0;i<n;i++){ kv=popmin(heap); el->rank[kv.key]=n-(++r); for (j=cd0[kv.key];j<cd0[kv.key+1];j++){ update(heap,adj0[j]); } } freeheap(heap); free(d0); free(cd0); free(adj0); } ////////////////////////// //Building the special graph graph* mkgraph(edgelist *el){ Node i,max; Edge j; Node *d; graph* g=malloc(sizeof(graph)); d=calloc(el->n,sizeof(Node)); for (j=0;j<el->e;j++) { d[el->edges[j].s]++; } g->cd=malloc((el->n+1)*sizeof(Edge)); g->cd[0]=0; max=0; for (i=1;i<el->n+1;i++) { g->cd[i]=g->cd[i-1]+d[i-1]; max=(max>d[i-1])?max:d[i-1]; d[i-1]=0; } printf("core value (max truncated degree) = %lu\n",max); fflush(stdout); g->adj=malloc(el->e*sizeof(Node)); for (j=0;j<el->e;j++) { g->adj[ g->cd[el->edges[j].s] + d[ el->edges[j].s ]++ ]=el->edges[j].t; } free(d); g->core=max; g->n=el->n; return g; } subgraph* allocsub(graph *g,Kvalue k){ Kvalue i; subgraph* sg=malloc(sizeof(subgraph)); sg->n=calloc(k,sizeof(Node)); sg->d=malloc(k*sizeof(Node*)); sg->nodes=malloc(k*sizeof(Node*)); for (i=2;i<k;i++){ sg->d[i]=malloc(g->core*sizeof(Node)); sg->nodes[i]=malloc(g->core*sizeof(Node)); } sg->lab=calloc(g->core,sizeof(Kvalue)); sg->adj=malloc(g->core*g->core*sizeof(Node)); sg->core=g->core; return sg; } void mksub(graph* g,Node u,subgraph* sg,Kvalue k){ Node i,j,v,w; Edge l; static Node *old=NULL,*new=NULL;//to improve #pragma omp threadprivate(new,old) if (old==NULL){ new=malloc(g->n*sizeof(Node)); old=malloc(g->core*sizeof(Node)); for (i=0;i<g->n;i++){ new[i]=-1; } } for (i=0;i<sg->n[k-1];i++){ sg->lab[i]=0; } j=0; for (l=g->cd[u];l<g->cd[u+1];l++){ v=g->adj[l]; new[v]=j; old[j]=v; sg->lab[j]=k-1; sg->nodes[k-1][j]=j; sg->d[k-1][j]=0;//new degrees j++; } sg->n[k-1]=j; for (i=0;i<sg->n[k-1];i++){//reodering adjacency list and computing new degrees v=old[i]; for (l=g->cd[v];l<g->cd[v+1];l++){ w=g->adj[l]; j=new[w]; if (j!=-1){ sg->adj[sg->core*i+sg->d[k-1][i]++]=j; } } } for (l=g->cd[u];l<g->cd[u+1];l++){ new[g->adj[l]]=-1; } } void kclique_thread(Kvalue l, subgraph *sg, Clique *n) { Node i,j,k,end,u,v,w; if(l==2){ for(i=0; i<sg->n[2]; i++){//list all edges u=sg->nodes[2][i]; end=u*sg->core+sg->d[2][u]; for (j=u*sg->core;j<end;j++) { (*n)++;//listing here!!! // NOTE THAT WE COULD DO (*n)+=g->d[2][u] to be much faster (for counting only); !!!!!!!!!!!!!!!!!! } } return; } for(i=0; i<sg->n[l]; i++){ u=sg->nodes[l][i]; //printf("%u %u\n",i,u); sg->n[l-1]=0; end=u*sg->core+sg->d[l][u]; for (j=u*sg->core;j<end;j++){//relabeling nodes and forming U'. v=sg->adj[j]; if (sg->lab[v]==l){ sg->lab[v]=l-1; sg->nodes[l-1][sg->n[l-1]++]=v; sg->d[l-1][v]=0;//new degrees } } for (j=0;j<sg->n[l-1];j++){//reodering adjacency list and computing new degrees v=sg->nodes[l-1][j]; end=sg->core*v+sg->d[l][v]; for (k=sg->core*v;k<end;k++){ w=sg->adj[k]; if (sg->lab[w]==l-1){ sg->d[l-1][v]++; } else{ sg->adj[k--]=sg->adj[--end]; sg->adj[end]=w; } } } kclique_thread(l-1, sg, n); for (j=0;j<sg->n[l-1];j++){//restoring labels v=sg->nodes[l-1][j]; sg->lab[v]=l; } } } Clique kclique_main(Kvalue k, graph *g) { Node u; Clique n=0; subgraph *sg; #pragma omp parallel private(sg,u) reduction(+:n) { sg=allocsub(g,k); #pragma omp for schedule(dynamic, 1) nowait for(u=0; u<g->n; u++){ mksub(g,u,sg,k); kclique_thread(k-1, sg, &n); } } return n; } int main(int argc,char** argv){ edgelist* el; graph* g; Kvalue k=atoi(argv[2]); Clique n; omp_set_num_threads(atoi(argv[1])); time_t t0,t1,t2; t1=time(NULL); t0=t1; printf("Reading edgelist from file %s\n",argv[3]); el=readedgelist(argv[3]); printf("Number of nodes = %lu\n",el->n); printf("Number of edges = %llu\n",el->e); t2=time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60)); t1=t2; printf("Building the graph structure\n"); ord_core(el); relabel(el); g=mkgraph(el); printf("Number of nodes (degree > 0) = %lu\n",g->n); free_edgelist(el); t2=time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60)); t1=t2; printf("Iterate over all cliques\n"); n=kclique_main(k, g); printf("Number of %u-cliques: %llu\n",k,n); t2=time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60)); t1=t2; free_graph(g); printf("- Overall time = %ldh%ldm%lds\n",(t2-t0)/3600,((t2-t0)%3600)/60,((t2-t0)%60)); return 0; }
SoaDistanceTableABOMPTarget.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. // Amrita Mathuriya, amrita.mathuriya@intel.com, Intel Corp. // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// // -*- C++ -*- #ifndef QMCPLUSPLUS_DTDIMPL_AB_OMPTARGET_H #define QMCPLUSPLUS_DTDIMPL_AB_OMPTARGET_H #include "OMPTarget/OMPallocator.hpp" #include "Platforms/PinnedAllocator.h" #include "Particle/RealSpacePositionsOMPTarget.h" namespace qmcplusplus { /**@ingroup nnlist * @brief A derived classe from DistacneTableData, specialized for AB using a transposed form */ template<typename T, unsigned D, int SC> class SoaDistanceTableABOMPTarget : public DTD_BConds<T, D, SC>, public DistanceTableData { private: template<typename DT> using OffloadPinnedVector = Vector<DT, OMPallocator<DT, PinnedAlignedAllocator<DT>>>; ///accelerator output array for multiple walkers, N_targets x N_sources_padded x (D+1) (distances, displacements) OffloadPinnedVector<RealType> offload_output; ///accelerator input array for a list of target particle positions, N_targets x D OffloadPinnedVector<RealType> target_pos; ///accelerator input buffer for multiple data set OffloadPinnedVector<char> offload_input; ///accelerator output buffer for r and dr OffloadPinnedVector<RealType> r_dr_memorypool_; ///target particle id std::vector<int> particle_id; ///device pointer of r_dr_memorypool_ RealType* r_dr_device_ptr_; /// timer for offload portion NewTimer& offload_timer_; /// timer for copy portion NewTimer& copy_timer_; /// timer for offload portion NewTimer& eval_timer_; public: SoaDistanceTableABOMPTarget(const ParticleSet& source, ParticleSet& target) : DTD_BConds<T, D, SC>(source.Lattice), DistanceTableData(source, target), r_dr_device_ptr_(nullptr), offload_timer_(*timer_manager.createTimer(std::string("SoaDistanceTableABOMPTarget::offload_") + target.getName() + "_" + source.getName(), timer_level_fine)), copy_timer_(*timer_manager.createTimer(std::string("SoaDistanceTableABOMPTarget::copy_") + target.getName() + "_" + source.getName(), timer_level_fine)), eval_timer_(*timer_manager.createTimer(std::string("SoaDistanceTableABOMPTarget::evaluate_") + target.getName() + "_" + source.getName(), timer_level_fine)) { auto* coordinates_soa = dynamic_cast<const RealSpacePositionsOMPTarget*>(&source.getCoordinates()); if (!coordinates_soa) throw std::runtime_error("Source particle set doesn't have OpenMP offload. Contact developers!"); resize(source.getTotalNum(), target.getTotalNum()); #pragma omp target enter data map(to:this[:1]) } void resize(int ns, int nt) { N_sources = ns; N_targets = nt; if (N_sources * N_targets == 0) return; // initialize memory containers and views const int N_sources_padded = getAlignedSize<T>(N_sources); const int stride_size = N_sources_padded * (D + 1); r_dr_memorypool_.resize(stride_size * N_targets); auto* pool_ptr = r_dr_memorypool_.data(); #pragma omp target data use_device_ptr(pool_ptr) { r_dr_device_ptr_ = pool_ptr; } distances_.resize(N_targets); displacements_.resize(N_targets); for (int i = 0; i < N_targets; ++i) { distances_[i].attachReference(r_dr_memorypool_.data() + i * stride_size, N_sources); displacements_[i].attachReference(N_sources, N_sources_padded, r_dr_memorypool_.data() + i * stride_size + N_sources_padded); } // The padding of temp_r_ and temp_dr_ is necessary for the memory copy in the update function // temp_r_ is padded explicitly while temp_dr_ is padded internally temp_r_.resize(N_sources_padded); temp_dr_.resize(N_sources); } SoaDistanceTableABOMPTarget() = delete; SoaDistanceTableABOMPTarget(const SoaDistanceTableABOMPTarget&) = delete; ~SoaDistanceTableABOMPTarget() { #pragma omp target exit data map(delete:this[:1]) } /** evaluate the full table */ inline void evaluate(ParticleSet& P) { ScopedTimer eval(&eval_timer_); // be aware of the sign of Displacement const int N_targets_local = N_targets; const int N_sources_local = N_sources; const int N_sources_padded = getAlignedSize<T>(N_sources); target_pos.resize(N_targets * D); for (size_t iat = 0; iat < N_targets; iat++) for (size_t idim = 0; idim < D; idim++) target_pos[iat * D + idim] = P.R[iat][idim]; auto* target_pos_ptr = target_pos.data(); auto* source_pos_ptr = Origin->getCoordinates().getAllParticlePos().data(); auto* r_dr_ptr = r_dr_memorypool_.data(); // To maximize thread usage, the loop over electrons is chunked. Each chunk is sent to an OpenMP offload thread team. const int ChunkSizePerTeam = 256; const int num_teams = (N_sources + ChunkSizePerTeam - 1) / ChunkSizePerTeam; { ScopedTimer offload(&offload_timer_); #pragma omp target teams distribute collapse(2) num_teams(N_targets*num_teams) \ map(to: source_pos_ptr[:N_sources_padded*D]) \ map(always, to: target_pos_ptr[:N_targets*D]) \ map(always, from: r_dr_ptr[:r_dr_memorypool_.size()]) for (int iat = 0; iat < N_targets_local; ++iat) for (int team_id = 0; team_id < num_teams; team_id++) { const int first = ChunkSizePerTeam * team_id; const int last = (first + ChunkSizePerTeam) > N_sources_local ? N_sources_local : first + ChunkSizePerTeam; T pos[D]; for (int idim = 0; idim < D; idim++) pos[idim] = target_pos_ptr[iat * D + idim]; const size_t stride_size = N_sources_padded * (D + 1); auto* r_iat_ptr = r_dr_ptr + iat * stride_size; auto* dr_iat_ptr = r_iat_ptr + N_sources_padded; DTD_BConds<T, D, SC>::computeDistancesOffload(pos, source_pos_ptr, r_iat_ptr, dr_iat_ptr, N_sources_padded, first, last); } } } /** It has two implementation mw_evaluate_transfer_inplace and mw_evaluate_fuse_transfer with different D2H memory transfer schemes. * Eventually, there will be only one version wihtout any transfer and solve the dilemma. */ inline void mw_evaluate(const RefVector<DistanceTableData>& dt_list, const RefVector<ParticleSet>& p_list) { ScopedTimer eval(&eval_timer_); mw_evaluate_fuse_transfer(dt_list, p_list); } /** this function implements mw_evaluate. * After offloading the computation of distances and displacements, the per-walker result is transferred back walker by walker in place. * The runtime overhead is very high for small problem size with many walkers. */ inline void mw_evaluate_transfer_inplace(const RefVector<DistanceTableData>& dt_list, const RefVector<ParticleSet>& p_list) { const size_t nw = dt_list.size(); size_t count_targets = 0; for (ParticleSet& p: p_list) count_targets += p.getTotalNum(); const size_t total_targets = count_targets; // This is horrible optimization putting different data types in a single buffer but allows a single H2D transfer constexpr size_t realtype_size = sizeof(RealType); constexpr size_t int_size = sizeof(int); constexpr size_t ptr_size = sizeof(RealType*); offload_input.resize(total_targets * D * realtype_size + total_targets * int_size + (nw + total_targets) * ptr_size); auto target_positions = reinterpret_cast<RealType*>(offload_input.data()); auto walker_id_ptr = reinterpret_cast<int*>(offload_input.data() + total_targets * D * realtype_size); auto source_ptrs = reinterpret_cast<RealType**>(offload_input.data() + total_targets * D * realtype_size + total_targets * int_size); auto output_ptrs = reinterpret_cast<RealType**>(offload_input.data() + total_targets * D * realtype_size + total_targets * int_size + nw * ptr_size); const int N_sources_padded = getAlignedSize<T>(N_sources); offload_output.resize(total_targets * N_sources_padded * (D + 1)); count_targets = 0; for (size_t iw = 0; iw < nw; iw++) { auto& dt = static_cast<SoaDistanceTableABOMPTarget&>(dt_list[iw].get()); ParticleSet& pset(p_list[iw]); assert(N_sources == dt.N_sources); auto& RSoA_OMPTarget = static_cast<const RealSpacePositionsOMPTarget&>(dt.Origin->getCoordinates()); source_ptrs[iw] = const_cast<RealType*>(RSoA_OMPTarget.getDevicePtr()); for (size_t iat = 0; iat < pset.getTotalNum(); ++iat, ++count_targets) { for (size_t idim = 0; idim < D; idim++) target_positions[count_targets * D + idim] = pset.R[iat][idim]; walker_id_ptr[count_targets] = iw; output_ptrs[count_targets] = dt.r_dr_device_ptr_ + iat * N_sources_padded * (D + 1); } } const int N_sources_local = N_sources; // To maximize thread usage, the loop over electrons is chunked. Each chunk is sent to an OpenMP offload thread team. const int ChunkSizePerTeam = 256; const int num_teams = (N_sources + ChunkSizePerTeam - 1) / ChunkSizePerTeam; auto* input_ptr = offload_input.data(); { ScopedTimer offload(&offload_timer_); #pragma omp target teams distribute collapse(2) num_teams(total_targets*num_teams) \ map(always, to: input_ptr[:offload_input.size()]) \ nowait depend(out: total_targets) for (int iat = 0; iat < total_targets; ++iat) for (int team_id = 0; team_id < num_teams; team_id++) { auto* target_pos_ptr = reinterpret_cast<RealType*>(input_ptr); const int walker_id = reinterpret_cast<int*>(input_ptr + total_targets * D * realtype_size)[iat]; auto* source_pos_ptr = reinterpret_cast<RealType**>(input_ptr + total_targets * D * realtype_size + total_targets * int_size)[walker_id]; auto* r_iat_ptr = reinterpret_cast<RealType**>(input_ptr + total_targets * D * realtype_size + total_targets * int_size + nw * ptr_size)[iat]; auto* dr_iat_ptr = r_iat_ptr + N_sources_padded; const int first = ChunkSizePerTeam * team_id; const int last = (first + ChunkSizePerTeam) > N_sources_local ? N_sources_local : first + ChunkSizePerTeam; T pos[D]; for (int idim = 0; idim < D; idim++) pos[idim] = target_pos_ptr[iat * D + idim]; DTD_BConds<T, D, SC>::computeDistancesOffload(pos, source_pos_ptr, r_iat_ptr, dr_iat_ptr, N_sources_padded, first, last); } } { ScopedTimer copy(&copy_timer_); for (size_t iw = 0; iw < nw; iw++) { auto& dt = static_cast<SoaDistanceTableABOMPTarget&>(dt_list[iw].get()); auto* pool_ptr = dt.r_dr_memorypool_.data(); #pragma omp target update from(pool_ptr[:dt.r_dr_memorypool_.size()]) nowait depend(inout:total_targets) } #pragma omp taskwait } } /** this function implements mw_evaluate. * After offloading the computation of distances and displacements, the result for all the walkers is transferred back together in one shot * and then copied to per-walker data structure. Memory copy on the CPU is still costly and not beneficial for large problem size with a few walkers. */ inline void mw_evaluate_fuse_transfer(const RefVector<DistanceTableData>& dt_list, const RefVector<ParticleSet>& p_list) { const size_t nw = dt_list.size(); size_t count_targets = 0; for (ParticleSet& p: p_list) count_targets += p.getTotalNum(); const size_t total_targets = count_targets; // This is horrible optimization putting different data types in a single buffer but allows a single H2D transfer const size_t realtype_size = sizeof(RealType); const size_t int_size = sizeof(int); const size_t ptr_size = sizeof(RealType*); offload_input.resize(total_targets * D * realtype_size + total_targets * int_size + nw * ptr_size); auto target_positions = reinterpret_cast<RealType*>(offload_input.data()); auto walker_id_ptr = reinterpret_cast<int*>(offload_input.data() + total_targets * D * realtype_size); auto source_ptrs = reinterpret_cast<RealType**>(offload_input.data() + total_targets * D * realtype_size + total_targets * int_size); particle_id.resize(total_targets); const int N_sources_padded = getAlignedSize<T>(N_sources); offload_output.resize(total_targets * N_sources_padded * (D + 1)); count_targets = 0; for (size_t iw = 0; iw < nw; iw++) { auto& dt = static_cast<SoaDistanceTableABOMPTarget&>(dt_list[iw].get()); ParticleSet& pset(p_list[iw]); assert(N_sources == dt.N_sources); auto& RSoA_OMPTarget = static_cast<const RealSpacePositionsOMPTarget&>(dt.Origin->getCoordinates()); source_ptrs[iw] = const_cast<RealType*>(RSoA_OMPTarget.getDevicePtr()); for (size_t iat = 0; iat < pset.getTotalNum(); ++iat, ++count_targets) { for (size_t idim = 0; idim < D; idim++) target_positions[count_targets * D + idim] = pset.R[iat][idim]; walker_id_ptr[count_targets] = iw; particle_id[count_targets] = iat; } } const int N_sources_local = N_sources; // To maximize thread usage, the loop over electrons is chunked. Each chunk is sent to an OpenMP offload thread team. const int ChunkSizePerTeam = 256; const int num_teams = (N_sources + ChunkSizePerTeam - 1) / ChunkSizePerTeam; auto* r_dr_ptr = offload_output.data(); auto* input_ptr = offload_input.data(); { ScopedTimer offload(&offload_timer_); #pragma omp target teams distribute collapse(2) num_teams(total_targets*num_teams) \ map(always, to: input_ptr[:offload_input.size()]) \ map(always, from: r_dr_ptr[:offload_output.size()]) for (int iat = 0; iat < total_targets; ++iat) for (int team_id = 0; team_id < num_teams; team_id++) { auto* target_pos_ptr = reinterpret_cast<RealType*>(input_ptr); const int walker_id = reinterpret_cast<int*>(input_ptr + total_targets * D * realtype_size)[iat]; auto* source_pos_ptr = reinterpret_cast<RealType**>(input_ptr + total_targets * D * realtype_size + total_targets * int_size)[walker_id]; auto* r_iat_ptr = r_dr_ptr + iat * N_sources_padded * (D + 1); auto* dr_iat_ptr = r_dr_ptr + iat * N_sources_padded * (D + 1) + N_sources_padded; const int first = ChunkSizePerTeam * team_id; const int last = (first + ChunkSizePerTeam) > N_sources_local ? N_sources_local : first + ChunkSizePerTeam; T pos[D]; for (int idim = 0; idim < D; idim++) pos[idim] = target_pos_ptr[iat * D + idim]; DTD_BConds<T, D, SC>::computeDistancesOffload(pos, source_pos_ptr, r_iat_ptr, dr_iat_ptr, N_sources_padded, first, last); } } { ScopedTimer copy(&copy_timer_); for (size_t iat = 0; iat < total_targets; iat++) { const int wid = walker_id_ptr[iat]; const int pid = particle_id[iat]; auto& dt = static_cast<SoaDistanceTableABOMPTarget&>(dt_list[wid].get()); assert(N_sources_padded == dt.displacements_[pid].capacity()); auto offset = offload_output.data() + iat * N_sources_padded * (D + 1); std::copy_n(offset, N_sources_padded, dt.distances_[pid].data()); std::copy_n(offset + N_sources_padded, N_sources_padded * D, dt.displacements_[pid].data()); } } } ///evaluate the temporary pair relations inline void move(const ParticleSet& P, const PosType& rnew, const IndexType iat, bool prepare_old) { DTD_BConds<T, D, SC>::computeDistances(rnew, Origin->getCoordinates().getAllParticlePos(), temp_r_.data(), temp_dr_, 0, N_sources); // If the full table is not ready all the time, overwrite the current value. // If this step is missing, DT values can be undefined in case a move is rejected. if (!need_full_table_) DTD_BConds<T, D, SC>::computeDistances(P.R[iat], Origin->getCoordinates().getAllParticlePos(), distances_[iat].data(), displacements_[iat], 0, N_sources); } ///update the stripe for jat-th particle inline void update(IndexType iat, bool partial_update) { std::copy_n(temp_r_.data(), N_sources, distances_[iat].data()); for (int idim = 0; idim < D; ++idim) std::copy_n(temp_dr_.data(idim), N_sources, displacements_[iat].data(idim)); } size_t get_neighbors(int iat, RealType rcut, int* restrict jid, RealType* restrict dist, PosType* restrict displ) const { constexpr T cminus(-1); size_t nn = 0; for (int jat = 0; jat < N_targets; ++jat) { const RealType rij = distances_[jat][iat]; if (rij < rcut) { //make the compact list jid[nn] = jat; dist[nn] = rij; displ[nn] = cminus * displacements_[jat][iat]; nn++; } } return nn; } int get_first_neighbor(IndexType iat, RealType& r, PosType& dr, bool newpos) const { RealType min_dist = std::numeric_limits<RealType>::max(); int index = -1; if (newpos) { for (int jat = 0; jat < N_sources; ++jat) if (temp_r_[jat] < min_dist) { min_dist = temp_r_[jat]; index = jat; } if (index >= 0) { r = min_dist; dr = temp_dr_[index]; } } else { for (int jat = 0; jat < N_sources; ++jat) if (distances_[iat][jat] < min_dist) { min_dist = distances_[iat][jat]; index = jat; } if (index >= 0) { r = min_dist; dr = displacements_[iat][index]; } } return index; } size_t get_neighbors(int iat, RealType rcut, RealType* restrict dist) const { size_t nn = 0; for (int jat = 0; jat < N_targets; ++jat) { const RealType rij = distances_[jat][iat]; if (rij < rcut) { //make the compact list dist[nn] = rij; nn++; } } return nn; } }; } // namespace qmcplusplus #endif
GB_binop__ne_fc64.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__ne_fc64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__ne_fc64) // A.*B function (eWiseMult): GB (_AemultB_03__ne_fc64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_fc64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((node)) // C+=B function (dense accum): GB (_Cdense_accumB__ne_fc64) // C+=b function (dense accum): GB (_Cdense_accumb__ne_fc64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_fc64) // C=scalar+B GB (_bind1st__ne_fc64) // C=scalar+B' GB (_bind1st_tran__ne_fc64) // C=A+scalar GB (_bind2nd__ne_fc64) // C=A'+scalar GB (_bind2nd_tran__ne_fc64) // C type: bool // A type: GxB_FC64_t // B,b type: GxB_FC64_t // BinaryOp: cij = GB_FC64_ne (aij, bij) #define GB_ATYPE \ GxB_FC64_t #define GB_BTYPE \ GxB_FC64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = (creal (Ax [pA]) != 0) || (cimag (Ax [pA]) != 0) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = (creal (Bx [pB]) != 0) || (cimag (Bx [pB]) != 0) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_FC64_ne (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_NE || GxB_NO_FC64 || GxB_NO_NE_FC64) //------------------------------------------------------------------------------ // 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__ne_fc64) ( 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__ne_fc64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ne_fc64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type GxB_FC64_t GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #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 bool *restrict Cx = (bool *) 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 bool *restrict Cx = (bool *) 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__ne_fc64) ( 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__ne_fc64) ( 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__ne_fc64) ( 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__ne_fc64) ( 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__ne_fc64) ( 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__ne_fc64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ; GxB_FC64_t *Bx = (GxB_FC64_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 ; GxB_FC64_t bij = Bx [p] ; Cx [p] = GB_FC64_ne (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ne_fc64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ; GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC64_t aij = Ax [p] ; Cx [p] = GB_FC64_ne (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) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_ne (x, aij) ; \ } GrB_Info GB (_bind1st_tran__ne_fc64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_ne (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__ne_fc64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__isge_int64.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__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_08__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_02__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_04__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_int64) // A*D function (colscale): GB (_AxD__isge_int64) // D*A function (rowscale): GB (_DxB__isge_int64) // C+=B function (dense accum): GB (_Cdense_accumB__isge_int64) // C+=b function (dense accum): GB (_Cdense_accumb__isge_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_int64) // C=scalar+B GB (_bind1st__isge_int64) // C=scalar+B' GB (_bind1st_tran__isge_int64) // C=A+scalar GB (_bind2nd__isge_int64) // C=A'+scalar GB (_bind2nd_tran__isge_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // 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) // 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) \ int64_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) \ 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_ISGE || GxB_NO_INT64 || GxB_NO_ISGE_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isge_int64) ( 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__isge_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__isge_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__isge_int64) ( 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 int64_t *restrict Cx = (int64_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__isge_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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 } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isge_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 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) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_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__isge_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__isge_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__isge_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__isge_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__isge_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__isge_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__isge_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__isge_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
64.h
/* This file is part of Primer Pooler (c) Silas S. Brown. For Wen. 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. */ /* Anything in sixty four dot h calls sixty four bit funcs and 128.h is auto-generated: rplace w.128 throughout (similarly for 32.h for 32-bit architectures). These files should be included ONLY by bit-common.h. The general interface is in all-primers.h. */ typedef struct { bit64 AorT, GorT, valid; } Primer64; typedef struct { bit64 MaybeA, MaybeC, MaybeG, MaybeT; } DegeneratePrimer64; /* more than one possibility for each base */ typedef struct { union { DegeneratePrimer64 D; Primer64 notD; } p; int isD; } MaybeDegeneratePrimer64; static MaybeDegeneratePrimer64 wrapPrimer64(Primer64 p) { MaybeDegeneratePrimer64 r; r.p.notD = p; r.isD = 0; return r; } static MaybeDegeneratePrimer64 wrapDegeneratePrimer64(DegeneratePrimer64 p) { MaybeDegeneratePrimer64 r; r.p.D = p; r.isD = 1; return r; } static inline DegeneratePrimer64 upgradeToDegenerate64(MaybeDegeneratePrimer64 p) { if(p.isD) return p.p.D; DegeneratePrimer64 d; Primer64 notD = p.p.notD; d.MaybeA = notD.valid & notD.AorT & ~notD.GorT; d.MaybeC = notD.valid & ~(notD.AorT | notD.GorT); d.MaybeG = notD.valid & ~notD.AorT & notD.GorT; d.MaybeT = notD.valid & notD.AorT & notD.GorT; return d; } static inline bit64 DegenerateValid64(DegeneratePrimer64 p) { /* returns the valid bits of p (we could store this separately, but it's redundant, and might be better pay-off to keep things small and cacheable) */ return p.MaybeA | p.MaybeC | p.MaybeG | p.MaybeT; } static Primer64 parsePrimer64(const char *ACGT) { Primer64 r={0,0,0}; while(1) { char l=fast_toUpper(*ACGT++); if(!l) return r; if(strchr("AGCT",l)) { r.AorT = (r.AorT<<1) | (l=='A'||l=='T'); r.GorT = (r.GorT<<1) | (l=='G'||l=='T'); r.valid = (r.valid<<1) | 1; } else reportUnrecognisedBase(l); } } static DegeneratePrimer64 parseDegeneratePrimer64(const char *ABC) { DegeneratePrimer64 r={0,0,0,0}; while(1) { char l=fast_toUpper(*ABC++); if(!l) return r; const char *combo = strchr(degenerateCombos,l); if(combo) { int c=combo-degenerateCombos + 1; r.MaybeA = (r.MaybeA<<1) | ((c&8)!=0); r.MaybeC = (r.MaybeC<<1) | ((c&4)!=0); r.MaybeG = (r.MaybeG<<1) | ((c&2)!=0); r.MaybeT = (r.MaybeT<<1) | ((c&1)!=0); } else reportUnrecognisedBase(l); } } static MaybeDegeneratePrimer64 parseMaybeDegeneratePrimer64(const char *ABC) { size_t l=strcspn(ABC,"BDHKMNRSVWYbdhkmnrsvwy"); if(ABC[l]) return wrapDegeneratePrimer64(parseDegeneratePrimer64(ABC)); else return wrapPrimer64(parsePrimer64(ABC)); } static inline void PrimerComplement64(Primer64 *p) { // A->T, T->A, C->G, G->C. So AorT stays, GorT flipped. p->GorT = ~(p->GorT); } static inline void PrimerComplement64D(DegeneratePrimer64 *p) { bit64 tmp=p->MaybeA; p->MaybeA=p->MaybeT; p->MaybeT=tmp; tmp=p->MaybeG; p->MaybeG=p->MaybeC; p->MaybeC=tmp; } static inline void PrimerComplement64MaybeD(MaybeDegeneratePrimer64 *p) { if(p->isD) PrimerComplement64D(&(p->p.D)); else PrimerComplement64(&(p->p.notD)); } static int NumPossibilities64D_32bases(DegeneratePrimer64 d) { /* number of possible primers this degenerate primer might be equal to (assumes aligned right) */ int r = 1, sR, poss; for(sR=0; sR<32; sR++) { /* 32, not sixty four etc, because we want the return value to work with Make2bitFrom64D */ poss = ((d.MaybeA >> sR) & 1) + ((d.MaybeC >> sR) & 1) + ((d.MaybeG >> sR) & 1) + ((d.MaybeT >> sR) & 1); if (poss) r *= poss; else break; } return r; } static int NumPossibilities64MaybeD_32bases(MaybeDegeneratePrimer64 d) { if(d.isD) return NumPossibilities64D_32bases(d.p.D); else return 1; } static int Make2bitFrom64D(DegeneratePrimer64 d,ULL *out,ULL *outValid,int possNo,int nPoss) { /* note: ULL across all 3 .h variants - more than 32 bases here will be truncated (return value is 1 if it got truncated). TODO: we could make a "not degenerate" version of this which just shifts bits around, but I'd be very surprised if this function is anywhere near the top of a profile trace, so for now I'll leave it as you have to call upgradeToDegenerate64 from the Maybe. Note: for ease of binary search (see amplicons.c), bases are shifted in from the LEFT (not from the right as in the other functions), and the result reads backwards from the 'end' cursor at left. */ int sR, poss; ULL toOut=0,toOutValid=0; for(sR=0; sR<32; sR++) { /* 32, not sixty four etc */ int MaybeA = ((d.MaybeA >> sR) & 1), MaybeC = ((d.MaybeC >> sR) & 1), MaybeG = ((d.MaybeG >> sR) & 1), MaybeT = ((d.MaybeT >> sR) & 1); poss = MaybeA + MaybeC + MaybeG + MaybeT; if (poss) { int partitionSize = nPoss / poss; int possToTake = possNo / partitionSize; possNo %= partitionSize; nPoss /= poss; ULL bits = 0; /* we set it to a value to stop the "might be uninitialised" warning */ if (MaybeT) possToTake--; /* if(!possToTake--) bits=0; but it's at 0 anyway */ if (MaybeC && !possToTake--) bits=1; if (MaybeA && !possToTake--) bits=2; if (MaybeG && !possToTake) bits=3; int sL = 62-2*sR; /* IMPORTANT: don't write (64-2) as it'll be changed to 32-2 in 32.h; this is ULL */ toOut |= (bits << sL); toOutValid |= ((ULL)3 << sL); } else break; } *out=toOut; *outValid = toOutValid; #define Is_64bit /* will change to Is_32bit in 32.h */ #ifdef Is_32bit return 0; // avoid compiler warnings #else return ((d.MaybeA >> 32) | (d.MaybeC >> 32) | (d.MaybeG >> 32) | (d.MaybeT >> 32)) != 0; #endif } static inline Primer64 PrimerReverse64(Primer64 p) { /* assumes 'valid' is right-aligned */ bit64 v=p.valid,i1=p.AorT,i2=p.GorT,o1=0,o2=0; while(v) { o1=(o1<<1)|(i1&1); o2=(o2<<1)|(i2&1); i1>>=1; i2>>=1; v>>=1; } p.AorT = o1; p.GorT = o2; return p; } static inline DegeneratePrimer64 DegeneratePrimerReverse64(DegeneratePrimer64 p) { /* assumes right-aligned */ bit64 i1=p.MaybeA, i2=p.MaybeC, i3=p.MaybeG, i4=p.MaybeT, o1=0, o2=0, o3=0, o4=0; while(i1 || i2 || i3 || i4) { o1=(o1<<1)|(i1&1); o2=(o2<<1)|(i2&1); o3=(o3<<1)|(i3&1); o4=(o4<<1)|(i4&1); i1>>=1; i2>>=1; i3>>=1; i4>>=1; } p.MaybeA = o1; p.MaybeC = o2; p.MaybeG = o3; p.MaybeT = o4; return p; } static inline MaybeDegeneratePrimer64 MaybeDegeneratePrimerReverse64(MaybeDegeneratePrimer64 p) { if(p.isD) return wrapDegeneratePrimer64(DegeneratePrimerReverse64(p.p.D)); else return wrapPrimer64(PrimerReverse64(p.p.notD)); } static inline void PrimerTag64(Primer64 *p,Primer64 tag) { /* assumes 'valid' is right-aligned in both p and tag */ int sL = popcount64(p->valid); /* = 64-leading0_64 */ p->valid |= (tag.valid << sL); p->AorT |= (tag.AorT << sL); p->GorT|=(tag.GorT << sL); } static inline void DegeneratePrimerTag64(DegeneratePrimer64 *p,DegeneratePrimer64 tag) { int sL = popcount64(p->MaybeA | p->MaybeC | p->MaybeG | p->MaybeT); p->MaybeA |= (tag.MaybeA << sL); p->MaybeC |= (tag.MaybeC << sL); p->MaybeG |= (tag.MaybeG << sL); p->MaybeT |= (tag.MaybeT << sL); } static inline void MaybeDegeneratePrimerTag64(MaybeDegeneratePrimer64 *p,MaybeDegeneratePrimer64 tag) { if (tag.isD && !(p->isD)) { /* a degenerate tag (is this possible? well if it is, we're ready...) */ p->p.D = upgradeToDegenerate64(*p); p->isD = 1; } if(p->isD) DegeneratePrimerTag64(&(p->p.D),upgradeToDegenerate64(tag)); else PrimerTag64(&(p->p.notD),tag.p.notD); } static inline void PrimerTag64B(Primer64 *p,Primer64 tag) { /* for backward primers: reverse the tag first, and add it to the lsb of the primer rather than the msb */ tag = PrimerReverse64(tag); int sL = popcount64(tag.valid); p->valid = ((p->valid) << sL) | tag.valid; p->AorT = ((p->AorT) << sL) | tag.AorT; p->GorT = ((p->GorT) << sL) | tag.GorT; } static inline void DegeneratePrimerTag64B(DegeneratePrimer64 *p,DegeneratePrimer64 tag) { tag = DegeneratePrimerReverse64(tag); int sL = popcount64(tag.MaybeA | tag.MaybeC | tag.MaybeG | tag.MaybeT); p->MaybeA = ((p->MaybeA) << sL) | tag.MaybeA; p->MaybeC = ((p->MaybeC) << sL) | tag.MaybeC; p->MaybeG = ((p->MaybeG) << sL) | tag.MaybeG; p->MaybeT = ((p->MaybeT) << sL) | tag.MaybeT; } static inline void MaybeDegeneratePrimerTag64B(MaybeDegeneratePrimer64 *p,MaybeDegeneratePrimer64 tag) { if (tag.isD && !(p->isD)) { p->p.D = upgradeToDegenerate64(*p); p->isD = 1; } if(p->isD) DegeneratePrimerTag64B(&(p->p.D),upgradeToDegenerate64(tag)); else PrimerTag64B(&(p->p.notD),tag.p.notD); } static inline void PrimerRmTag64(Primer64 *p,Primer64 tag) { int toRM = popcount64(tag.valid); bit64 mask = ~(tag.valid << (popcount64(p->valid) - toRM)); p->valid &= mask; p->AorT &= mask; p->GorT &= mask; } static inline void DegeneratePrimerRmTag64(DegeneratePrimer64 *p,DegeneratePrimer64 tag) { bit64 tValid = tag.MaybeA | tag.MaybeC | tag.MaybeG | tag.MaybeT, pValid = p->MaybeA | p->MaybeC | p->MaybeG | p->MaybeT; int toRM = popcount64(tValid); bit64 mask = ~(tValid << (popcount64(pValid) - toRM)); p->MaybeA &= mask; p->MaybeC &= mask; p->MaybeG &= mask; p->MaybeT &= mask; } static inline void MaybeDegeneratePrimerRmTag64(MaybeDegeneratePrimer64 *p,MaybeDegeneratePrimer64 tag) { if (tag.isD && !(p->isD)) { p->p.D = upgradeToDegenerate64(*p); p->isD = 1; } if(p->isD) DegeneratePrimerRmTag64(&(p->p.D),upgradeToDegenerate64(tag)); else PrimerRmTag64(&(p->p.notD),tag.p.notD); } static inline void PrimerRmTag64B(Primer64 *p,Primer64 tag) { int sR = popcount64(tag.valid); p->valid >>= sR; p->AorT >>= sR; p->GorT >>= sR; } static inline void DegeneratePrimerRmTag64B(DegeneratePrimer64 *p,DegeneratePrimer64 tag) { int sR = popcount64(tag.MaybeA | tag.MaybeC | tag.MaybeG | tag.MaybeT); p->MaybeA >>= sR; p->MaybeC >>= sR; p->MaybeG >>= sR; p->MaybeT >>= sR; } static inline void MaybeDegeneratePrimerRmTag64B(MaybeDegeneratePrimer64 *p,MaybeDegeneratePrimer64 tag) { if (tag.isD && !(p->isD)) { p->p.D = upgradeToDegenerate64(*p); p->isD = 1; } if(p->isD) DegeneratePrimerRmTag64B(&(p->p.D),upgradeToDegenerate64(tag)); else PrimerRmTag64B(&(p->p.notD),tag.p.notD); } static inline int score64(Primer64 p1,Primer64 p2) { /* score the interaction between p1 and p2, fast. p2 must have been PrimerReverse64'd by the caller. */ int sL=(64 - 1/*threshold*/) - leading0_64(p2.valid), maxScore = 0; /* this initial value of maxScore is also the minimum score that can be returned. Do not make it negative without reviewing code that assumes it's >=0 */ Primer64 p1B; /* we start with p1 shifted left */ p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; int reload = sL - leading0_64(p1.valid); if(reload<0) reload=0; /* TODO: if rewritten into 2 loops, can reload only once: load in the middle, shift to the right until gone, reload in the middle <<1, while overlap test + shift left. Of course if the above reload <= 0 then do just the 1 loop as below because it'll be faster in that case. */ while(1) { bit64 overlap = p1B.valid & p2.valid; if(!overlap) return maxScore; /* all done */ bit64 bonds = (~(p1B.AorT ^ p2.AorT)) & (p1B.GorT ^ p2.GorT) & overlap; int score = 2*popcount64(bonds) - popcount64(overlap); maxScore = (score > maxScore ? score : maxScore); if(reload) { --sL; p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; --reload; } else { p1B.AorT >>=1; p1B.GorT >>=1; p1B.valid >>=1; } } } static inline int score64D(DegeneratePrimer64 p1,DegeneratePrimer64 p2) { bit64 p1Valid = DegenerateValid64(p1), p2Valid = DegenerateValid64(p2); int sL=(64 - 1/*threshold*/) - leading0_64(p2Valid), maxScore = 0; DegeneratePrimer64 p1B; p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; bit64 p1Bvalid = p1Valid << sL; int reload = sL - leading0_64(p1Valid); if(reload<0) reload=0; while(1) { bit64 overlap = p1Bvalid & p2Valid; if(!overlap) return maxScore; bit64 bonds = (p1B.MaybeA & p2.MaybeT) | (p1B.MaybeC & p2.MaybeG) | (p1B.MaybeG & p2.MaybeC) | (p1B.MaybeT & p2.MaybeA); int score = 2*popcount64(bonds) - popcount64(overlap); maxScore = (score > maxScore ? score : maxScore); if(reload) { --sL; p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; p1Bvalid = p1Valid << sL; --reload; } else { p1B.MaybeA >>=1; p1B.MaybeC >>=1; p1B.MaybeG >>=1; p1B.MaybeT >>=1; p1Bvalid >>=1; } } } static inline int score64MaybeD(MaybeDegeneratePrimer64 p1,MaybeDegeneratePrimer64 p2) { if(p1.isD || p2.isD) return score64D(upgradeToDegenerate64(p1),upgradeToDegenerate64(p2)); else return score64(p1.p.notD,p2.p.notD); } static inline int count64(Primer64 p1,Primer64 p2, int *tried) { /* count the number of alignments of >0 bonds, for information only. Similar to score64, but called only when outputting interaction data. (TODO: could make this return maxScore or minDG as well, to save having to call that func separately, but low priority because this is called only when printing out bonds in excess of threshold) */ int sL=(64 - 1/*threshold*/) - leading0_64(p2.valid), count = 0; Primer64 p1B; /* we start with p1 shifted left */ p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; int reload = sL - leading0_64(p1.valid); if(reload<0) reload=0; while(1) { bit64 overlap = p1B.valid & p2.valid; if(!overlap) return count; (*tried)++; if((~(p1B.AorT ^ p2.AorT)) & (p1B.GorT ^ p2.GorT) & overlap) count++; if(reload) { --sL; p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; --reload; } else { p1B.AorT >>=1; p1B.GorT >>=1; p1B.valid >>=1; } } } static inline int count64D(DegeneratePrimer64 p1,DegeneratePrimer64 p2,int *tried) { bit64 p1Valid = DegenerateValid64(p1), p2Valid = DegenerateValid64(p2); int sL=(64 - 1/*threshold*/) - leading0_64(p2Valid), count = 0; DegeneratePrimer64 p1B; p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; bit64 p1Bvalid = p1Valid << sL; int reload = sL - leading0_64(p1Valid); if(reload<0) reload=0; while(1) { bit64 overlap = p1Bvalid & p2Valid; if(!overlap) return count; (*tried)++; if ((p1B.MaybeA & p2.MaybeT) | (p1B.MaybeC & p2.MaybeG) | (p1B.MaybeG & p2.MaybeC) | (p1B.MaybeT & p2.MaybeA)) count++; if(reload) { --sL; p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; p1Bvalid = p1Valid << sL; --reload; } else { p1B.MaybeA >>=1; p1B.MaybeC >>=1; p1B.MaybeG >>=1; p1B.MaybeT >>=1; p1Bvalid >>=1; } } } static inline void count64MaybeD(MaybeDegeneratePrimer64 p1,MaybeDegeneratePrimer64 p2,FILE *f) { /* Put clarification for any beginner users who haven't been informed that we automatically try all positions and print only the worst case */ int tried = 0; int c = ((p1.isD || p2.isD) ? count64D(upgradeToDegenerate64(p1),upgradeToDegenerate64(p2),&tried) : count64(p1.p.notD,p2.p.notD,&tried)); fprintf(f,"Positions tried: %d\nBonding positions: %d%s\n",tried,c,(c>1)?" (worst one shown here)":""); } static void printBases64(Primer64 p,FILE *f) { bit64 i = (bit64)1 << (64-1-leading0_64(p.valid)); for(; i&p.valid; i>>=1) fputc( (p.AorT & i) ? ((p.GorT & i)?'T':'A') : ((p.GorT & i)?'G':'C'), f); } static void printBases64D(DegeneratePrimer64 p,FILE *f) { bit64 valid = DegenerateValid64(p); bit64 i = (bit64)1 << (64-1-leading0_64(valid)); for(; i&valid; i>>=1) { int j = (((p.MaybeA & i)!=0)<<3) | (((p.MaybeC & i)!=0)<<2) | (((p.MaybeG & i)!=0)<<1) | ((p.MaybeT & i)!=0); fputc(degenerateCombos[j-1],f); } } static void printBases64MaybeD(MaybeDegeneratePrimer64 p,FILE *f) { if(p.isD) printBases64D(p.p.D,f); else printBases64(p.p.notD,f); } static void print64_inner(Primer64 p1,int sL,Primer64 p2,bit64 overlap,bit64 bonds,FILE* f) { /* code common to print64 and dGprint64 */ int i1 = leading0_64(p1.valid)-sL, i2 = leading0_64(p2.valid), iMid = leading0_64(overlap); if(i1<i2) { i2-=i1; iMid-=i1; i1=0; } else { i1-=i2; iMid-=i2; i2=0; } indent(i1,f); fputs("5'-",f); printBases64(p1,f); fputs("-3'\n",f); indent(iMid+(sizeof("5'-")-1), f); bit64 bond = (bit64)1 << (64-1-leading0_64(overlap)); for(; bond&overlap; bond>>=1) fputc((bond&bonds)?'|':'x',f); fputc('\n',f); indent(i2,f); fputs("3'-",f); printBases64(p2,f);fputs("-5'\n",f); } static void print64D_inner(DegeneratePrimer64 p1,int sL,DegeneratePrimer64 p2,bit64 overlap,bit64 bonds,FILE* f) { int i1 = leading0_64(DegenerateValid64(p1))-sL, i2 = leading0_64(DegenerateValid64(p2)), iMid = leading0_64(overlap); if(i1<i2) { i2-=i1; iMid-=i1; i1=0; } else { i1-=i2; iMid-=i2; i2=0; } indent(i1,f); fputs("5'-",f); printBases64D(p1,f); fputs("-3'\n",f); indent(iMid+(sizeof("5'-")-1), f); bit64 bond = (bit64)1 << (64-1-leading0_64(overlap)); for(; bond&overlap; bond>>=1) fputc((bond&bonds)?'|':'x',f); fputc('\n',f); indent(i2,f); fputs("3'-",f); printBases64D(p2,f); fputs("-5'\n",f); } static void print64(Primer64 p1,Primer64 p2,int maxScore,FILE *f) { /* maxScore has been found by score64; print a representation of the interaction, along with the score */ int sL=(64 - 1) - leading0_64(p2.valid); int sR = 0; Primer64 p1B; while(1) { if(sL) { p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; } else { /* this function is allowed to be a bit slower than score64, and we need to keep all bits */ p1B.AorT = p1.AorT >> sR; p1B.GorT = p1.GorT >> sR; p1B.valid = p1.valid >> sR; } bit64 overlap = p1B.valid & p2.valid; bit64 bonds = (~(p1B.AorT ^ p2.AorT)) & (p1B.GorT ^ p2.GorT) & overlap; int score = 2*popcount64(bonds) - popcount64(overlap); if(score == maxScore) { /* TODO: if more than one ==maxScore, prioritise any that has more C-G links, stronger than A-T */ fprintf(f,"Matches = %d\n",popcount64(bonds)); fprintf(f,"Score = %d\n",maxScore); print64_inner(p1,sL-sR,p2,overlap,bonds,f); //return; /* comment out to print ALL maxScore matches */ } if(!overlap) return; /* needed if not returning above */ if(sL) sL--; else sR++; } } static void print64D(DegeneratePrimer64 p1,DegeneratePrimer64 p2,int maxScore,FILE *f) { int sL=(64 - 1) - leading0_64(DegenerateValid64(p2)); int sR = 0; DegeneratePrimer64 p1B; while(1) { if(sL) { p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; } else { p1B.MaybeA = p1.MaybeA >> sR; p1B.MaybeC = p1.MaybeC >> sR; p1B.MaybeG = p1.MaybeG >> sR; p1B.MaybeT = p1.MaybeT >> sR; } bit64 overlap = DegenerateValid64(p1B) & DegenerateValid64(p2); bit64 bonds = (p1B.MaybeA & p2.MaybeT) | (p1B.MaybeC & p2.MaybeG) | (p1B.MaybeG & p2.MaybeC) | (p1B.MaybeT & p2.MaybeA); int score = 2*popcount64(bonds) - popcount64(overlap); if(score == maxScore) { /* TODO: if more than one ==maxScore, how to prioritise the links in the degenerate case? */ fprintf(f,"Matches = %d\n",popcount64(bonds)); fprintf(f,"Score = %d\n",maxScore); print64D_inner(p1,sL-sR,p2,overlap,bonds,f); //return; /* comment out to print ALL maxScore matches */ } if(!overlap) return; /* needed if not returning above */ if(sL) sL--; else sR++; } } static void print64MaybeD(MaybeDegeneratePrimer64 p1,MaybeDegeneratePrimer64 p2,const char *name1,const char *name2,int maxScore,FILE *f) { if(!name1 || !*name1) name1="(no name)"; if(!name2 || !*name2) name2="(no name)"; fprintf(f,"%s versus %s\n",name1,name2); count64MaybeD(p1,p2,f); if(p1.isD || p2.isD) print64D(upgradeToDegenerate64(p1),upgradeToDegenerate64(p2),maxScore,f); else print64(p1.p.notD,p2.p.notD,maxScore,f); fputc('\n',f); } static void parseFASTA64(char *fileData,MaybeDegeneratePrimer64 *buf,MaybeDegeneratePrimer64 *tags,int *whichTag,char* *names) { /* (note: adds extra 0 bytes to fileData) */ char *seqName=NULL; int p=0; int lastByte_to_whichTag[256]; memset(&lastByte_to_whichTag,0xFF,sizeof(lastByte_to_whichTag)); char check_not_last[256]={0}; int nextTag = 0; fileData += strspn(fileData,"\r\n\xef\xbb\xbf"); while(*fileData) { size_t lineEnd,start=0; do { // multiline seq? lineEnd = strcspn(fileData+start,"\r\n\xef\xbb\xbf") + start; /* see comment in load-common.c re stray BOMs */ start = strspn(fileData+lineEnd,"\r\n\xef\xbb\xbf") + lineEnd; } while(*fileData!='>' && fileData[start] && fileData[start]!='>'); char o=fileData[lineEnd]; if (*fileData == '>') { seqName = fileData+1; while(*seqName==' ') seqName++; /* ignore spaces between > and label */ while(fileData[--lineEnd]==' '); /* and after end of label */ fileData[++lineEnd]=0; } else if (lineEnd) { fileData[lineEnd] = 0; MaybeDegeneratePrimer64 mdp = parseMaybeDegeneratePrimer64(fileData); if(!strncmp(seqName,"tag",3) && strlen(seqName)==4){ unsigned char tagType=fast_toUpper(seqName[3]); if (lastByte_to_whichTag[tagType] == -1) { /* This tag type hasn't been set before, so retroactively apply it to previous primers */ int p2; for(p2=0; p2<p; p2++) if(tagType==(unsigned char)fast_toUpper(names[p2][strlen(names[p2])-1])) whichTag[p2] = nextTag; } else check_not_last[tagType] = 1; lastByte_to_whichTag[tagType] = nextTag; tags[nextTag++] = mdp; } else { names[p] = seqName; unsigned char tagType=fast_toUpper(seqName[strlen(seqName)-1]); whichTag[p] = lastByte_to_whichTag[tagType]; check_not_last[tagType] = 0; buf[p++] = mdp; } } fileData += start; if(!o) break; /* no \n at end ?? */ } p = 0; for(nextTag=0; nextTag<256; nextTag++) if(check_not_last[nextTag]) { if(p) fprintf(stderr,"WARNING: Same applies to >tag%c\n",nextTag); else { p = 1; fprintf(stderr,"\nWARNING: You have multiple >tag%c sequences\n and the last one does not precede a >...%c primer.\n This probably means you've made a mistake.\n Apart from the first >tag%c, all >tag%c tags will apply to\n >...%c primers AFTER the >tag%c (not before it).\n",nextTag,nextTag,nextTag,nextTag,nextTag,nextTag); } } } static void counts64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,FILE *f) { int i,j; int counts[64]={0},maxS = 0; for(i=0; i<np; i++) for(j=i; j<np; j++) { int score = score64MaybeD(forward[i],backward[j]); counts[score]++; if(score>maxS) maxS=score; } for(i=0; i<=maxS; i++) fprintf(f,"%d\t%d\n",i,counts[i]); if(f!=stdout) fclose(f); } static int pCounts64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,const int *pools,const int *precalcScores) { /* like counts64 but includes combinations only if they're in the same pool + count invalid/overlap scores */ int i,j; int counts[64]={0},maxS = 0, other=0; for(i=0; i<np; i++) for(j=i; j<np; j++) if(pools[i]==pools[j]) { int score = precalcScores ? *precalcScores++ : score64MaybeD(forward[i],backward[j]); if(score<64) { counts[score]++; if(score>maxS) maxS=score; } else other++; } else if(precalcScores) precalcScores++; int first = 1; for(i=0; i<=maxS; i++) fprintf(stderr,"%s%d\t%d",first?((first=0),""):"\n",i,counts[i]); if(other) fprintf(stderr,"%sOverlaps\t%d",first?"":"\n",other); return other; } static void printBonds64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,FILE *f,int threshold,char* *names,const int *pools) { int i,j; ScoreRecord* sr=malloc(t_Nitems(np)*sizeof(ScoreRecord)); ScoreRecord* sr2 = sr; for(i=0; i<np; i++) for(j=i; j<np; j++) { if(!pools || pools[i]==pools[j]) { int score = score64MaybeD(forward[i],backward[j]); if (score >= threshold) { if(sr) { sr2->score = score; sr2->i = i; (sr2++)->j = j; } else print64MaybeD(forward[i],backward[j],names[i],names[j],score,f); /* fallback: print in any order if can't sort by highest score 1st */ } } } if(sr) { qsort(sr,sr2-sr,sizeof(ScoreRecord),highestScore1st); ScoreRecord *s; for(s=sr; s<sr2; s++) print64MaybeD(forward[s->i],backward[s->j],names[s->i],names[s->j],s->score,f); free(sr); } } static int* triangle64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np) { /* Triangular score cache for pooling purposes */ int* scores = malloc(t_Nitems(np)*sizeof(int)); if(scores) { int i,j,*p=scores; for(i=0; i<np; i++) for(j=i; j<np; j++) *p++ = (i==j ? 0 /* ignore self-interaction */ : score64MaybeD(forward[i],backward[j])); } return scores; } static inline bit64 rm_unstable_bonds64(bit64 bonds,bit64 overlap) { /* MPprimer_dimer_check.pl's "primer_dimer" function does this before its deltaG calculation. Says single matched bases surrounded by mismatches are unstable, removes 01 when not followed by valid 1 */ bit64 lone_1s = bonds & ((~bonds)<<1) & ((~bonds)>>1); lone_1s &= (overlap>>1); /* left-hand bit is never got rid of */ return bonds & ~lone_1s; } static inline float deltaG64(Primer64 p1,Primer64 p2,const float* table) { /* like score64 but does deltaG instead */ int sL=(64 - 1/*threshold*/) - leading0_64(p2.valid); float minDG = INFINITY; Primer64 p1B; p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; int reload = sL - leading0_64(p1.valid); if(reload<0) reload=0; while(1) { bit64 overlap = p1B.valid & p2.valid; if(!overlap) return minDG; bit64 bonds = rm_unstable_bonds64((~(p1B.AorT ^ p2.AorT)) & (p1B.GorT ^ p2.GorT) & overlap, overlap); int shift = 64-2-leading0_64(bonds); bit64 mask=(bit64)3 << shift, maskEnd = (bit64)3 << trail0_64(bonds); float dG = table[256+((p1B.AorT & mask)>>(shift+1))]; // init for(; mask>=maskEnd; mask>>=1,shift--) dG += table[(((p1B.AorT & mask)>>shift)<<6) | (((p1B.GorT & mask)>>shift)<<4) | (((p2.AorT & mask)>>shift)<<2) | ((p2.GorT & mask)>>shift)]; dG += table[256+((p1B.AorT & mask)>>(shift+1))]; // init at end minDG = (dG < minDG ? dG : minDG); if(reload) { --sL; p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; --reload; } else { p1B.AorT >>=1; p1B.GorT >>=1; p1B.valid >>=1; } } } static inline float deltaG64D(DegeneratePrimer64 p1,DegeneratePrimer64 p2,const float* table) { bit64 p1Valid = DegenerateValid64(p1), p2Valid = DegenerateValid64(p2); int sL=(64 - 1/*threshold*/) - leading0_64(p2Valid); float minDG = INFINITY; DegeneratePrimer64 p1B; p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; bit64 p1Bvalid = p1Valid << sL; int reload = sL - leading0_64(p1Valid); if(reload<0) reload=0; while(1) { bit64 overlap = p1Bvalid & p2Valid; if(!overlap) return minDG; bit64 bonds = rm_unstable_bonds64((p1B.MaybeA & p2.MaybeT) | (p1B.MaybeC & p2.MaybeG) | (p1B.MaybeG & p2.MaybeC) | (p1B.MaybeT & p2.MaybeA),overlap); int shift = 64-2-leading0_64(bonds); bit64 mask=(bit64)3 << shift, maskEnd = (bit64)3 << trail0_64(bonds); float dG = table[256+!(((p1B.MaybeC|p1B.MaybeG) & mask)>>(shift+1))]; // init (worst-case scenario is C or G) for(; mask>=maskEnd; mask>>=1,shift--) dG += minDGdegenerate((p1B.MaybeA & mask)>>shift,(p1B.MaybeC & mask)>>shift,(p1B.MaybeG & mask)>>shift,(p1B.MaybeT & mask)>>shift,(p2.MaybeA & mask)>>shift,(p2.MaybeC & mask)>>shift,(p2.MaybeG & mask)>>shift,(p2.MaybeT & mask)>>shift,table); dG += table[256+!(((p1B.MaybeC|p1B.MaybeG) & mask)>>(shift+1))]; minDG = (dG < minDG ? dG : minDG); if(reload) { --sL; p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; p1Bvalid = p1Valid << sL; --reload; } else { p1B.MaybeA >>=1; p1B.MaybeC >>=1; p1B.MaybeG >>=1; p1B.MaybeT >>=1; p1Bvalid >>=1; } } } static inline float deltaG64MaybeD(MaybeDegeneratePrimer64 p1,MaybeDegeneratePrimer64 p2,const float* table) { if(p1.isD || p2.isD) return deltaG64D(upgradeToDegenerate64(p1),upgradeToDegenerate64(p2),table); else return deltaG64(p1.p.notD,p2.p.notD,table); } static void dGprint64(Primer64 p1,Primer64 p2,float minDG,FILE *f,const float *table) { int sL=(64 - 1) - leading0_64(p2.valid); int sR = 0; Primer64 p1B; while(1) { if(sL) { p1B.AorT = p1.AorT << sL; p1B.GorT = p1.GorT << sL; p1B.valid = p1.valid << sL; } else { p1B.AorT = p1.AorT >> sR; p1B.GorT = p1.GorT >> sR; p1B.valid = p1.valid >> sR; assert(p1B.valid); /* if this breaks, check the range of nearlyEqual */ } bit64 overlap = p1B.valid & p2.valid; bit64 bonds0 = (~(p1B.AorT ^ p2.AorT)) & (p1B.GorT ^ p2.GorT) & overlap, bonds = rm_unstable_bonds64(bonds0, overlap); int shift = 64-2-leading0_64(bonds); bit64 mask=(bit64)3 << shift, maskEnd = (bit64)3 << trail0_64(bonds); float dG = table[256+((p1B.AorT & mask)>>(shift+1))]; // init for(; mask>=maskEnd; mask>>=1,shift--) dG += table[(((p1B.AorT & mask)>>shift)<<6) | (((p1B.GorT & mask)>>shift)<<4) | (((p2.AorT & mask)>>shift)<<2) | ((p2.GorT & mask)>>shift)]; dG += table[256+((p1B.AorT & mask)>>(shift+1))]; // init at end if(nearlyEqual(dG,minDG)) { fprintf(f,"dG = %.3g\n",dG); print64_inner(p1,sL-sR,p2,overlap,bonds0,f); return; } if(sL) sL--; else sR++; } } static void dGprint64D(DegeneratePrimer64 p1,DegeneratePrimer64 p2,float minDG,FILE *f,const float *table) { int sL=(64 - 1) - leading0_64(DegenerateValid64(p2)); int sR = 0; DegeneratePrimer64 p1B; while(1) { if(sL) { p1B.MaybeA = p1.MaybeA << sL; p1B.MaybeC = p1.MaybeC << sL; p1B.MaybeG = p1.MaybeG << sL; p1B.MaybeT = p1.MaybeT << sL; } else { p1B.MaybeA = p1.MaybeA >> sR; p1B.MaybeC = p1.MaybeC >> sR; p1B.MaybeG = p1.MaybeG >> sR; p1B.MaybeT = p1.MaybeT >> sR; assert(sR < 64); /* if this breaks, check the range of nearlyEqual */ } bit64 overlap = DegenerateValid64(p1B) & DegenerateValid64(p2); bit64 bonds0 = (p1B.MaybeA & p2.MaybeT) | (p1B.MaybeC & p2.MaybeG) | (p1B.MaybeG & p2.MaybeC) | (p1B.MaybeT & p2.MaybeA), bonds = rm_unstable_bonds64(bonds0,overlap); int shift = 64-2-leading0_64(bonds); bit64 mask=(bit64)3 << shift, maskEnd = (bit64)3 << trail0_64(bonds); float dG = table[256+!(((p1B.MaybeC|p1B.MaybeG) & mask)>>(shift+1))]; // init (worst-case scenario is C or G) for(; mask>=maskEnd; mask>>=1,shift--) dG += minDGdegenerate((p1B.MaybeA & mask)>>shift,(p1B.MaybeC & mask)>>shift,(p1B.MaybeG & mask)>>shift,(p1B.MaybeT & mask)>>shift,(p2.MaybeA & mask)>>shift,(p2.MaybeC & mask)>>shift,(p2.MaybeG & mask)>>shift,(p2.MaybeT & mask)>>shift,table); dG += table[256+!(((p1B.MaybeC|p1B.MaybeG) & mask)>>(shift+1))]; if(nearlyEqual(dG,minDG)) { fprintf(f,"dG = %.3g\n",dG); print64D_inner(p1,sL-sR,p2,overlap,bonds0,f); return; } if(sL) sL--; else sR++; } } static void dGprint64MaybeD(MaybeDegeneratePrimer64 p1,MaybeDegeneratePrimer64 p2,const char *name1,const char *name2,float minDG,FILE *f,const float *table) { if(!name1 || !*name1) name1="(no name)"; if(!name2 || !*name2) name2="(no name)"; fprintf(f,"%s versus %s\n",name1,name2); count64MaybeD(p1,p2,f); if(p1.isD || p2.isD) dGprint64D(upgradeToDegenerate64(p1),upgradeToDegenerate64(p2),minDG,f,table); else dGprint64(p1.p.notD,p2.p.notD,minDG,f,table); fputc('\n',f); } static void dGprintBonds64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,FILE *f,float threshold,char* *names,const int *pools,const float *table) { DG_ScoreRecord* sr=malloc(t_Nitems(np)*sizeof(DG_ScoreRecord)); DG_ScoreRecord* sr2 = sr; time_t start=time(NULL); time_t next = sr?t_ProgressStart("Sorting... "):0; #if defined(_OPENMP) #pragma omp parallel #endif { TwoRanges tr=t_iBounds(np); int r,i,j,done=0; for(r=0; r<2; r++) for(i=tr.r[r].start; i<tr.r[r].end; i++,sr?t_Progress("Sorting... ",tr,np,done,&next):0,done+=np-i) for(j=i; j<np; j++) { if(!pools || pools[i]==pools[j]) { float dG = deltaG64MaybeD(forward[i],backward[j],table); if (dG <= threshold) { #if defined(_OPENMP) #pragma omp critical #endif if(sr) { sr2->dG = dG; sr2->i = i; (sr2++)->j = j; } else dGprint64MaybeD(forward[i],backward[j],names[i],names[j],dG,f,table); } } } } if(sr) { qsort(sr,sr2-sr,sizeof(DG_ScoreRecord),dGhighestScore1st); fputs("\rSorting... done",stderr); prnSeconds((long)(time(NULL)-start)); fputs("\n",stderr); if(f!=stdout) { fputs("Outputting... ",stderr); start = time(NULL); next = start + 2; } fflush(stderr); DG_ScoreRecord *s; for(s=sr; s<sr2; s++) { if(f!=stdout && time(NULL) > next) { fprintf(stderr,"\rOutputting... (%d%%) ",100*(int)(s-sr)/(int)(sr2-sr)); fflush(stderr); next = time(NULL) + 2; } dGprint64MaybeD(forward[s->i],backward[s->j],names[s->i],names[s->j],s->dG,f,table); } free(sr); if(f!=stdout) { fputs("\rOutputting... done",stderr); prnSeconds((long)(time(NULL)-start)); fputs("\n",stderr); fflush(stderr); } } } static int* dGtriangle64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,const float *table) { /* To save doing a float version of the pool splitter, emulate 'score' by using -dG*2, as bins of size 0.5 should be enough (*10 creates too many empty ones and split_into_pools would need changing) */ time_t next = t_ProgressStart("Precalculating dG... "); time_t start = next; int* scores = malloc(t_Nitems(np)*sizeof(int)); if(scores) #if defined(_OPENMP) #pragma omp parallel #endif { TwoRanges tr=t_iBounds(np); int r,i,j,*p,done=0; for(r=0; r<2; r++) for(i=tr.r[r].start, p=scores+t_offset(np,i,i); i<tr.r[r].end; i++,t_Progress("Precalculating dG... ",tr,np,done,&next),done+=np-i) for(j=i; j<np; j++) *p++ = (i==j ? 0 : dGbucket(deltaG64MaybeD(forward[i],backward[j],table),0x4000-1)); } fputs("\rPrecalculating dG... done",stderr); prnSeconds((long)(time(NULL)-start)); fputs("\n",stderr); fflush(stderr); return scores; } static int dGpCounts64(int np,const int *pools,const int *precalcScores,FILE *f) { /* this is a combination of counts64 and pCounts64, for the delta-G variant. pools can be NULL, but not precalcScores */ int i,j; int*counts=calloc(0x4000+1,sizeof(int)); if(!counts) return 0; for(i=0; i<np; i++) for(j=i; j<np; j++) if(!pools || pools[i]==pools[j]) { counts[*precalcScores++]++; /* this version has no precalcScores==NULL fallback; could put one in if don't mind passing around the extra parameters */ } else precalcScores++; int lines=0; for(i=0x4000-1; i>0; i--) if(counts[i] && ++lines==20) break; int first = 1; for(; i<0x4000; i++) if(counts[i]) { fprintf(f,"%s%.3g\t%d",first?((first=0),""):"\n",((float)(-i))/2.0,counts[i]); } int other=counts[0x4000]; free(counts); if(other) fprintf(f,"%sOverlaps\t%d",first?"":"\n",other); if(f!=stdout && f!=stderr) fclose(f); return other; } static void dGsCounts64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,const float *table,FILE *f) { /* show how much the score can vary around a deltaG range (in case anyone thinks it's more accurate than it is) */ int *counts=calloc(0x4000,sizeof(int)), *maxScore=calloc(0x4000,sizeof(int)), *minScore=malloc(0x4000*sizeof(int)); if(memFail(counts,minScore,maxScore,_memFail)) return; memset(minScore,0xFF,0x4000*sizeof(int)); time_t next = t_ProgressStart("Precalculating dG... "); time_t start = next; #if defined(_OPENMP) #pragma omp parallel #endif { TwoRanges tr=t_iBounds(np); int r,i,j,done=0; for(r=0; r<2; r++) for(i=tr.r[r].start; i<tr.r[r].end; i++,t_Progress("Precalculating dG... ",tr,np,done,&next),done+=np-i) for(j=i; j<np; j++) { float dG = deltaG64MaybeD(forward[i],backward[j],table); int score = score64MaybeD(forward[i],backward[j]); int bucket = dGbucket(dG,0x4000-1); #if defined(_OPENMP) #pragma omp critical #endif { counts[bucket]++; if(minScore[bucket]<0 || score<minScore[bucket]) minScore[bucket] = score; if(score>maxScore[bucket]) maxScore[bucket] = score; }}} fputs("\rPrecalculating dG... done",stderr); prnSeconds((long)(time(NULL)-start)); fputs("\n",stderr); fflush(stderr); int i; for(i=0; i<0x4000; i++) if(counts[i]) { fprintf(f,"%c%d.%d\t%d\t (score ",i?'-':' ',i/2,(i%2)?5:0,counts[i]); if(minScore[i]==maxScore[i]) fprintf(f,"%d)\n",minScore[i]); else fprintf(f,"%d-%d)\n",minScore[i],maxScore[i]); } if(f!=stdout && f!=stderr) fclose(f); } static void pStats64(const MaybeDegeneratePrimer64 *forward,const MaybeDegeneratePrimer64 *backward,int np,const int *pools,const int *precalcScores,FILE *f) { /* like pCounts64 but outputs per-pool */ int i,j,nPools=0,pool; for(i=0; i<np; i++) if(pools[i]>nPools) nPools=pools[i]; const int *precalcScores2 = precalcScores; nPools++; /* 1 higher than max */ for(pool=0; pool<nPools; pool++) { fprintf(f,"Pool %d:\n",pool+1); precalcScores = precalcScores2; int counts[64]={0},maxS = 0, other=0; for(i=0; i<np; i++) for(j=i; j<np; j++) if(pools[i]==pools[j] && pools[i]==pool) { int score = precalcScores ? *precalcScores++ : score64MaybeD(forward[i],backward[j]); if(score<64) { counts[score]++; if(score>maxS) maxS=score; } else other++; } else if(precalcScores) precalcScores++; for(i=0; i<=maxS; i++) fprintf(f,"%d\t%d\n",i,counts[i]); if(other) fprintf(f,"Overlaps\t%d\n",other); } if(f!=stdout && f!=stderr) fclose(f); } static void pStats64dG(int np,const int *pools,const int *precalcScores,FILE *f) { int*counts=malloc((0x4000+1)*sizeof(int)); if(memFail(counts,_memFail)) return; int i,j,nPools=0,pool; for(i=0; i<np; i++) if(pools[i]>nPools) nPools=pools[i]; const int *precalcScores2 = precalcScores; nPools++; for(pool=0; pool<nPools; pool++) { fprintf(f,"Pool %d:\n",pool+1); memset(counts,0,(0x4000+1)*sizeof(int)); precalcScores = precalcScores2; for(i=0; i<np; i++) for(j=i; j<np; j++) if(pools[i]==pools[j] && pools[i]==pool) { counts[*precalcScores++]++; } else precalcScores++; int lines=0; for(i=0x4000-1; i>0; i--) if(counts[i] && ++lines==20) break; for(; i<0x4000; i++) if(counts[i]) { fprintf(f,"%.3g\t%d\n",((float)(-i))/2.0,counts[i]); } int other=counts[0x4000]; if(other) fprintf(f,"Overlaps\t%d\n",other); } free(counts); if(f!=stdout && f!=stderr) fclose(f); }
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/DiagnosticSema.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; // TODO SYCL Integration header approach relies on an assumption that kernel // lambda objects created by the host compiler and any of the device compilers // will be identical wrt to field types, order and offsets. Some verification // mechanism should be developed to enforce that. // TODO FIXME SYCL Support for SYCL in FE should be refactored: // - kernel identification and generation should be made a separate pass over // AST. RecursiveASTVisitor + VisitFunctionTemplateDecl + // FunctionTemplateDecl::getSpecializations() mechanism could be used for that. // - All SYCL stuff on Sema level should be encapsulated into a single Sema // field // - Move SYCL stuff into a separate header // Represents contents of a SYCL integration header file produced by a SYCL // device compiler and used by SYCL host compiler (via forced inclusion into // compiled SYCL source): // - SYCL kernel names // - SYCL kernel parameters and offsets of corresponding actual arguments class SYCLIntegrationHeader { public: // Kind of kernel's parameters as captured by the compiler in the // kernel lambda or function object enum kernel_param_kind_t { kind_first, kind_accessor = kind_first, kind_std_layout, kind_sampler, kind_pointer, kind_specialization_constants_buffer, kind_stream, kind_last = kind_stream }; public: SYCLIntegrationHeader(bool UnnamedLambdaSupport, Sema &S); /// Emits contents of the header into given stream. void emit(raw_ostream &Out); /// Emits contents of the header into a file with given name. /// Returns true/false on success/failure. bool emit(StringRef MainSrc); /// Signals that subsequent parameter descriptor additions will go to /// the kernel with given name. Starts new kernel invocation descriptor. void startKernel(StringRef KernelName, QualType KernelNameType, StringRef KernelStableName, SourceLocation Loc, bool IsESIMD); /// Adds a kernel parameter descriptor to current kernel invocation /// descriptor. void addParamDesc(kernel_param_kind_t Kind, int Info, unsigned Offset); /// Signals that addition of parameter descriptors to current kernel /// invocation descriptor has finished. void endKernel(); /// Registers a specialization constant to emit info for it into the header. void addSpecConstant(StringRef IDName, QualType IDType); /// Note which free functions (this_id, this_item, etc) are called within the /// kernel void setCallsThisId(bool B); void setCallsThisItem(bool B); void setCallsThisNDItem(bool B); void setCallsThisGroup(bool B); private: // Kernel actual parameter descriptor. struct KernelParamDesc { // Represents a parameter kind. kernel_param_kind_t Kind = kind_last; // If Kind is kind_scalar or kind_struct, then // denotes parameter size in bytes (includes padding for structs) // If Kind is kind_accessor // denotes access target; possible access targets are defined in // access/access.hpp int Info = 0; // Offset of the captured parameter value in the lambda or function object. unsigned Offset = 0; KernelParamDesc() = default; }; // there are four free functions the kernel may call (this_id, this_item, // this_nd_item, this_group) struct KernelCallsSYCLFreeFunction { bool CallsThisId; bool CallsThisItem; bool CallsThisNDItem; bool CallsThisGroup; }; // Kernel invocation descriptor struct KernelDesc { /// Kernel name. std::string Name; /// Kernel name type. QualType NameType; /// Kernel name with stable lambda name mangling std::string StableName; SourceLocation KernelLocation; /// Whether this kernel is an ESIMD one. bool IsESIMDKernel; /// Descriptor of kernel actual parameters. SmallVector<KernelParamDesc, 8> Params; // Whether kernel calls any of the SYCL free functions (this_item(), // this_id(), etc) KernelCallsSYCLFreeFunction FreeFunctionCalls; KernelDesc() = default; }; /// Returns the latest invocation descriptor started by /// SYCLIntegrationHeader::startKernel KernelDesc *getCurKernelDesc() { return KernelDescs.size() > 0 ? &KernelDescs[KernelDescs.size() - 1] : nullptr; } private: /// Keeps invocation descriptors for each kernel invocation started by /// SYCLIntegrationHeader::startKernel SmallVector<KernelDesc, 4> KernelDescs; using SpecConstID = std::pair<QualType, std::string>; /// Keeps specialization constants met in the translation unit. Maps spec /// constant's ID type to generated unique name. Duplicates are removed at /// integration header emission time. llvm::SmallVector<SpecConstID, 4> SpecConsts; /// Whether header is generated with unnamed lambda support bool UnnamedLambdaSupport; Sema &S; }; class SYCLIntegrationFooter { public: SYCLIntegrationFooter(Sema &S) : S(S) {} bool emit(StringRef MainSrc); void addVarDecl(const VarDecl *VD); private: bool emit(raw_ostream &O); Sema &S; llvm::SmallVector<const VarDecl *> SpecConstants; void emitSpecIDName(raw_ostream &O, const VarDecl *VD); }; /// Tracks expected type during expression parsing, for use in code completion. /// The type is tied to a particular token, all functions that update or consume /// the type take a start location of the token they are looking at as a /// parameter. This avoids updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Handles e.g. BaseType{ .D = Tok... void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. /// /// The callback should also emit signature help as a side-effect, but only /// if the completion point has been reached. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); /// Get the expected type associated with this location, if any. /// /// If the location is a function argument, determining the expected type /// involves considering all function overloads and the arguments so far. /// In this case, signature help for these function overloads will be reported /// as a side-effect (only if the completion point has been reached). QualType get(SourceLocation Tok) const { if (!Enabled || Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: bool Enabled; /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 29; static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } // Marks a type as a SYCL Kernel without necessarily adding it. Additionally, // it diagnoses if this causes any of the evaluated // __builtin_sycl_unique_stable_name values to change. void MarkSYCLKernel(SourceLocation NewLoc, QualType Ty, bool IsInstantiation); // Does the work necessary to deal with a SYCL kernel lambda. At the moment, // this just marks the list of lambdas required to name the kernel. It does // this by dispatching to MarkSYCLKernel, so it also does the diagnostics. void AddSYCLKernelLambda(const FunctionDecl *FD); class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; /// Increment when we find a reference; decrement when we find an ignored /// assignment. Ultimately the value is 0 if every reference is an ignored /// assignment. llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); /// This virtual key function only exists to limit the emission of debug info /// describing the Sema class. GCC and Clang only emit debug info for a class /// with a vtable when the vtable is emitted. Sema is final and not /// polymorphic, but the debug info size savings are so significant that it is /// worth adding a vtable just to take advantage of this optimization. virtual void anchor(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First clear the diagnostic // builder itself so it won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template <typename T> friend const ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// Bitmask to contain the list of reasons a single diagnostic should be /// emitted, based on its language. This permits multiple offload systems /// to coexist in the same translation unit. enum class DeviceDiagnosticReason { /// Diagnostic doesn't apply to anything. Included for completeness, but /// should make this a no-op. None = 0, /// OpenMP specific diagnostic. OmpDevice = 1 << 0, OmpHost = 1 << 1, OmpAll = OmpDevice | OmpHost, /// CUDA specific diagnostics. CudaDevice = 1 << 2, CudaHost = 1 << 3, CudaAll = CudaDevice | CudaHost, /// SYCL specific diagnostic. Sycl = 1 << 4, /// ESIMD specific diagnostic. Esimd = 1 << 5, /// A flag representing 'all'. This can be used to avoid the check /// all-together and make this behave as it did before the /// DiagnosticReason was added (that is, unconditionally emit). /// Note: This needs to be updated if any flags above are added. All = OmpAll | CudaAll | Sycl | Esimd, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/All) }; private: // A collection of a pair of undefined functions and their callers known // to be reachable from a routine on the device (kernel or device function). typedef std::pair<const FunctionDecl *, const FunctionDecl *> CallPair; llvm::SmallVector<CallPair> UndefinedReachableFromSyclDevice; public: // Helper routine to add a pair of Callee-Caller pair of FunctionDecl * // to UndefinedReachableFromSyclDevice. void addFDToReachableFromSyclDevice(const FunctionDecl *Callee, const FunctionDecl *Caller) { UndefinedReachableFromSyclDevice.push_back(std::make_pair(Callee, Caller)); } // Helper routine to check if a pair of Callee-Caller FunctionDecl * // is in UndefinedReachableFromSyclDevice. bool isFDReachableFromSyclDevice(const FunctionDecl *Callee, const FunctionDecl *Caller) { return llvm::any_of(UndefinedReachableFromSyclDevice, [Callee, Caller](const CallPair &P) { return P.first == Callee && P.second == Caller; }); } /// A generic diagnostic builder for errors which may or may not be deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class SemaDiagnosticBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S, DeviceDiagnosticReason R); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId] .getDiag() .second << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].getDiag().second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId] .getDiag() .second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].getDiag().second.AddFixItHint( Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether deferrable diagnostics should be deferred. bool DeferDiags = false; /// RAII class to control scope of DeferDiags. class DeferDiagsRAII { Sema &S; bool SavedDeferDiags = false; public: DeferDiagsRAII(Sema &S, bool DeferDiags) : S(S), SavedDeferDiags(S.DeferDiags) { S.DeferDiags = DeferDiags; } ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } }; /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void setFunctionHasMustTail(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// Retrieve the current function, if any, that should be analyzed for /// potential availability violations. sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); SYCLIntelFPGAIVDepAttr * BuildSYCLIntelFPGAIVDepAttr(const AttributeCommonInfo &CI, Expr *Expr1, Expr *Expr2); template <typename FPGALoopAttrT> FPGALoopAttrT *BuildSYCLIntelFPGALoopAttr(const AttributeCommonInfo &A, Expr *E = nullptr); LoopUnrollHintAttr *BuildLoopUnrollHintAttr(const AttributeCommonInfo &A, Expr *E); OpenCLUnrollHintAttr * BuildOpenCLLoopUnrollHintAttr(const AttributeCommonInfo &A, Expr *E); SYCLIntelFPGALoopCountAttr * BuildSYCLIntelFPGALoopCount(const AttributeCommonInfo &CI, Expr *E); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType getDecltypeForParenthesizedExpr(Expr *E); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); void warnOnReservedIdentifier(const NamedDecl *D); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const BindingDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, /// Merge availability attributes for an implementation of /// an optional protocol requirement. AMK_OptionalProtocolImplementation }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, bool AllowRecovery = false); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplatePack, }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); DeviceDiagnosticReason getEmissionReason(const FunctionDecl *Decl); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the /// correct number of arguments were passed, etc. Returns true if the /// attribute has been diagnosed. bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A); bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); llvm::Error isValidSectionSpecifier(StringRef Str); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Process the attributes before creating an attributed statement. Returns /// the semantic attributes that have been processed. void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesWithRange &InAttrs, SmallVectorImpl<const Attr *> &OutAttrs); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnAfterCompoundStatementLeadingPragmas(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt); StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList, Stmt *SubStmt); bool CheckRebuiltAttributedStmtAttributes(ArrayRef<const Attr *> Attrs); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); struct NamedReturnInfo { const VarDecl *Candidate; enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; Status S; bool isMoveEligible() const { return S != None; }; bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } }; NamedReturnInfo getNamedReturnInfo(Expr *&E, bool ForceCXX2b = false); NamedReturnInfo getNamedReturnInfo(const VarDecl *VD, bool ForceCXX20 = false); const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// If VD is set but not otherwise used, diagnose, for a parameter or a /// variable. void DiagnoseUnusedButSetDecl(const VarDecl *VD); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI); ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy); ExprResult BuildSYCLUniqueStableIdExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E); ExprResult ActOnSYCLUniqueStableIdExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void FilterUsingLookup(Scope *S, LookupResult &lookup); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R = nullptr, const UsingDecl *UD = nullptr); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists); NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr *> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); // Complete an enum decl, maybe without a scope spec. bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS = nullptr); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, ExprResult RequiresClause); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); template <typename AttrType> void AddOneConstantPowerTwoValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); void AddIntelFPGABankBitsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size); template <typename AttrType> void addIntelTripleArgAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr); void AddWorkGroupSizeHintAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim); WorkGroupSizeHintAttr * MergeWorkGroupSizeHintAttr(Decl *D, const WorkGroupSizeHintAttr &A); void AddIntelReqdSubGroupSize(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelReqdSubGroupSizeAttr * MergeIntelReqdSubGroupSizeAttr(Decl *D, const IntelReqdSubGroupSizeAttr &A); IntelNamedSubGroupSizeAttr * MergeIntelNamedSubGroupSizeAttr(Decl *D, const IntelNamedSubGroupSizeAttr &A); void AddSYCLIntelNumSimdWorkItemsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelNumSimdWorkItemsAttr * MergeSYCLIntelNumSimdWorkItemsAttr(Decl *D, const SYCLIntelNumSimdWorkItemsAttr &A); void AddSYCLIntelESimdVectorizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelESimdVectorizeAttr * MergeSYCLIntelESimdVectorizeAttr(Decl *D, const SYCLIntelESimdVectorizeAttr &A); void AddSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelSchedulerTargetFmaxMhzAttr *MergeSYCLIntelSchedulerTargetFmaxMhzAttr( Decl *D, const SYCLIntelSchedulerTargetFmaxMhzAttr &A); void AddSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelNoGlobalWorkOffsetAttr *MergeSYCLIntelNoGlobalWorkOffsetAttr( Decl *D, const SYCLIntelNoGlobalWorkOffsetAttr &A); void AddSYCLIntelLoopFuseAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelLoopFuseAttr * MergeSYCLIntelLoopFuseAttr(Decl *D, const SYCLIntelLoopFuseAttr &A); void AddIntelFPGAPrivateCopiesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); void AddIntelFPGAMaxReplicatesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelFPGAMaxReplicatesAttr * MergeIntelFPGAMaxReplicatesAttr(Decl *D, const IntelFPGAMaxReplicatesAttr &A); void AddIntelFPGAForcePow2DepthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelFPGAForcePow2DepthAttr * MergeIntelFPGAForcePow2DepthAttr(Decl *D, const IntelFPGAForcePow2DepthAttr &A); void AddSYCLIntelFPGAInitiationIntervalAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGAInitiationIntervalAttr *MergeSYCLIntelFPGAInitiationIntervalAttr( Decl *D, const SYCLIntelFPGAInitiationIntervalAttr &A); SYCLIntelFPGAMaxConcurrencyAttr *MergeSYCLIntelFPGAMaxConcurrencyAttr( Decl *D, const SYCLIntelFPGAMaxConcurrencyAttr &A); void AddSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelMaxGlobalWorkDimAttr * MergeSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const SYCLIntelMaxGlobalWorkDimAttr &A); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addSYCLIntelPipeIOAttr - Adds a pipe I/O attribute to a particular /// declaration. void addSYCLIntelPipeIOAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ID); /// AddSYCLIntelFPGAMaxConcurrencyAttr - Adds a max_concurrency attribute to a /// particular declaration. void AddSYCLIntelFPGAMaxConcurrencyAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); bool checkAllowedSYCLInitializer(VarDecl *VD, bool CheckValueDependent = false); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; struct DeclareTargetContextInfo { struct MapInfo { OMPDeclareTargetDeclAttr::MapTypeTy MT; SourceLocation Loc; }; /// Explicitly listed variables and functions in a 'to' or 'link' clause. llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; /// The 'device_type' as parsed from the clause. OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; /// The directive kind, `begin declare target` or `declare target`. OpenMPDirectiveKind Kind; /// The directive location. SourceLocation Loc; DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc) {} }; /// Number of nested '#pragma omp declare target' directives. SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true, bool SuppressExprDiags = false); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Analyzes and checks a loop nest for use by a loop transformation. /// /// \param Kind The loop transformation directive kind. /// \param NumLoops How many nested loops the directive is expecting. /// \param AStmt Associated statement of the transformation directive. /// \param LoopHelpers [out] The loop analysis result. /// \param Body [out] The body code nested in \p NumLoops loop. /// \param OriginalInits [out] Collection of statements and declarations that /// must have been executed/declared before entering the /// loop. /// /// \return Whether there was any error. bool checkTransformableLoopNest( OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, Stmt *&Body, SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> &OriginalInits); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<StringRef> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Called at the end of target region i.e. '#pragma omp end declare target'. const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); /// Called once a target context is completed, that can be when a /// '#pragma omp end declare target' was encountered or when a /// '#pragma omp declare target' without declaration-definition-seq was /// encountered. void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to /// an OpenMP loop directive. StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '#pragma omp tile' after parsing of its clauses and /// the associated statement. StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '#pragma omp unroll' after parsing of its clauses /// and the associated statement. StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp interop'. StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp dispatch' after parsing of the // /associated statement. StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp masked' after parsing of the // /associated statement. StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'sizes' clause. OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'full' clauses. OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-form 'partial' clauses. OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'init' clause. OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'use' clause. OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'novariants' clause. OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'nocontext' clause. OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'filter' clause. OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. In the success case, /// the statement is rewritten to remove implicit nodes from the return /// value. bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); private: /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. bool checkMustTailAttr(const Stmt *St, const Attr &MTA); public: /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); bool areVectorTypesSameSize(QualType srcType, QualType destType); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckMatrixCast - Check type constraints for matrix casts. // We allow casting between matrixes of the same dimensions i.e. when they // have the same number of rows and column. Returns true if the cast is // invalid. bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); class DeviceDeferredDiagnostic { public: DeviceDeferredDiagnostic(SourceLocation SL, const PartialDiagnostic &PD, DeviceDiagnosticReason R) : Diagnostic(SL, PD), Reason(R) {} PartialDiagnosticAt &getDiag() { return Diagnostic; } DeviceDiagnosticReason getReason() const { return Reason; } private: PartialDiagnosticAt Diagnostic; DeviceDiagnosticReason Reason; }; /// 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<DeviceDeferredDiagnostic>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD = nullptr); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, FunctionDecl *FD = nullptr) { return targetDiag(Loc, PD.getDiagID(), FD) << PD; } /// Check if the expression is allowed to be used in expressions for the /// offloading devices. void checkDeviceDecl(ValueDecl *D, SourceLocation Loc); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); enum CUDAVariableTarget { CVT_Device, /// Emitted on device side with a shadow variable on host side CVT_Host, /// Emitted on host side only CVT_Both, /// Emitted on both sides with different addresses CVT_Unified, /// Emitted as a unified address, e.g. managed variables }; /// Determines whether the given variable is emitted on host or device side. CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Determines the preferred type of the current function argument, by /// examining the signatures of all possible overloads. /// Returns null if unknown or ambiguous, or if code completion is off. /// /// If the code completion point has been reached, also reports the function /// signatures that were considered. /// /// FIXME: rename to GuessCallArgumentType to reduce confusion. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, StringRef ParamName, QualType ArgTy, QualType ParamTy); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); void CheckSYCLKernelCall(FunctionDecl *CallerFunc, SourceRange CallLoc, ArrayRef<const Expr *> Args); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckIntelFPGARegBuiltinFunctionCall(unsigned BuiltinID, CallExpr *Call); bool CheckIntelFPGAMemBuiltinFunctionCall(CallExpr *Call); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckFreeArguments(const CallExpr *E); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Nullable_result = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; private: // We store SYCL Kernels here and handle separately -- which is a hack. // FIXME: It would be best to refactor this. llvm::SetVector<Decl *> SyclDeviceDecls; // SYCL integration header instance for current compilation unit this Sema // is associated with. std::unique_ptr<SYCLIntegrationHeader> SyclIntHeader; std::unique_ptr<SYCLIntegrationFooter> SyclIntFooter; // Used to suppress diagnostics during kernel construction, since these were // already emitted earlier. Diagnosing during Kernel emissions also skips the // useful notes that shows where the kernel was called. bool DiagnosingSYCLKernel = false; public: void addSyclDeviceDecl(Decl *d) { SyclDeviceDecls.insert(d); } llvm::SetVector<Decl *> &syclDeviceDecls() { return SyclDeviceDecls; } /// Lazily creates and returns SYCL integration header instance. SYCLIntegrationHeader &getSyclIntegrationHeader() { if (SyclIntHeader == nullptr) SyclIntHeader = std::make_unique<SYCLIntegrationHeader>( getLangOpts().SYCLUnnamedLambda, *this); return *SyclIntHeader.get(); } SYCLIntegrationFooter &getSyclIntegrationFooter() { if (SyclIntFooter == nullptr) SyclIntFooter = std::make_unique<SYCLIntegrationFooter>(*this); return *SyclIntFooter.get(); } void addSyclVarDecl(VarDecl *VD) { if (LangOpts.SYCLIsDevice && !LangOpts.SYCLIntFooter.empty()) getSyclIntegrationFooter().addVarDecl(VD); } enum SYCLRestrictKind { KernelGlobalVariable, KernelRTTI, KernelNonConstStaticDataVariable, KernelCallVirtualFunction, KernelUseExceptions, KernelCallRecursiveFunction, KernelCallFunctionPointer, KernelAllocateStorage, KernelUseAssembly, KernelCallDllimportFunction, KernelCallVariadicFunction, KernelCallUndefinedFunction, KernelConstStaticVariable }; bool isKnownGoodSYCLDecl(const Decl *D); void checkSYCLDeviceVarDecl(VarDecl *Var); void copySYCLKernelAttrs(const CXXRecordDecl *KernelObj); void ConstructOpenCLKernel(FunctionDecl *KernelCallerFunc, MangleContext &MC); void MarkDevices(); /// Get the number of fields or captures within the parsed type. ExprResult ActOnSYCLBuiltinNumFieldsExpr(ParsedType PT); ExprResult BuildSYCLBuiltinNumFieldsExpr(SourceLocation Loc, QualType SourceTy); /// Get a value based on the type of the given field number so that callers /// can wrap it in a decltype() to get the actual type of the field. ExprResult ActOnSYCLBuiltinFieldTypeExpr(ParsedType PT, Expr *Idx); ExprResult BuildSYCLBuiltinFieldTypeExpr(SourceLocation Loc, QualType SourceTy, Expr *Idx); /// Get the number of base classes within the parsed type. ExprResult ActOnSYCLBuiltinNumBasesExpr(ParsedType PT); ExprResult BuildSYCLBuiltinNumBasesExpr(SourceLocation Loc, QualType SourceTy); /// Get a value based on the type of the given base number so that callers /// can wrap it in a decltype() to get the actual type of the base class. ExprResult ActOnSYCLBuiltinBaseTypeExpr(ParsedType PT, Expr *Idx); ExprResult BuildSYCLBuiltinBaseTypeExpr(SourceLocation Loc, QualType SourceTy, Expr *Idx); /// Emit a diagnostic about the given attribute having a deprecated name, and /// also emit a fixit hint to generate the new attribute name. void DiagnoseDeprecatedAttribute(const ParsedAttr &A, StringRef NewScope, StringRef NewName); /// Diagnoses an attribute in the 'intelfpga' namespace and suggests using /// the attribute in the 'intel' namespace instead. void CheckDeprecatedSYCLAttributeSpelling(const ParsedAttr &A, StringRef NewName = ""); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode( SourceLocation Loc, unsigned DiagID, DeviceDiagnosticReason Reason = DeviceDiagnosticReason::Sycl | DeviceDiagnosticReason::Esimd); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); /// Finishes analysis of the deferred functions calls that may be not /// properly declared for device compilation. void finalizeSYCLDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc, DeviceDiagnosticReason Reason); /// Tells whether given variable is a SYCL explicit SIMD extension's "private /// global" variable - global variable in the private address space. bool isSYCLEsimdPrivateGlobal(VarDecl *VDecl) { return getLangOpts().SYCLIsDevice && VDecl->hasAttr<SYCLSimdAttr>() && VDecl->hasGlobalStorage() && (VDecl->getType().getAddressSpace() == LangAS::sycl_private); } }; inline Expr *checkMaxWorkSizeAttrExpr(Sema &S, const AttributeCommonInfo &CI, Expr *E) { assert(E && "Attribute must have an argument."); if (!E->isInstantiationDependent()) { llvm::APSInt ArgVal; ExprResult ICE = S.VerifyIntegerConstantExpression(E, &ArgVal); if (ICE.isInvalid()) return nullptr; E = ICE.get(); if (ArgVal.isNegative()) { S.Diag(E->getExprLoc(), diag::warn_attribute_requires_non_negative_integer_argument) << E->getType() << S.Context.UnsignedLongLongTy << E->getSourceRange(); return E; } unsigned Val = ArgVal.getZExtValue(); if (Val == 0) { S.Diag(E->getExprLoc(), diag::err_attribute_argument_is_zero) << CI << E->getSourceRange(); return nullptr; } } return E; } template <typename WorkGroupAttrType> void Sema::addIntelTripleArgAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr) { assert((XDimExpr && YDimExpr && ZDimExpr) && "argument has unexpected null value"); // Accept template arguments for now as they depend on something else. // We'll get to check them when they eventually get instantiated. if (!XDimExpr->isValueDependent() && !YDimExpr->isValueDependent() && !ZDimExpr->isValueDependent()) { // Save ConstantExpr in semantic attribute XDimExpr = checkMaxWorkSizeAttrExpr(*this, CI, XDimExpr); YDimExpr = checkMaxWorkSizeAttrExpr(*this, CI, YDimExpr); ZDimExpr = checkMaxWorkSizeAttrExpr(*this, CI, ZDimExpr); if (!XDimExpr || !YDimExpr || !ZDimExpr) return; } D->addAttr(::new (Context) WorkGroupAttrType(Context, CI, XDimExpr, YDimExpr, ZDimExpr)); } template <typename AttrType> void Sema::AddOneConstantPowerTwoValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { AttrType TmpAttr(Context, CI, E); if (!E->isValueDependent()) { llvm::APSInt Value; ExprResult ICE = VerifyIntegerConstantExpression(E, &Value); if (ICE.isInvalid()) return; if (!Value.isStrictlyPositive()) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << CI << /*positive*/ 0; return; } if (!Value.isPowerOf2()) { Diag(CI.getLoc(), diag::err_attribute_argument_not_power_of_two) << &TmpAttr; return; } if (IntelFPGANumBanksAttr::classof(&TmpAttr)) { if (auto *BBA = D->getAttr<IntelFPGABankBitsAttr>()) { unsigned NumBankBits = BBA->args_size(); if (NumBankBits != Value.ceilLogBase2()) { Diag(TmpAttr.getLocation(), diag::err_bankbits_numbanks_conflicting); return; } } } E = ICE.get(); } if (!D->hasAttr<IntelFPGAMemoryAttr>()) D->addAttr(IntelFPGAMemoryAttr::CreateImplicit( Context, IntelFPGAMemoryAttr::Default)); // We are adding a user NumBanks, drop any implicit default. if (IntelFPGANumBanksAttr::classof(&TmpAttr)) { if (auto *NBA = D->getAttr<IntelFPGANumBanksAttr>()) if (NBA->isImplicit()) D->dropAttr<IntelFPGANumBanksAttr>(); } D->addAttr(::new (Context) AttrType(Context, CI, E)); } template <typename FPGALoopAttrT> FPGALoopAttrT *Sema::BuildSYCLIntelFPGALoopAttr(const AttributeCommonInfo &A, Expr *E) { if (!E && !(A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGALoopCoalesce)) return nullptr; if (E && !E->isInstantiationDependent()) { Optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(getASTContext()); if (!ArgVal) { Diag(E->getExprLoc(), diag::err_attribute_argument_type) << A.getAttrName() << AANT_ArgumentIntegerConstant << E->getSourceRange(); return nullptr; } int Val = ArgVal->getSExtValue(); if (A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGAInitiationInterval || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGALoopCoalesce) { if (Val <= 0) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << A.getAttrName() << /* positive */ 0; return nullptr; } } else if (A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGAMaxConcurrency || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGAMaxInterleaving || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGASpeculatedIterations || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGALoopCount) { if (Val < 0) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << A.getAttrName() << /* non-negative */ 1; return nullptr; } } else { llvm_unreachable("unknown sycl fpga loop attr"); } } return new (Context) FPGALoopAttrT(Context, A, E); } /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-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] = 32; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); 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 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(0,ceild(3*t1-3*t2-2,4)),ceild(3*t1-6,8)),ceild(24*t2-Nz-19,32));t3<=min(min(min(floord(4*Nt+Ny-9,32),floord(12*t1+Ny+15,32)),floord(24*t2+Ny+11,32)),floord(24*t1-24*t2+Nz+Ny+13,32));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-30,32)),ceild(3*t1-62,64)),ceild(24*t2-Nz-243,256)),ceild(32*t3-Ny-243,256));t4<=min(min(min(min(floord(4*Nt+Nx-9,256),floord(12*t1+Nx+15,256)),floord(24*t2+Nx+11,256)),floord(32*t3+Nx+19,256)),floord(24*t1-24*t2+Nz+Nx+13,256));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(256*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),8*t3+6),64*t4+62);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(256*t4,4*t5+4); ubv=min(256*t4+255,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "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; }
BFS.c
// ----------------------------------------------------------------------------- // // "00_AccelGraph" // // ----------------------------------------------------------------------------- // Copyright (c) 2014-2019 All rights reserved // ----------------------------------------------------------------------------- // Author : Abdullah Mughrabi // Email : atmughra@ncsu.edu||atmughrabi@gmail.com // File : BFS.c // Create : 2019-09-28 15:20:58 // Revise : 2019-09-28 15:34:05 // Editor : Abdullah Mughrabi // ----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <omp.h> #include "timer.h" #include "myMalloc.h" #include "boolean.h" #include "arrayQueue.h" #include "bitmap.h" #include "graphConfig.h" #include "reorder.h" #include "graphCSR.h" #include "graphGrid.h" #include "graphAdjArrayList.h" #include "graphAdjLinkedList.h" #include "BFS.h" // ******************************************************************************************** // *************** Stats DataStructure ************** // ******************************************************************************************** struct BFSStats *newBFSStatsGraphCSR(struct GraphCSR *graph) { uint32_t vertex_id; struct BFSStats *stats = (struct BFSStats *) my_malloc(sizeof(struct BFSStats)); stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->distances_DualOrder = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->parents_DualOrder = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->iteration = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; // optimization for BFS implentaion instead of -1 we use -out degree to for hybrid approach counter #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; // stats->parents_DualOrder[vertex_id] = 0; if(graph->vertices->out_degree[vertex_id]) { stats->parents[vertex_id] = graph->vertices->out_degree[vertex_id] * (-1); stats->parents_DualOrder[vertex_id] = graph->vertices->out_degree[vertex_id] * (-1); } else { stats->parents[vertex_id] = -1; stats->parents_DualOrder[vertex_id] = -1; } } return stats; } struct BFSStats *newBFSStatsGraphGrid(struct GraphGrid *graph) { uint32_t vertex_id; struct BFSStats *stats = (struct BFSStats *) my_malloc(sizeof(struct BFSStats)); stats->distances_DualOrder = NULL; stats->parents_DualOrder = NULL; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->iteration = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; stats->parents[vertex_id] = -1; } return stats; } struct BFSStats *newBFSStatsGraphAdjArrayList(struct GraphAdjArrayList *graph) { uint32_t vertex_id; struct BFSStats *stats = (struct BFSStats *) my_malloc(sizeof(struct BFSStats)); stats->distances_DualOrder = NULL; stats->parents_DualOrder = NULL; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->iteration = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; // optimization for BFS implentaion instead of -1 we use -out degree to for hybrid approach counter #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; if(graph->vertices[vertex_id].out_degree) stats->parents[vertex_id] = graph->vertices[vertex_id].out_degree * (-1); else stats->parents[vertex_id] = -1; } return stats; } struct BFSStats *newBFSStatsGraphAdjLinkedList(struct GraphAdjLinkedList *graph) { uint32_t vertex_id; struct BFSStats *stats = (struct BFSStats *) my_malloc(sizeof(struct BFSStats)); stats->distances_DualOrder = NULL; stats->parents_DualOrder = NULL; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->iteration = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; // optimization for BFS implentaion instead of -1 we use -out degree to for hybrid approach counter #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; if(graph->vertices[vertex_id].out_degree) stats->parents[vertex_id] = graph->vertices[vertex_id].out_degree * (-1); else stats->parents[vertex_id] = -1; } return stats; } void freeBFSStats(struct BFSStats *stats) { if(stats) { if(stats->distances) free(stats->distances); if(stats->parents) free(stats->parents); if(stats->distances_DualOrder) free(stats->distances_DualOrder); if(stats->parents_DualOrder) free(stats->parents_DualOrder); free(stats); } } void syncDualOrderParentArrays(int **parents, int **parents_DualOrder, uint32_t *labels, uint32_t num_vertices) { uint32_t vertex_id; uint32_t vertex_v; int *parents_temp; uint32_t num_threads_max = omp_get_max_threads(); #pragma omp parallel for default(none) private(vertex_id,vertex_v) shared(parents,parents_DualOrder,labels,num_vertices) num_threads(num_threads_max) for(vertex_id = 0; vertex_id < num_vertices ; vertex_id++) { vertex_v = labels[vertex_id]; // vertex_u = inv_labels[vertex_id]; if((*parents)[vertex_id] >= 0) { (*parents_DualOrder)[vertex_v] = labels[(*parents)[vertex_id]]; } else { (*parents_DualOrder)[vertex_v] = (*parents)[vertex_id]; } } parents_temp = *parents; *parents = *parents_DualOrder; *parents_DualOrder = parents_temp; } void syncDualOrderDistancesArrays(uint32_t *distances, uint32_t *distances_DualOrder, uint32_t *labels, uint32_t num_vertices) { uint32_t vertex_id; uint32_t vertex_v; // uint32_t vertex_u; uint32_t *distances_temp; uint32_t num_threads_max = omp_get_max_threads(); #pragma omp parallel for default(none) private(vertex_id,vertex_v) shared(distances,distances_DualOrder,labels,num_vertices) num_threads(num_threads_max) for(vertex_id = 0; vertex_id < num_vertices ; vertex_id++) { vertex_v = labels[vertex_id]; // vertex_u = inv_labels[vertex_id]; distances_DualOrder[vertex_v] = distances[vertex_id]; } distances_temp = distances; distances = distances_DualOrder; distances_DualOrder = distances_temp; } // ******************************************************************************************** // *************** CSR DataStructure ************** // ******************************************************************************************** struct BFSStats *breadthFirstSearchGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = NULL; switch (arguments->pushpull) { case 0: // pull stats = breadthFirstSearchPullGraphCSR(arguments, graph); break; case 1: // push stats = breadthFirstSearchPushGraphCSR(arguments, graph); break; case 2: // pull/push stats = breadthFirstSearchDirectionOptimizedGraphCSR(arguments, graph); break; case 3: // push-bitmap queue instead of array queue stats = breadthFirstSearchPushBitmapGraphCSR(arguments, graph); break; case 4: // pull/push-bitmap queue instead of array queue stats = breadthFirstSearchPushDirectionOptimizedBitmapGraphCSR(arguments, graph); break; default:// push stats = breadthFirstSearchDirectionOptimizedGraphCSR(arguments, graph); break; } return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPullGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PULL/BU (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t nf = 0; // number of vertices in sharedFrontierQueue Start(timer_inner); setBit(sharedFrontierQueue->q_bitmap_next, arguments->source); sharedFrontierQueue->q_bitmap_next->numSetBits = 1; stats->parents[arguments->source] = arguments->source; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while (sharedFrontierQueue->q_bitmap->numSetBits) { Start(timer_inner); nf = bottomUpStepGraphCSR(graph, sharedFrontierQueue->q_bitmap, sharedFrontierQueue->q_bitmap_next, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = nf; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); //stats stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPushGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PUSH/TD (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t P = arguments->algo_numThreads; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { Start(timer_inner); topDownStepGraphCSR(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchDirectionOptimizedGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PUSH/PULL(SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); struct Bitmap *bitmapCurr = newBitmap(graph->num_vertices); struct Bitmap *bitmapNext = newBitmap(graph->num_vertices); uint32_t P = arguments->algo_numThreads; uint32_t mu = graph->num_edges; // number of edges to check from sharedFrontierQueue uint32_t mf = graph->vertices->out_degree[arguments->source]; // number of edges from unexplored verticies uint32_t nf = 0; // number of vertices in sharedFrontierQueue uint32_t nf_prev = 0; // number of vertices in sharedFrontierQueue uint32_t n = graph->num_vertices; // number of nodes uint32_t alpha = 15; uint32_t beta = 18; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { if(mf > (mu / alpha)) { Start(timer_inner); arrayQueueToBitmap(sharedFrontierQueue, bitmapCurr); nf = sizeArrayQueue(sharedFrontierQueue); Stop(timer_inner); printf("| E %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); do { Start(timer_inner); nf_prev = nf; nf = bottomUpStepGraphCSR(graph, bitmapCurr, bitmapNext, stats); swapBitmaps(&bitmapCurr, &bitmapNext); clearBitmap(bitmapNext); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } while(( nf > nf_prev) || // growing; ( nf > (n / beta))); Start(timer_inner); bitmapToArrayQueue(bitmapCurr, sharedFrontierQueue, localFrontierQueues); Stop(timer_inner); printf("| C %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); mf = 1; } else { Start(timer_inner); mu -= mf; mf = topDownStepGraphCSR(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } } // end while Stop(timer); // stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); freeBitmap(bitmapNext); freeBitmap(bitmapCurr); free(timer); free(timer_inner); return stats; } // top-down-step(graph, sharedFrontierQueue, next, parents) // for v ∈ sharedFrontierQueue do // for u ∈ neighbors[v] do // if parents[u] = -1 then // parents[u] ← v // next ← next ∪ {u} // end if // end for // end for uint32_t topDownStepGraphCSR(struct GraphCSR *graph, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue **localFrontierQueues, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t i; uint32_t j; uint32_t edge_idx; uint32_t mf = 0; #pragma omp parallel default (none) private(u,v,j,i,edge_idx) shared(stats,localFrontierQueues,graph,sharedFrontierQueue,mf) { uint32_t t_id = omp_get_thread_num(); struct ArrayQueue *localFrontierQueue = localFrontierQueues[t_id]; #pragma omp for reduction(+:mf) schedule(auto) for(i = sharedFrontierQueue->head ; i < sharedFrontierQueue->tail; i++) { v = sharedFrontierQueue->queue[i]; edge_idx = graph->vertices->edges_idx[v]; for(j = edge_idx ; j < (edge_idx + graph->vertices->out_degree[v]) ; j++) { u = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); int u_parent = stats->parents[u]; if(u_parent < 0 ) { if(__sync_bool_compare_and_swap(&stats->parents[u], u_parent, v)) { enArrayQueue(localFrontierQueue, u); mf += -(u_parent); stats->distances[u] = stats->distances[v] + 1; } } } } flushArrayQueueToShared(localFrontierQueue, sharedFrontierQueue); } return mf; } // bottom-up-step(graph, sharedFrontierQueue, next, parents) //pull // for v ∈ vertices do // if parents[v] = -1 then // for u ∈ neighbors[v] do // if u ∈ sharedFrontierQueue then // parents[v] ← u // next ← next ∪ {v} // break // end if // end for // end if // end for uint32_t bottomUpStepGraphCSR(struct GraphCSR *graph, struct Bitmap *bitmapCurr, struct Bitmap *bitmapNext, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t j; uint32_t edge_idx; uint32_t out_degree; struct Vertex *vertices = NULL; uint32_t *sorted_edges_array = NULL; // uint32_t processed_nodes = bitmapCurr->numSetBits; uint32_t nf = 0; // number of vertices in sharedFrontierQueue // stats->processed_nodes += processed_nodes; #if DIRECTED vertices = graph->inverse_vertices; sorted_edges_array = graph->inverse_sorted_edges_array->edges_array_dest; #else vertices = graph->vertices; sorted_edges_array = graph->sorted_edges_array->edges_array_dest; #endif #pragma omp parallel for default(none) private(j,u,v,out_degree,edge_idx) shared(stats,bitmapCurr,bitmapNext,graph,vertices,sorted_edges_array) reduction(+:nf) schedule(dynamic, 1024) for(v = 0 ; v < graph->num_vertices ; v++) { out_degree = vertices->out_degree[v]; if(stats->parents[v] < 0) // optmization { edge_idx = vertices->edges_idx[v]; for(j = edge_idx ; j < (edge_idx + out_degree) ; j++) { u = EXTRACT_VALUE(sorted_edges_array[j]); if(getBit(bitmapCurr, u)) { stats->parents[v] = u; //we are not considering distance array as it is not implemented in AccelGraph stats->distances[v] = stats->distances[u] + 1; setBitAtomic(bitmapNext, v); nf++; break; } } } } return nf; } // ******************************************************************************************** // *************** CSR DataStructure/Bitmap Frontiers ************** // ******************************************************************************************** // / breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPushBitmapGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PUSH/Bitmap (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); Start(timer_inner); setBit(sharedFrontierQueue->q_bitmap_next, arguments->source); sharedFrontierQueue->q_bitmap_next->numSetBits = 1; stats->parents[arguments->source] = arguments->source; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while (sharedFrontierQueue->q_bitmap->numSetBits) { Start(timer_inner); topDownStepUsingBitmapsGraphCSR(graph, sharedFrontierQueue, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = getNumOfSetBits(sharedFrontierQueue->q_bitmap_next); swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->q_bitmap->numSetBits; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->q_bitmap->numSetBits, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPushDirectionOptimizedBitmapGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PUSH/PULL Bitmap (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t mu = graph->num_edges; // number of edges to check from sharedFrontierQueue uint32_t mf = graph->vertices->out_degree[arguments->source]; // number of edges from unexplored verticies uint32_t nf = 0; // number of vertices in sharedFrontierQueue uint32_t nf_prev = 0; // number of vertices in sharedFrontierQueue uint32_t n = graph->num_vertices; // number of nodes uint32_t alpha = 15; uint32_t beta = 18; Start(timer_inner); setBit(sharedFrontierQueue->q_bitmap_next, arguments->source); sharedFrontierQueue->q_bitmap_next->numSetBits = 1; stats->parents[arguments->source] = arguments->source; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while (sharedFrontierQueue->q_bitmap->numSetBits) { if(mf > (mu / alpha)) { nf = sharedFrontierQueue->q_bitmap->numSetBits; printf("| E %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); do { Start(timer_inner); nf_prev = nf; nf = bottomUpStepGraphCSR(graph, sharedFrontierQueue->q_bitmap, sharedFrontierQueue->q_bitmap_next, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = nf; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); //stats stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } while(( nf > nf_prev) || // growing; ( nf > (n / beta))); printf("| C %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); mf = 1; } else { mu -= mf; Start(timer_inner); mf = topDownStepUsingBitmapsGraphCSR(graph, sharedFrontierQueue, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = getNumOfSetBits(sharedFrontierQueue->q_bitmap_next); swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->q_bitmap->numSetBits; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->q_bitmap->numSetBits, Seconds(timer_inner)); } } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } uint32_t topDownStepUsingBitmapsGraphCSR(struct GraphCSR *graph, struct ArrayQueue *sharedFrontierQueue, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t i; uint32_t j; uint32_t edge_idx; uint32_t mf = 0; #pragma omp parallel default (none) private(u,v,j,i,edge_idx) shared(stats,graph,sharedFrontierQueue,mf) { #pragma omp for reduction(+:mf) for(i = 0 ; i < (sharedFrontierQueue->q_bitmap->size); i++) { if(getBit(sharedFrontierQueue->q_bitmap, i)) { // processed_nodes++; v = i; edge_idx = graph->vertices->edges_idx[v]; for(j = edge_idx ; j < (edge_idx + graph->vertices->out_degree[v]) ; j++) { u = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); int u_parent = stats->parents[u]; if(u_parent < 0 ) { if(__sync_bool_compare_and_swap(&stats->parents[u], u_parent, v)) { mf += -(u_parent); stats->distances[u] = stats->distances[v] + 1; setBitAtomic(sharedFrontierQueue->q_bitmap_next, u); } } } } } } return mf; } // ******************************************************************************************** // *************** CSR DataStructure DualOrder ************** // ******************************************************************************************** struct BFSStats *breadthFirstSearchGraphCSRDualOrder(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = NULL; switch (arguments->pushpull) { case 0: // pull stats = breadthFirstSearchPullGraphCSRDualOrder(arguments, graph); break; case 1: // push stats = breadthFirstSearchPushGraphCSRDualOrder(arguments, graph); break; case 2: // pull/push stats = breadthFirstSearchDirectionOptimizedGraphCSRDualOrder(arguments, graph); break; default:// push stats = breadthFirstSearchDirectionOptimizedGraphCSRDualOrder(arguments, graph); break; } return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPullGraphCSRDualOrder(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } #if DIRECTED arguments->source = graph->inverse_sorted_edges_array->label_array[arguments->source]; #else arguments->source = graph->sorted_edges_array->label_array[arguments->source]; #endif printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS DualOrder PULL/BU (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t nf = 0; // number of vertices in sharedFrontierQueue Start(timer_inner); setBit(sharedFrontierQueue->q_bitmap_next, arguments->source); sharedFrontierQueue->q_bitmap_next->numSetBits = 1; stats->parents[arguments->source] = arguments->source; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while (sharedFrontierQueue->q_bitmap->numSetBits) { Start(timer_inner); nf = bottomUpStepGraphCSRDualOrder(graph, sharedFrontierQueue->q_bitmap, sharedFrontierQueue->q_bitmap_next, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = nf; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); //stats stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } // end while Stop(timer); // stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPushGraphCSRDualOrder(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS DualOrder PUSH/TD (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t P = arguments->algo_numThreads; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { Start(timer_inner); topDownStepGraphCSRDualOrder(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } // end while Stop(timer); // stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchDirectionOptimizedGraphCSRDualOrder(struct Arguments *arguments, struct GraphCSR *graph) { struct BFSStats *stats = newBFSStatsGraphCSR(graph); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } arguments->source = graph->sorted_edges_array->label_array[arguments->source]; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS DualOrder PUSH/PULL(SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); struct Bitmap *bitmapCurr = newBitmap(graph->num_vertices); struct Bitmap *bitmapNext = newBitmap(graph->num_vertices); uint32_t P = arguments->algo_numThreads; uint32_t mu = graph->num_edges; // number of edges to check from sharedFrontierQueue uint32_t mf = graph->vertices->out_degree[arguments->source]; // number of edges from unexplored verticies uint32_t nf = 0; // number of vertices in sharedFrontierQueue uint32_t nf_prev = 0; // number of vertices in sharedFrontierQueue uint32_t n = graph->num_vertices; // number of nodes uint32_t alpha = 15; uint32_t beta = 18; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { if(mf > (mu / alpha)) { Start(timer_inner); arrayQueueToBitmapDualOrder(sharedFrontierQueue, bitmapCurr, graph->sorted_edges_array->inverse_label_array); syncDualOrderParentArrays(&(stats->parents), &(stats->parents_DualOrder), graph->sorted_edges_array->inverse_label_array, graph->num_vertices); // syncDualOrderDistancesArrays(stats->distances, stats->distances_DualOrder, graph->sorted_edges_array->label_array, graph->inverse_sorted_edges_array->label_array, graph->num_vertices); nf = sizeArrayQueue(sharedFrontierQueue); Stop(timer_inner); printf("| E %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); do { Start(timer_inner); nf_prev = nf; nf = bottomUpStepGraphCSRDualOrder(graph, bitmapCurr, bitmapNext, stats); swapBitmaps(&bitmapCurr, &bitmapNext); clearBitmap(bitmapNext); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } while(( nf > nf_prev) || // growing; ( nf > (n / beta))); Start(timer_inner); syncDualOrderParentArrays(&(stats->parents), &(stats->parents_DualOrder), graph->inverse_sorted_edges_array->inverse_label_array, graph->num_vertices); // syncDualOrderDistancesArrays(stats->distances, stats->distances_DualOrder, graph->inverse_sorted_edges_array->label_array, graph->sorted_edges_array->label_array, graph->num_vertices); bitmapToArrayQueueDualOrder(bitmapCurr, sharedFrontierQueue, localFrontierQueues, graph->inverse_sorted_edges_array->inverse_label_array); Stop(timer_inner); printf("| C %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); mf = 1; } else { Start(timer_inner); mu -= mf; mf = topDownStepGraphCSRDualOrder(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } } // end while Stop(timer); // stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); freeBitmap(bitmapNext); freeBitmap(bitmapCurr); free(timer); free(timer_inner); return stats; } // top-down-step(graph, sharedFrontierQueue, next, parents) // for v ∈ sharedFrontierQueue do // for u ∈ neighbors[v] do // if parents[u] = -1 then // parents[u] ← v // next ← next ∪ {u} // end if // end for // end for uint32_t topDownStepGraphCSRDualOrder(struct GraphCSR *graph, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue **localFrontierQueues, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t i; uint32_t j; uint32_t edge_idx; uint32_t mf = 0; #pragma omp parallel default (none) private(u,v,j,i,edge_idx) shared(stats,localFrontierQueues,graph,sharedFrontierQueue,mf) { uint32_t t_id = omp_get_thread_num(); struct ArrayQueue *localFrontierQueue = localFrontierQueues[t_id]; #pragma omp for reduction(+:mf) schedule(auto) for(i = sharedFrontierQueue->head ; i < sharedFrontierQueue->tail; i++) { v = sharedFrontierQueue->queue[i]; edge_idx = graph->vertices->edges_idx[v]; for(j = edge_idx ; j < (edge_idx + graph->vertices->out_degree[v]) ; j++) { u = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); int u_parent = stats->parents[u]; if(u_parent < 0 ) { if(__sync_bool_compare_and_swap(&stats->parents[u], u_parent, v)) { enArrayQueue(localFrontierQueue, u); mf += -(u_parent); stats->distances[u] = stats->distances[v] + 1; } } } } flushArrayQueueToShared(localFrontierQueue, sharedFrontierQueue); } return mf; } // bottom-up-step(graph, sharedFrontierQueue, next, parents) //pull // for v ∈ vertices do // if parents[v] = -1 then // for u ∈ neighbors[v] do // if u ∈ sharedFrontierQueue then // parents[v] ← u // next ← next ∪ {v} // break // end if // end for // end if // end for uint32_t bottomUpStepGraphCSRDualOrder(struct GraphCSR *graph, struct Bitmap *bitmapCurr, struct Bitmap *bitmapNext, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t j; uint32_t edge_idx; uint32_t out_degree; struct Vertex *vertices = NULL; uint32_t *sorted_edges_array = NULL; // uint32_t processed_nodes = bitmapCurr->numSetBits; uint32_t nf = 0; // number of vertices in sharedFrontierQueue // stats->processed_nodes += processed_nodes; #if DIRECTED vertices = graph->inverse_vertices; sorted_edges_array = graph->inverse_sorted_edges_array->edges_array_dest; #else vertices = graph->vertices; sorted_edges_array = graph->sorted_edges_array->edges_array_dest; #endif #pragma omp parallel for default(none) private(j,u,v,out_degree,edge_idx) shared(stats,bitmapCurr,bitmapNext,graph,vertices,sorted_edges_array) reduction(+:nf) schedule(dynamic, 1024) for(v = 0 ; v < graph->num_vertices ; v++) { out_degree = vertices->out_degree[v]; if(stats->parents[v] < 0) // optmization { edge_idx = vertices->edges_idx[v]; for(j = edge_idx ; j < (edge_idx + out_degree) ; j++) { u = EXTRACT_VALUE(sorted_edges_array[j]); if(getBit(bitmapCurr, u)) { stats->parents[v] = u; //we are not considering distance array as it is not implemented in AccelGraph stats->distances[v] = stats->distances[u] + 1; setBitAtomic(bitmapNext, v); nf++; break; } } } } return nf; } // ******************************************************************************************** // *************** GRID DataStructure ************** // ******************************************************************************************** struct BFSStats *breadthFirstSearchGraphGrid(struct Arguments *arguments, struct GraphGrid *graph) { struct BFSStats *stats = NULL; switch (arguments->pushpull) { case 0: // pull stats = breadthFirstSearchRowGraphGrid(arguments, graph); break; case 1: // push stats = breadthFirstSearchRowGraphGridBitmap(arguments, graph); break; case 2: // pull stats = breadthFirstSearchColumnGraphGrid(arguments, graph); break; case 3: // push stats = breadthFirstSearchColumnGraphGridBitmap(arguments, graph); break; default:// push stats = breadthFirstSearchRowGraphGrid(arguments, graph); break; } return stats; } // function STREAMVERTICES(Fv,F) // Sum = 0 // for each vertex do // if F(vertex) then // Sum += Fv(edge) // end if // end for // return Sum // end function // function STREAMEDGES(Fe,F) // Sum = 0 // for each active block do >> block with active edges // for each edge ∈ block do // if F(edge.arguments->source) then // Sum += Fe(edge) // end if // end for // end for // return Sum // end function //we assume that the edges are not sorted in each partition struct BFSStats *breadthFirstSearchRowGraphGrid(struct Arguments *arguments, struct GraphGrid *graph) { struct BFSStats *stats = newBFSStatsGraphGrid(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS-Row (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_iteration = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t P = arguments->algo_numThreads; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; #pragma omp parallel for for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } graphGridReset(graph); uint32_t processed_nodes = 0; Start(timer_iteration); enArrayQueue(sharedFrontierQueue, arguments->source); arrayQueueGenerateBitmap(sharedFrontierQueue); stats->parents[arguments->source] = arguments->source; // graphGridSetActivePartitions(graph->grid, arguments->source); graphGridSetActivePartitionsMap(graph->grid, arguments->source); Stop(timer_iteration); printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, ++processed_nodes, Seconds(timer_iteration)); stats->time_total += Seconds(timer_iteration); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { Start(timer_iteration); breadthFirstSearchStreamEdgesRowGraphGrid(graph, sharedFrontierQueue, localFrontierQueues, stats); Stop(timer_iteration); processed_nodes = sharedFrontierQueue->tail_next - sharedFrontierQueue->tail; slideWindowArrayQueue(sharedFrontierQueue); arrayQueueGenerateBitmap(sharedFrontierQueue); breadthFirstSearchSetActivePartitions(graph, sharedFrontierQueue); stats->time_total += Seconds(timer_iteration); printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, processed_nodes, Seconds(timer_iteration)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", sharedFrontierQueue->tail_next, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "**", sharedFrontierQueue->tail_next, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } // #pragma omp parallel for // for(i=0 ; i < P*P ; i++){ // freeArrayQueue(localFrontierQueuesL2[i]); // } // free(localFrontierQueuesL2); free(localFrontierQueues); free(timer_iteration); free(timer); return stats; } struct BFSStats *breadthFirstSearchColumnGraphGrid(struct Arguments *arguments, struct GraphGrid *graph) { struct BFSStats *stats = newBFSStatsGraphGrid(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS-Column (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_iteration = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t P = arguments->algo_numThreads; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; #pragma omp parallel for for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } graphGridReset(graph); uint32_t processed_nodes = 0; Start(timer_iteration); enArrayQueue(sharedFrontierQueue, arguments->source); arrayQueueGenerateBitmap(sharedFrontierQueue); stats->parents[arguments->source] = arguments->source; // graphGridSetActivePartitions(graph->grid, arguments->source); graphGridSetActivePartitionsMap(graph->grid, arguments->source); Stop(timer_iteration); printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, ++processed_nodes, Seconds(timer_iteration)); stats->time_total += Seconds(timer_iteration); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { Start(timer_iteration); breadthFirstSearchStreamEdgesColumnGraphGrid(graph, sharedFrontierQueue, localFrontierQueues, stats); Stop(timer_iteration); processed_nodes = sharedFrontierQueue->tail_next - sharedFrontierQueue->tail; slideWindowArrayQueue(sharedFrontierQueue); arrayQueueGenerateBitmap(sharedFrontierQueue); breadthFirstSearchSetActivePartitions(graph, sharedFrontierQueue); stats->time_total += Seconds(timer_iteration); printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, processed_nodes, Seconds(timer_iteration)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", sharedFrontierQueue->tail_next, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "**", sharedFrontierQueue->tail_next, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } // #pragma omp parallel for // for(i=0 ; i < P*P ; i++){ // freeArrayQueue(localFrontierQueuesL2[i]); // } // free(localFrontierQueuesL2); free(localFrontierQueues); free(timer_iteration); free(timer); return stats; } // function STREAMEDGES(Fe,F) // Sum = 0 // for each active block do >> block with active edges // for each edge ∈ block do // if F(edge.arguments->source) then // Sum += Fe(edge) // end if // end for // end for // return Sum // end function //we assume that the edges are not sorted in each partition void breadthFirstSearchStreamEdgesRowGraphGrid(struct GraphGrid *graph, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue **localFrontierQueues, struct BFSStats *stats) { // struct Timer* timer = (struct Timer*) malloc(sizeof(struct Timer)); uint32_t totalPartitions = 0; totalPartitions = graph->grid->num_partitions; // PxP uint32_t i; for (i = 0; i < totalPartitions; ++i) { uint32_t j; #pragma omp parallel for default(none) shared(i,stats,totalPartitions,localFrontierQueues ,sharedFrontierQueue, graph) for (j = 0; j < totalPartitions; ++j) { uint32_t t_id = omp_get_thread_num(); // uint32_t A = 0; struct ArrayQueue *localFrontierQueue = localFrontierQueues[t_id]; if(getBit(graph->grid->activePartitionsMap, (i * totalPartitions) + j)) { // #pragma omp task untied // { breadthFirstSearchPartitionGraphGrid(graph, &(graph->grid->partitions[(i * totalPartitions) + j]), sharedFrontierQueue, localFrontierQueue, stats); flushArrayQueueToShared(localFrontierQueue, sharedFrontierQueue); // } } } } // flushArrayQueueToShared(localFrontierQueue,sharedFrontierQueue); // } } void breadthFirstSearchStreamEdgesColumnGraphGrid(struct GraphGrid *graph, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue **localFrontierQueues, struct BFSStats *stats) { // struct Timer* timer = (struct Timer*) malloc(sizeof(struct Timer)); uint32_t totalPartitions = 0; totalPartitions = graph->grid->num_partitions; // PxP #pragma omp parallel default(none) shared(stats,totalPartitions,localFrontierQueues ,sharedFrontierQueue, graph) // #pragma omp single nowait { uint32_t t_id = omp_get_thread_num(); // uint32_t A = 0; struct ArrayQueue *localFrontierQueue = localFrontierQueues[t_id]; uint32_t j; #pragma omp for for (j = 0; j < totalPartitions; ++j) { uint32_t i; for (i = 0; i < totalPartitions; ++i) { if(getBit(graph->grid->activePartitionsMap, (i * totalPartitions) + j)) { // #pragma omp task untied // { breadthFirstSearchPartitionGraphGrid(graph, &(graph->grid->partitions[(i * totalPartitions) + j]), sharedFrontierQueue, localFrontierQueue, stats); flushArrayQueueToShared(localFrontierQueue, sharedFrontierQueue); // } } } } } // flushArrayQueueToShared(localFrontierQueue,sharedFrontierQueue); // } } void breadthFirstSearchPartitionGraphGrid(struct GraphGrid *graph, struct Partition *partition, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue *localFrontierQueue, struct BFSStats *stats) { uint32_t i; uint32_t src; uint32_t dest; // #pragma omp parallel default(none) private(i,src,dest) shared(localFrontierQueuesL2,graph,partition,sharedFrontierQueue,localFrontierQueue) // { // uint32_t t_id = omp_get_thread_num(); // struct ArrayQueue* localFrontierQueueL2 = localFrontierQueuesL2[t_id]; // #pragma omp for schedule(dynamic, 1024) for (i = 0; i < partition->num_edges; ++i) { src = partition->edgeList->edges_array_src[i]; dest = partition->edgeList->edges_array_dest[i]; int v_dest = stats->parents[dest]; if(isEnArrayQueued(sharedFrontierQueue, src) && (v_dest < 0)) { // if(__sync_bool_compare_and_swap(&stats->parents[dest], v_dest, src)) // { stats->parents[dest] = src; stats->distances[dest] = stats->distances[src] + 1; enArrayQueue(localFrontierQueue, dest); // } } } // flushArrayQueueToShared(localFrontierQueueL2,localFrontierQueue); // // slideWindowArrayQueue(localFrontierQueue); // localFrontierQueue->tail = localFrontierQueue->tail_next; // to apply to condition to the next flush // } } void breadthFirstSearchSetActivePartitions(struct GraphGrid *graph, struct ArrayQueue *sharedFrontierQueue) { uint32_t i; uint32_t v; // graphGridResetActivePartitions(graph->grid); graphGridResetActivePartitionsMap(graph->grid); #pragma omp parallel for default(none) shared(graph,sharedFrontierQueue) private(i,v) schedule(dynamic,1024) for(i = sharedFrontierQueue->head ; i < sharedFrontierQueue->tail; i++) { v = sharedFrontierQueue->queue[i]; // graphGridSetActivePartitions(graph->grid, v); // if(getBit(graph->grid->activePartitionsMap,i)) graphGridSetActivePartitionsMap(graph->grid, v); } } // ******************************************************************************************** // *************** GRID DataStructure/Bitmap Frontiers ************** // ******************************************************************************************** // function STREAMVERTICES(Fv,F) // Sum = 0 // for each vertex do // if F(vertex) then // Sum += Fv(edge) // end if // end for // return Sum // end function // function STREAMEDGES(Fe,F) // Sum = 0 // for each active block do >> block with active edges // for each edge ∈ block do // if F(edge.arguments->source) then // Sum += Fe(edge) // end if // end for // end for // return Sum // end function //we assume that the edges are not sorted in each partition struct BFSStats *breadthFirstSearchRowGraphGridBitmap(struct Arguments *arguments, struct GraphGrid *graph) { struct BFSStats *stats = newBFSStatsGraphGrid(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS-Row Bitmap (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_iteration = (struct Timer *) malloc(sizeof(struct Timer)); struct Bitmap *FrontierBitmapCurr = newBitmap(graph->num_vertices); struct Bitmap *FrontierBitmapNext = newBitmap(graph->num_vertices); graphGridReset(graph); uint32_t processed_nodes = 0; uint32_t total_processed_nodes = 0; Start(timer_iteration); setBit(FrontierBitmapNext, arguments->source); stats->parents[arguments->source] = arguments->source; processed_nodes = getNumOfSetBits(FrontierBitmapNext); swapBitmaps (&FrontierBitmapCurr, &FrontierBitmapNext); clearBitmap(FrontierBitmapNext); // printf("%u %u\n",getNumOfSetBits(FrontierBitmapCurr),getNumOfSetBits(FrontierBitmapNext) ); breadthFirstSearchSetActivePartitionsBitmap(graph, FrontierBitmapCurr); Stop(timer_iteration); total_processed_nodes += processed_nodes; printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, processed_nodes, Seconds(timer_iteration)); stats->time_total += Seconds(timer_iteration); Start(timer); while(processed_nodes) // start while { Start(timer_iteration); breadthFirstSearchStreamEdgesRowGraphGridBitmap(graph, FrontierBitmapCurr, FrontierBitmapNext, stats); Stop(timer_iteration); processed_nodes = getNumOfSetBits(FrontierBitmapNext); swapBitmaps (&FrontierBitmapCurr, &FrontierBitmapNext); clearBitmap(FrontierBitmapNext); breadthFirstSearchSetActivePartitionsBitmap(graph, FrontierBitmapCurr); total_processed_nodes += processed_nodes; stats->time_total += Seconds(timer_iteration); printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, processed_nodes, Seconds(timer_iteration)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", total_processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "**", total_processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeBitmap(FrontierBitmapCurr); freeBitmap(FrontierBitmapNext); free(timer_iteration); free(timer); return stats; } struct BFSStats *breadthFirstSearchColumnGraphGridBitmap(struct Arguments *arguments, struct GraphGrid *graph) { struct BFSStats *stats = newBFSStatsGraphGrid(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS-Column Bitmap (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_iteration = (struct Timer *) malloc(sizeof(struct Timer)); struct Bitmap *FrontierBitmapCurr = newBitmap(graph->num_vertices); struct Bitmap *FrontierBitmapNext = newBitmap(graph->num_vertices); graphGridReset(graph); uint32_t processed_nodes = 0; uint32_t total_processed_nodes = 0; Start(timer_iteration); setBit(FrontierBitmapNext, arguments->source); stats->parents[arguments->source] = arguments->source; processed_nodes = getNumOfSetBits(FrontierBitmapNext); swapBitmaps (&FrontierBitmapCurr, &FrontierBitmapNext); clearBitmap(FrontierBitmapNext); // printf("%u %u\n",getNumOfSetBits(FrontierBitmapCurr),getNumOfSetBits(FrontierBitmapNext) ); breadthFirstSearchSetActivePartitionsBitmap(graph, FrontierBitmapCurr); Stop(timer_iteration); total_processed_nodes += processed_nodes; printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, processed_nodes, Seconds(timer_iteration)); stats->time_total += Seconds(timer_iteration); Start(timer); while(processed_nodes) // start while { Start(timer_iteration); breadthFirstSearchStreamEdgesColumnGraphGridBitmap(graph, FrontierBitmapCurr, FrontierBitmapNext, stats); Stop(timer_iteration); processed_nodes = getNumOfSetBits(FrontierBitmapNext); swapBitmaps (&FrontierBitmapCurr, &FrontierBitmapNext); clearBitmap(FrontierBitmapNext); breadthFirstSearchSetActivePartitionsBitmap(graph, FrontierBitmapCurr); total_processed_nodes += processed_nodes; stats->time_total += Seconds(timer_iteration); printf("| %-15u | %-15u | %-15f | \n", stats->iteration++, processed_nodes, Seconds(timer_iteration)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", total_processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "**", total_processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeBitmap(FrontierBitmapCurr); freeBitmap(FrontierBitmapNext); free(timer_iteration); free(timer); return stats; } // function STREAMEDGES(Fe,F) // Sum = 0 // for each active block do >> block with active edges // for each edge ∈ block do // if F(edge.arguments->source) then // Sum += Fe(edge) // end if // end for // end for // return Sum // end function //we assume that the edges are not sorted in each partition void breadthFirstSearchStreamEdgesRowGraphGridBitmap(struct GraphGrid *graph, struct Bitmap *FrontierBitmapCurr, struct Bitmap *FrontierBitmapNext, struct BFSStats *stats) { // struct Timer* timer = (struct Timer*) malloc(sizeof(struct Timer)); uint32_t totalPartitions = 0; totalPartitions = graph->grid->num_partitions; // PxP uint32_t i; for (i = 0; i < totalPartitions; ++i) { uint32_t j; #pragma omp parallel for default(none) shared(i,stats,totalPartitions,FrontierBitmapCurr ,FrontierBitmapNext, graph) for (j = 0; j < totalPartitions; ++j) { if(getBit(graph->grid->activePartitionsMap, (i * totalPartitions) + j) && graph->grid->partitions[(i * totalPartitions) + j].num_edges) { breadthFirstSearchPartitionGraphGridBitmap(graph, &(graph->grid->partitions[(i * totalPartitions) + j]), FrontierBitmapCurr, FrontierBitmapNext, stats); } } } } void breadthFirstSearchStreamEdgesColumnGraphGridBitmap(struct GraphGrid *graph, struct Bitmap *FrontierBitmapCurr, struct Bitmap *FrontierBitmapNext, struct BFSStats *stats) { // struct Timer* timer = (struct Timer*) malloc(sizeof(struct Timer)); uint32_t totalPartitions = 0; totalPartitions = graph->grid->num_partitions; // PxP #pragma omp parallel default(none) shared(stats,totalPartitions,FrontierBitmapCurr ,FrontierBitmapNext, graph) // #pragma omp single nowait { uint32_t j; // #pragma omp for schedule(dynamic, 256) #pragma omp for for (j = 0; j < totalPartitions; ++j) { uint32_t i; for (i = 0; i < totalPartitions; ++i) { if(getBit(graph->grid->activePartitionsMap, (i * totalPartitions) + j) && graph->grid->partitions[(i * totalPartitions) + j].num_edges) { breadthFirstSearchPartitionGraphGridBitmap(graph, &(graph->grid->partitions[(i * totalPartitions) + j]), FrontierBitmapCurr, FrontierBitmapNext, stats); } } } } } void breadthFirstSearchPartitionGraphGridBitmap(struct GraphGrid *graph, struct Partition *partition, struct Bitmap *FrontierBitmapCurr, struct Bitmap *FrontierBitmapNext, struct BFSStats *stats) { uint32_t i; uint32_t src; uint32_t dest; for (i = 0; i < partition->num_edges; ++i) { src = partition->edgeList->edges_array_src[i]; dest = partition->edgeList->edges_array_dest[i]; int v_dest = stats->parents[dest]; if((v_dest < 0)) { if(getBit(FrontierBitmapCurr, src)) { // if(__sync_bool_compare_and_swap(&stats->parents[dest], v_dest, src)) // { stats->parents[dest] = src; stats->distances[dest] = stats->distances[src] + 1; setBitAtomic(FrontierBitmapNext, dest); // } } } } } void breadthFirstSearchSetActivePartitionsBitmap(struct GraphGrid *graph, struct Bitmap *FrontierBitmap) { uint32_t i; graphGridResetActivePartitionsMap(graph->grid); #pragma omp parallel for default(none) shared(graph,FrontierBitmap) private(i) schedule(dynamic,1024) for(i = 0 ; i < FrontierBitmap->size; i++) { if(getBit(FrontierBitmap, i)) graphGridSetActivePartitionsMap(graph->grid, i); } } // ******************************************************************************************** // *************** ArrayList DataStructure ************** // ******************************************************************************************** struct BFSStats *breadthFirstSearchGraphAdjArrayList(struct Arguments *arguments, struct GraphAdjArrayList *graph) { struct BFSStats *stats = NULL; switch (arguments->pushpull) { case 0: // pull stats = breadthFirstSearchPullGraphAdjArrayList(arguments, graph); break; case 1: // push stats = breadthFirstSearchPushGraphAdjArrayList(arguments, graph); break; case 2: // pull/push stats = breadthFirstSearchDirectionOptimizedGraphAdjArrayList(arguments, graph); break; default:// push stats = breadthFirstSearchDirectionOptimizedGraphAdjArrayList(arguments, graph); break; } return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPullGraphAdjArrayList(struct Arguments *arguments, struct GraphAdjArrayList *graph) { struct BFSStats *stats = newBFSStatsGraphAdjArrayList(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PULL/BU (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t nf = 0; // number of vertices in sharedFrontierQueue Start(timer_inner); setBit(sharedFrontierQueue->q_bitmap_next, arguments->source); sharedFrontierQueue->q_bitmap_next->numSetBits = 1; stats->parents[arguments->source] = arguments->source; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while (sharedFrontierQueue->q_bitmap->numSetBits) { Start(timer_inner); nf = bottomUpStepGraphAdjArrayList(graph, sharedFrontierQueue->q_bitmap, sharedFrontierQueue->q_bitmap_next, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = nf; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); //stats stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPushGraphAdjArrayList(struct Arguments *arguments, struct GraphAdjArrayList *graph) { struct BFSStats *stats = newBFSStatsGraphAdjArrayList(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PUSH/TD (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t P = arguments->algo_numThreads; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { Start(timer_inner); topDownStepGraphAdjArrayList(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchDirectionOptimizedGraphAdjArrayList(struct Arguments *arguments, struct GraphAdjArrayList *graph) { struct BFSStats *stats = newBFSStatsGraphAdjArrayList(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); struct Bitmap *bitmapCurr = newBitmap(graph->num_vertices); struct Bitmap *bitmapNext = newBitmap(graph->num_vertices); uint32_t P = arguments->algo_numThreads; uint32_t mu = graph->num_edges; // number of edges to check from sharedFrontierQueue uint32_t mf = graph->vertices[arguments->source].out_degree; // number of edges from unexplored verticies uint32_t nf = 0; // number of vertices in sharedFrontierQueue uint32_t nf_prev = 0; // number of vertices in sharedFrontierQueue uint32_t n = graph->num_vertices; // number of nodes uint32_t alpha = 15; uint32_t beta = 18; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { if(mf > (mu / alpha)) { Start(timer_inner); arrayQueueToBitmap(sharedFrontierQueue, bitmapCurr); nf = sizeArrayQueue(sharedFrontierQueue); Stop(timer_inner); printf("| E %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); do { Start(timer_inner); nf_prev = nf; nf = bottomUpStepGraphAdjArrayList(graph, bitmapCurr, bitmapNext, stats); swapBitmaps(&bitmapCurr, &bitmapNext); clearBitmap(bitmapNext); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } while(( nf > nf_prev) || // growing; ( nf > (n / beta))); Start(timer_inner); bitmapToArrayQueue(bitmapCurr, sharedFrontierQueue, localFrontierQueues); Stop(timer_inner); printf("| C %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); mf = 1; } else { Start(timer_inner); mu -= mf; mf = topDownStepGraphAdjArrayList(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head;; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); freeBitmap(bitmapNext); freeBitmap(bitmapCurr); free(timer); free(timer_inner); return stats; } // top-down-step(graph, sharedFrontierQueue, next, parents) // for v ∈ sharedFrontierQueue do // for u ∈ neighbors[v] do // if parents[u] = -1 then // parents[u] ← v // next ← next ∪ {u} // end if // end for // end for uint32_t topDownStepGraphAdjArrayList(struct GraphAdjArrayList *graph, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue **localFrontierQueues, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t i; uint32_t j; uint32_t mf = 0; uint32_t out_degree; struct EdgeList *outNodes; #pragma omp parallel default (none) private(out_degree,outNodes,u,v,j,i) shared(stats,localFrontierQueues,graph,sharedFrontierQueue,mf) { uint32_t t_id = omp_get_thread_num(); struct ArrayQueue *localFrontierQueue = localFrontierQueues[t_id]; #pragma omp for reduction(+:mf) schedule(auto) for(i = sharedFrontierQueue->head ; i < sharedFrontierQueue->tail; i++) { v = sharedFrontierQueue->queue[i]; // v = deArrayQueue(sharedFrontierQueue); outNodes = graph->vertices[v].outNodes; out_degree = graph->vertices[v].out_degree; for(j = 0 ; j < out_degree ; j++) { u = outNodes->edges_array_dest[j]; int u_parent = stats->parents[u]; if(u_parent < 0 ) { if(__sync_bool_compare_and_swap(&stats->parents[u], u_parent, v)) { enArrayQueue(localFrontierQueue, u); stats->distances[u] = stats->distances[v] + 1; mf += -(u_parent); } } } } flushArrayQueueToShared(localFrontierQueue, sharedFrontierQueue); } return mf; } // bottom-up-step(graph, sharedFrontierQueue, next, parents) // for v ∈ vertices do // if parents[v] = -1 then // for u ∈ neighbors[v] do // if u ∈ sharedFrontierQueue then // parents[v] ← u // next ← next ∪ {v} // break // end if // end for // end if // end for uint32_t bottomUpStepGraphAdjArrayList(struct GraphAdjArrayList *graph, struct Bitmap *bitmapCurr, struct Bitmap *bitmapNext, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t j; // uint32_t processed_nodes = bitmapCurr->numSetBits; uint32_t nf = 0; // number of vertices in sharedFrontierQueue // stats->processed_nodes += processed_nodes; uint32_t degree; struct EdgeList *Nodes; #pragma omp parallel for default(none) private(Nodes,j,u,v,degree) shared(stats,bitmapCurr,bitmapNext,graph) reduction(+:nf) schedule(dynamic, 1024) for(v = 0 ; v < graph->num_vertices ; v++) { if(stats->parents[v] < 0) // optmization { #if DIRECTED // will look at the other neighbours if directed by using inverese edge list Nodes = graph->vertices[v].inNodes; degree = graph->vertices[v].in_degree; #else Nodes = graph->vertices[v].outNodes; degree = graph->vertices[v].out_degree; #endif for(j = 0 ; j < (degree) ; j++) { u = Nodes->edges_array_dest[j]; if(getBit(bitmapCurr, u)) { stats->parents[v] = u; setBitAtomic(bitmapNext, v); stats->distances[v] = stats->distances[u] + 1; nf++; break; } } } } return nf; } // ******************************************************************************************** // *************** LinkedList DataStructure ************** // ******************************************************************************************** struct BFSStats *breadthFirstSearchGraphAdjLinkedList(struct Arguments *arguments, struct GraphAdjLinkedList *graph) { struct BFSStats *stats = NULL; switch (arguments->pushpull) { case 0: // pull stats = breadthFirstSearchPullGraphAdjLinkedList(arguments, graph); break; case 1: // push stats = breadthFirstSearchPushGraphAdjLinkedList(arguments, graph); break; case 2: // pull/push stats = breadthFirstSearchDirectionOptimizedGraphAdjLinkedList(arguments, graph); break; default:// push stats = breadthFirstSearchDirectionOptimizedGraphAdjLinkedList(arguments, graph); break; } return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPullGraphAdjLinkedList(struct Arguments *arguments, struct GraphAdjLinkedList *graph) { struct BFSStats *stats = newBFSStatsGraphAdjLinkedList(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PULL/BU (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t nf = 0; // number of vertices in sharedFrontierQueue Start(timer_inner); setBit(sharedFrontierQueue->q_bitmap_next, arguments->source); sharedFrontierQueue->q_bitmap_next->numSetBits = 1; stats->parents[arguments->source] = arguments->source; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); stats->time_total += Seconds(timer_inner); printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while (sharedFrontierQueue->q_bitmap->numSetBits) { Start(timer_inner); nf = bottomUpStepGraphAdjLinkedList(graph, sharedFrontierQueue->q_bitmap, sharedFrontierQueue->q_bitmap_next, stats); sharedFrontierQueue->q_bitmap_next->numSetBits = nf; swapBitmaps(&sharedFrontierQueue->q_bitmap, &sharedFrontierQueue->q_bitmap_next); clearBitmap(sharedFrontierQueue->q_bitmap_next); Stop(timer_inner); //stats stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchPushGraphAdjLinkedList(struct Arguments *arguments, struct GraphAdjLinkedList *graph) { struct BFSStats *stats = newBFSStatsGraphAdjLinkedList(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PUSH/TD (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); uint32_t P = arguments->algo_numThreads; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { Start(timer_inner); topDownStepGraphAdjLinkedList(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); free(timer); free(timer_inner); return stats; } // breadth-first-search(graph, arguments->source) // sharedFrontierQueue ← {arguments->source} // next ← {} // parents ← [-1,-1,. . . -1] // while sharedFrontierQueue 6= {} do // top-down-step(graph, sharedFrontierQueue, next, parents) // sharedFrontierQueue ← next // next ← {} // end while // return parents struct BFSStats *breadthFirstSearchDirectionOptimizedGraphAdjLinkedList(struct Arguments *arguments, struct GraphAdjLinkedList *graph) { struct BFSStats *stats = newBFSStatsGraphAdjLinkedList(graph); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting BFS PULL/PUSH (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayQueue *sharedFrontierQueue = newArrayQueue(graph->num_vertices); struct Bitmap *bitmapCurr = newBitmap(graph->num_vertices); struct Bitmap *bitmapNext = newBitmap(graph->num_vertices); uint32_t P = arguments->algo_numThreads; uint32_t mu = graph->num_edges; // number of edges to check from sharedFrontierQueue uint32_t mf = graph->vertices[arguments->source].out_degree; // number of edges from unexplored verticies uint32_t nf = 0; // number of vertices in sharedFrontierQueue uint32_t nf_prev = 0; // number of vertices in sharedFrontierQueue uint32_t n = graph->num_vertices; // number of nodes uint32_t alpha = 15; uint32_t beta = 18; struct ArrayQueue **localFrontierQueues = (struct ArrayQueue **) my_malloc( P * sizeof(struct ArrayQueue *)); uint32_t i; for(i = 0 ; i < P ; i++) { localFrontierQueues[i] = newArrayQueue(graph->num_vertices); } Start(timer_inner); enArrayQueue(sharedFrontierQueue, arguments->source); // setBit(sharedFrontierQueue->q_bitmap,arguments->source); stats->parents[arguments->source] = arguments->source; Stop(timer_inner); stats->time_total += Seconds(timer_inner); // graph->vertices[arguments->source].visited = 1; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, ++stats->processed_nodes, Seconds(timer_inner)); Start(timer); while(!isEmptyArrayQueue(sharedFrontierQueue)) // start while { if(mf > (mu / alpha)) { Start(timer_inner); arrayQueueToBitmap(sharedFrontierQueue, bitmapCurr); nf = sizeArrayQueue(sharedFrontierQueue); Stop(timer_inner); printf("| E %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); do { Start(timer_inner); nf_prev = nf; nf = bottomUpStepGraphAdjLinkedList(graph, bitmapCurr, bitmapNext, stats); swapBitmaps(&bitmapCurr, &bitmapNext); clearBitmap(bitmapNext); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += nf; printf("| BU %-12u | %-15u | %-15f | \n", stats->iteration++, nf, Seconds(timer_inner)); } while(( nf > nf_prev) || // growing; ( nf > (n / beta))); Start(timer_inner); bitmapToArrayQueue(bitmapCurr, sharedFrontierQueue, localFrontierQueues); Stop(timer_inner); printf("| C %-12s | %-15s | %-15f | \n", " ", " ", Seconds(timer_inner)); mf = 1; } else { Start(timer_inner); mu -= mf; mf = topDownStepGraphAdjLinkedList(graph, sharedFrontierQueue, localFrontierQueues, stats); slideWindowArrayQueue(sharedFrontierQueue); Stop(timer_inner); //stats collection stats->time_total += Seconds(timer_inner); stats->processed_nodes += sharedFrontierQueue->tail - sharedFrontierQueue->head;; printf("| TD %-12u | %-15u | %-15f | \n", stats->iteration++, sharedFrontierQueue->tail - sharedFrontierQueue->head, Seconds(timer_inner)); } } // end while Stop(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); for(i = 0 ; i < P ; i++) { freeArrayQueue(localFrontierQueues[i]); } free(localFrontierQueues); freeArrayQueue(sharedFrontierQueue); freeBitmap(bitmapNext); freeBitmap(bitmapCurr); free(timer); free(timer_inner); return stats; } // top-down-step(graph, sharedFrontierQueue, next, parents) // for v ∈ sharedFrontierQueue do // for u ∈ neighbors[v] do // if parents[u] = -1 then // parents[u] ← v // next ← next ∪ {u} // end if // end for // end for uint32_t topDownStepGraphAdjLinkedList(struct GraphAdjLinkedList *graph, struct ArrayQueue *sharedFrontierQueue, struct ArrayQueue **localFrontierQueues, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t i; uint32_t j; uint32_t mf = 0; uint32_t out_degree; struct AdjLinkedListNode *outNodes; #pragma omp parallel default (none) private(out_degree,outNodes,u,v,j,i) shared(stats,localFrontierQueues,graph,sharedFrontierQueue,mf) { uint32_t t_id = omp_get_thread_num(); struct ArrayQueue *localFrontierQueue = localFrontierQueues[t_id]; #pragma omp for reduction(+:mf) schedule(auto) for(i = sharedFrontierQueue->head ; i < sharedFrontierQueue->tail; i++) { v = sharedFrontierQueue->queue[i]; // v = deArrayQueue(sharedFrontierQueue); outNodes = graph->vertices[v].outNodes; out_degree = graph->vertices[v].out_degree; for(j = 0 ; j < out_degree ; j++) { u = outNodes->dest; outNodes = outNodes->next; // travers pointer int u_parent = stats->parents[u]; if(u_parent < 0 ) { if(__sync_bool_compare_and_swap(&stats->parents[u], u_parent, v)) { enArrayQueue(localFrontierQueue, u); stats->distances[u] = stats->distances[v] + 1; mf += -(u_parent); } } } } flushArrayQueueToShared(localFrontierQueue, sharedFrontierQueue); } return mf; } // bottom-up-step(graph, sharedFrontierQueue, next, parents) // for v ∈ vertices do // if parents[v] = -1 then // for u ∈ neighbors[v] do // if u ∈ sharedFrontierQueue then // parents[v] ← u // next ← next ∪ {v} // break // end if // end for // end if // end for uint32_t bottomUpStepGraphAdjLinkedList(struct GraphAdjLinkedList *graph, struct Bitmap *bitmapCurr, struct Bitmap *bitmapNext, struct BFSStats *stats) { uint32_t v; uint32_t u; uint32_t j; // uint32_t processed_nodes = bitmapCurr->numSetBits; uint32_t nf = 0; // number of vertices in sharedFrontierQueue // stats->processed_nodes += processed_nodes; uint32_t degree; struct AdjLinkedListNode *Nodes; #pragma omp parallel for default(none) private(Nodes,j,u,v,degree) shared(stats,bitmapCurr,bitmapNext,graph) reduction(+:nf) schedule(dynamic, 1024) for(v = 0 ; v < graph->num_vertices ; v++) { if(stats->parents[v] < 0) // optmization { #if DIRECTED // will look at the other neighbours if directed by using inverese edge list Nodes = graph->vertices[v].inNodes; degree = graph->vertices[v].in_degree; #else Nodes = graph->vertices[v].outNodes; degree = graph->vertices[v].out_degree; #endif for(j = 0 ; j < (degree) ; j++) { u = Nodes->dest; Nodes = Nodes->next; if(getBit(bitmapCurr, u)) { stats->parents[v] = u; setBitAtomic(bitmapNext, v); stats->distances[v] = stats->distances[u] + 1; nf++; break; } } } } return nf; }
DUtils.h
#ifndef _D_UTILS_H_ #define _D_UTILS_H_ #include <stdio.h> #include <sys/ioctl.h> #include <sys/select.h> #include <termios.h> // XXX JOE #include <stropts.h> #include <unistd.h> namespace smil { struct index { size_t x; size_t y; size_t z; size_t o; index() { } index(const index &i) : x(i.x), y(i.y), z(i.z), o(i.o) { } }; #define WS ImDtTypes<labelT>::max() #define IndexToCoor(a) \ a.z = a.o / nbrPixelsInSlice; \ a.y = (a.o % nbrPixelsInSlice) / S[0]; \ a.x = a.o % S[0]; #define CoorToIndex(a) a.o = a.x + a.y * S[0] + a.z * nbrPixelsInSlice #define ForEachPixel(a) \ for (size_t i = 0; i < nbrPixels; ++i) { \ a.o = i; \ IndexToCoor(a); #define ENDForEachPixel } #define ForEachNeighborOf(a, b) \ for (pts = 0; pts < sePtsNumber; ++pts) { \ b.x = a.x + se.points[pts].x; \ b.y = a.y + se.points[pts].y; \ b.z = a.z + se.points[pts].z; \ if (b.x < S[0] && b.y < S[1] && b.z < S[2]) { \ CoorToIndex(b); #define ENDForEachNeighborOf \ } \ } #define LIVEVERSION template <class T1, class T2> void geoDistance(const Image<T1> &_in_, Image<T2> &_out_, const StrElt &se) { queue<size_t> *c1 = new queue<size_t>(), *c2 = new queue<size_t>(), *tmp; T1 *in = _in_.getPixels(); T2 *out = _out_.getPixels(); index p, q; UINT sePtsNumber = se.points.size(); UINT pts; size_t S[3]; _in_.getSize(S); size_t nbrPixelsInSlice = S[0] * S[1]; size_t nbrPixels = nbrPixelsInSlice * S[2]; ForEachPixel(p) { if (out[p.o] == 1) { c2->push(p.o); } } ENDForEachPixel T2 d = 1; while (!c2->empty()) { tmp = c1; c1 = c2; c2 = tmp; ++d; while (!c1->empty()) { p.o = c1->front(); c1->pop(); IndexToCoor(p); ForEachNeighborOf(p, q) { if (in[p.o] == in[q.o] && out[q.o] == 0) { out[q.o] = d; c2->push(q.o); } } ENDForEachNeighborOf } } delete c1; delete c2; } template <class T> RES_T applyThreshold(const Image<T> &_im_, const vector<T> &modes, Image<T> &_out_) { size_t S[3]; _im_.getSize(S); size_t s = S[0] * S[1] * S[2]; T *out = _out_.getPixels(); T *im = _im_.getPixels(); UINT nthreads = Core::getInstance()->getNumberOfThreads(); #pragma omp parallel for num_threads(nthreads) for (size_t p = 0; p < s; ++p) { out[p] = modes[im[p]]; } return RES_OK; } int __kbhit__() { static const int STDIN = 0; static bool initialized = false; if (!initialized) { termios term; tcgetattr(STDIN, &term); term.c_lflag &= ~ICANON; tcsetattr(STDIN, TCSANOW, &term); setbuf(stdin, NULL); initialized = true; } int bytesWaiting; ioctl(STDIN, FIONREAD, &bytesWaiting); return bytesWaiting; } bool __pause__() { int ch; struct termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch == ' '; } inline bool __letthrough__() { return __kbhit__() != 0; } } // namespace smil #endif // _D_UTILS_H_
DistanceTableData.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign // Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign // Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory // // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign ////////////////////////////////////////////////////////////////////////////////////// #ifndef QMCPLUSPLUS_DISTANCETABLEDATAIMPL_H #define QMCPLUSPLUS_DISTANCETABLEDATAIMPL_H #include "Particle/ParticleSet.h" #include "OhmmsPETE/OhmmsVector.h" #include "OhmmsPETE/OhmmsMatrix.h" #include "CPU/SIMD/aligned_allocator.hpp" #include "OhmmsSoA/VectorSoaContainer.h" #include <limits> #include <bitset> namespace qmcplusplus { class ResourceCollection; /** @ingroup nnlist * @brief Abstract class to manage pair data between two ParticleSets. * * Each DistanceTableData object is fined by Source and Target of ParticleSet types. * */ class DistanceTableData { public: static constexpr unsigned DIM = OHMMS_DIM; using IndexType = QMCTraits::IndexType; using RealType = QMCTraits::RealType; using PosType = QMCTraits::PosType; using DistRow = Vector<RealType, aligned_allocator<RealType>>; using DisplRow = VectorSoaContainer<RealType, DIM>; protected: const ParticleSet* Origin; const int N_sources; const int N_targets; /**defgroup SoA data */ /*@{*/ /** distances_[i][j] , [N_targets][N_sources] * Note: Derived classes decide if it is a memory view or the actual storage * For derived AA, only the lower triangle (j<i) is defined and up-to-date after pbyp move. * The upper triangle is symmetric to the lower one only when the full table is evaluated from scratch. * Avoid using the upper triangle because we may change the code to only allocate the lower triangle part. * For derived AB, the full table is up-to-date after pbyp move */ std::vector<DistRow> distances_; /** displacements_[N_targets]x[3][N_sources] * Note: Derived classes decide if it is a memory view or the actual storage * displacements_[i][j] = r_A2[j] - r_A1[i], the opposite sign of AoS dr * For derived AA, A1=A2=A, only the lower triangle (j<i) is defined. * For derived AB, A1=A, A2=B, the full table is allocated. */ std::vector<DisplRow> displacements_; /** temp_r */ DistRow temp_r_; /** temp_dr */ DisplRow temp_dr_; /*@}*/ /** whether full table needs to be ready at anytime or not * Optimization can be implemented during forward PbyP move when the full table is not needed all the time. * DT consumers should know if full table is needed or not and request via addTable. */ bool need_full_table_; /** set to particle id after move() with prepare_old = true. -1 means not prepared. * It is intended only for safety checks, not for codepath selection. */ int old_prepared_elec_id; ///name of the table const std::string name_; public: ///constructor using source and target ParticleSet DistanceTableData(const ParticleSet& source, const ParticleSet& target) : Origin(&source), N_sources(source.getTotalNum()), N_targets(target.getTotalNum()), need_full_table_(false), old_prepared_elec_id(-1), name_(source.getName() + "_" + target.getName()) {} ///virutal destructor virtual ~DistanceTableData() = default; ///get need_full_table_ inline bool getFullTableNeeds() const { return need_full_table_; } ///set need_full_table_ inline void setFullTableNeeds(bool is_needed) { need_full_table_ = is_needed; } ///return the name of table inline const std::string& getName() const { return name_; } ///returns the reference the origin particleset const ParticleSet& origin() const { return *Origin; } ///returns the number of centers inline IndexType centers() const { return Origin->getTotalNum(); } ///returns the number of centers inline IndexType targets() const { return N_targets; } ///returns the number of source particles inline IndexType sources() const { return N_sources; } /** return full table distances */ const std::vector<DistRow>& getDistances() const { return distances_; } /** return full table displacements */ const std::vector<DisplRow>& getDisplacements() const { return displacements_; } /** return a row of distances for a given target particle */ const DistRow& getDistRow(int iel) const { return distances_[iel]; } /** return a row of displacements for a given target particle */ const DisplRow& getDisplRow(int iel) const { return displacements_[iel]; } /** return old distances set up by move() for optimized distance table consumers */ virtual const DistRow& getOldDists() const { APP_ABORT("DistanceTableData::getOldDists is used incorrectly! Contact developers on github."); return temp_r_; // dummy return to avoid compiler warning. } /** return old displacements set up by move() for optimized distance table consumers */ virtual const DisplRow& getOldDispls() const { APP_ABORT("DistanceTableData::getOldDispls is used incorrectly! Contact developers on github."); return temp_dr_; // dummy return to avoid compiler warning. } /** return the temporary distances when a move is proposed */ const DistRow& getTempDists() const { return temp_r_; } /** return the temporary displacements when a move is proposed */ const DisplRow& getTempDispls() const { return temp_dr_; } /** evaluate the full Distance Table * @param P the target particle set */ virtual void evaluate(ParticleSet& P) = 0; virtual void mw_evaluate(const RefVectorWithLeader<DistanceTableData>& dt_list, const RefVectorWithLeader<ParticleSet>& p_list) const { #pragma omp parallel for for (int iw = 0; iw < dt_list.size(); iw++) dt_list[iw].evaluate(p_list[iw]); } /** recompute multi walker internal data, recompute * @param dt_list the distance table batch * @param p_list the target particle set batch * @param recompute if true, must recompute. Otherwise, implementation dependent. */ virtual void mw_recompute(const RefVectorWithLeader<DistanceTableData>& dt_list, const RefVectorWithLeader<ParticleSet>& p_list, const std::vector<bool>& recompute) const { #pragma omp parallel for for (int iw = 0; iw < dt_list.size(); iw++) if (recompute[iw]) dt_list[iw].evaluate(p_list[iw]); } /** evaluate the temporary pair relations when a move is proposed * @param P the target particle set * @param rnew proposed new position * @param iat the particle to be moved * @param prepare_old if true, prepare (temporary) old distances and displacements for using getOldDists and getOldDispls functions in acceptMove. * * Note: some distance table consumers (WaveFunctionComponent) have optimized code paths which require prepare_old = true for accepting a move. * Drivers/Hamiltonians know whether moves will be accepted or not and manage this flag when calling ParticleSet::makeMoveXXX functions. */ virtual void move(const ParticleSet& P, const PosType& rnew, const IndexType iat = 0, bool prepare_old = true) = 0; virtual void mw_move(const RefVectorWithLeader<DistanceTableData>& dt_list, const RefVectorWithLeader<ParticleSet>& p_list, const std::vector<PosType>& rnew_list, const IndexType iat = 0, bool prepare_old = true) const { #pragma omp parallel for for (int iw = 0; iw < dt_list.size(); iw++) dt_list[iw].move(p_list[iw], rnew_list[iw], iat, prepare_old); } /** update the distance table by the pair relations from the temporal position. * Used when a move is accepted in regular mode * @param iat the particle with an accepted move */ virtual void update(IndexType jat) = 0; /** fill partially the distance table by the pair relations from the temporary or old particle position. * Used in forward mode when a move is reject * @param iat the particle with an accepted move * @param from_temp if true, copy from temp. if false, copy from old */ virtual void updatePartial(IndexType jat, bool from_temp) { if (from_temp) update(jat); } /** build a compact list of a neighbor for the iat source * @param iat source particle id * @param rcut cutoff radius * @param jid compressed index * @param dist compressed distance * @param displ compressed displacement * @return number of target particles within rcut */ virtual size_t get_neighbors(int iat, RealType rcut, int* restrict jid, RealType* restrict dist, PosType* restrict displ) const { return 0; } /** find the first nearest neighbor * @param iat source particle id * @param r distance * @param dr displacement * @param newpos if true, use the data in temp_r_ and temp_dr_ for the proposed move. * if false, use the data in distance_[iat] and displacements_[iat] * @return the id of the nearest particle, -1 not found */ virtual int get_first_neighbor(IndexType iat, RealType& r, PosType& dr, bool newpos) const { APP_ABORT("DistanceTableData::get_first_neighbor is not implemented in calling base class"); return 0; } inline void print(std::ostream& os) { APP_ABORT("DistanceTableData::print is not supported") //os << "Table " << Origin->getName() << std::endl; //for (int i = 0; i < r_m.size(); i++) // os << r_m[i] << " "; //os << std::endl; } /// initialize a shared resource and hand it to a collection virtual void createResource(ResourceCollection& collection) const {} /// acquire a shared resource from a collection virtual void acquireResource(ResourceCollection& collection, const RefVectorWithLeader<DistanceTableData>& dt_list) const {} /// return a shared resource to a collection virtual void releaseResource(ResourceCollection& collection, const RefVectorWithLeader<DistanceTableData>& dt_list) const {} }; } // namespace qmcplusplus #endif
GB_unaryop__minv_uint16_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_uint16_fp64 // op(A') function: GB_tran__minv_uint16_fp64 // C type: uint16_t // A type: double // cast: uint16_t cij ; GB_CAST_UNSIGNED(cij,aij,16) // unaryop: cij = GB_IMINV_UNSIGNED (aij, 16) #define GB_ATYPE \ double #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 16) ; // casting #define GB_CASTING(z, x) \ uint16_t z ; GB_CAST_UNSIGNED(z,x,16) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT16 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint16_fp64 ( uint16_t *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint16_fp64 ( 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
composite.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/memory_.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resample.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImage() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImage method is: % % MagickBooleanType CompositeImage(Image *image, % const Image *source_image,const CompositeOperator compose, % const MagickBooleanType clip_to_self,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the canvas image, modified by he composition % % o source_image: the source image. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o clip_to_self: set to MagickTrue to limit composition to area composed. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o exception: return any errors or warnings in this structure. % */ /* Composition based on the SVG specification: A Composition is defined by... Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc) Y = 1 for source preserved Z = 1 for canvas preserved Conversion to transparency (then optimized) Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) Where... Sca = Sc*Sa normalized Source color divided by Source alpha Dca = Dc*Da normalized Dest color divided by Dest alpha Dc' = Dca'/Da' the desired color value for this channel. Da' in in the follow formula as 'gamma' The resulting alpla value. Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in the following optimizations... gamma = Sa+Da-Sa*Da; gamma = 1 - QuantiumScale*alpha * QuantiumScale*beta; opacity = QuantiumScale*alpha*beta; // over blend, optimized 1-Gamma The above SVG definitions also definate that Mathematical Composition methods should use a 'Over' blending mode for Alpha Channel. It however was not applied for composition modes of 'Plus', 'Minus', the modulus versions of 'Add' and 'Subtract'. Mathematical operator changes to be applied from IM v6.7... 1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed 'ModulusAdd' and 'ModulusSubtract' for clarity. 2) All mathematical compositions work as per the SVG specification with regard to blending. This now includes 'ModulusAdd' and 'ModulusSubtract'. 3) When the special channel flag 'sync' (syncronize channel updates) is turned off (enabled by default) then mathematical compositions are only performed on the channels specified, and are applied independantally of each other. In other words the mathematics is performed as 'pure' mathematical operations, rather than as image operations. */ static void HCLComposite(const MagickRealType hue,const MagickRealType chroma, const MagickRealType luma,MagickRealType *red,MagickRealType *green, MagickRealType *blue) { MagickRealType b, c, g, h, m, r, x; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); *red=QuantumRange*(r+m); *green=QuantumRange*(g+m); *blue=QuantumRange*(b+m); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma, MagickRealType *luma) { MagickRealType b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (MagickRealType *) NULL); assert(chroma != (MagickRealType *) NULL); assert(luma != (MagickRealType *) NULL); r=red; g=green; b=blue; max=MagickMax(r,MagickMax(g,b)); c=max-(MagickRealType) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == max) h=fmod((g-b)/c+6.0,6.0); else if (green == max) h=((b-r)/c)+2.0; else if (blue == max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static MagickBooleanType CompositeOverImage(Image *image, const Image *source_image,const MagickBooleanType clip_to_self, const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *image_view, *source_view; const char *value; MagickBooleanType clamp, status; MagickOffsetType progress; ssize_t y; /* Composite image. */ status=MagickTrue; progress=0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; size_t channels; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } 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++) { MagickRealType Da, Dc, Dca, gamma, Sa, Sc, Sca; register ssize_t i; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset, source,exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; q[i]=source[channel]; } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ if (GetPixelReadMask(source_image,p) == 0) { p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; q+=GetPixelChannels(image); continue; } Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); 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); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=GetPixelChannel(source_image,channel,p); continue; } if (channel == AlphaPixelChannel) { /* Set alpha channel. */ q[i]=clamp != MagickFalse ? ClampPixel(QuantumRange*(Sa+Da-Sa*Da)) : ClampToQuantum(QuantumRange*(Sa+Da-Sa*Da)); continue; } /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; q[i]=clamp != MagickFalse ? ClampPixel(gamma*QuantumRange*(Sca+Dca*(1.0-Sa))) : ClampToQuantum(gamma*QuantumRange*(Sca+Dca*(1.0-Sa))); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } MagickExport MagickBooleanType CompositeImage(Image *image, const Image *composite,const CompositeOperator compose, const MagickBooleanType clip_to_self,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *source_view, *image_view; const char *value; GeometryInfo geometry_info; Image *canvas_image, *source_image; MagickBooleanType clamp, status; MagickOffsetType progress; MagickRealType amount, canvas_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite!= (Image *) NULL); assert(composite->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); source_image=CloneImage(composite,0,0,MagickTrue,exception); if (source_image == (const Image *) NULL) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); (void) SetImageColorspace(source_image,image->colorspace,exception); if ((image->alpha_trait != UndefinedPixelTrait) && (source_image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(source_image,SetAlphaChannel,exception); if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp)) { status=CompositeOverImage(image,source_image,clip_to_self,x_offset, y_offset,exception); source_image=DestroyImage(source_image); return(status); } amount=0.5; canvas_image=(Image *) NULL; canvas_dissolve=1.0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); SetGeometryInfo(&geometry_info); percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(source_image,p) == 0) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(source_image); i++) { PixelChannel channel=GetPixelChannelChannel(source_image,i); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag, (MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case IntensityCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { if (GetPixelReadMask(source_image,p) == 0) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } SetPixelAlpha(image,clamp != MagickFalse ? ClampPixel(GetPixelIntensity(source_image,p)) : ClampToQuantum(GetPixelIntensity(source_image,p)),q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag, (MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case CopyAlphaCompositeOp: case ChangeMaskCompositeOp: { /* Modify canvas outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); break; } case BlurCompositeOp: { CacheView *canvas_view; MagickRealType angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling. Blur Image dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ canvas_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (const char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidSetting","'%s' '%s'","compose:args",value); source_image=DestroyImage(source_image); canvas_image=DestroyImage(canvas_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=height=geometry_info.rho*2.0; if ((flags & HeightValue) != 0 ) height=geometry_info.sigma*2.0; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; /* rotate vectors if a rotation angle is given */ if ((flags & XValue) != 0 ) { MagickRealType angle; angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } /* Otherwise lets set a angle range and calculate in the loop */ angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, then restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* do the variable blurring of each pixel in image */ GetPixelInfo(image,&pixel); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } if (fabs((double) angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(source_image,p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } #if 0 if ( x == 10 && y == 60 ) { (void) fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",blur.x1, blur.x2,blur.y1, blur.y2); (void) fprintf(stderr, "scaled by=%lf,%lf\n",QuantumScale* GetPixelRed(p),QuantumScale*GetPixelGreen(p)); #endif ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(source_image,p), blur.y1*QuantumScale*GetPixelGreen(source_image,p), blur.x2*QuantumScale*GetPixelRed(source_image,p), blur.y2*QuantumScale*GetPixelGreen(source_image,p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel,exception); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); source_view=DestroyCacheView(source_view); canvas_view=DestroyCacheView(canvas_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *canvas_view; MagickRealType horizontal_scale, vertical_scale; PixelInfo pixel; PointInfo center, offset; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ canvas_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue | HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0; vertical_scale=(MagickRealType) (source_image->rows-1)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1)/2.0; vertical_scale=(MagickRealType) (image->rows-1)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(source_image->columns-1)/200.0; vertical_scale*=(source_image->rows-1)/200.0; } else { horizontal_scale*=(image->columns-1)/200.0; vertical_scale*=(image->rows-1)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) != 0) center.x=(MagickRealType) ((image->columns-1)/2.0); else center.x=(MagickRealType) (x_offset+(source_image->columns-1)/ 2.0); else if ((flags & AspectValue) != 0) center.x=geometry_info.xi; else center.x=(MagickRealType) (x_offset+geometry_info.xi); if ((flags & YValue) == 0) if ((flags & AspectValue) != 0) center.y=(MagickRealType) ((image->rows-1)/2.0); else center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0); else if ((flags & AspectValue) != 0) center.y=geometry_info.psi; else center.y=(MagickRealType) (y_offset+geometry_info.psi); } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } /* Displace the offset. */ offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0); offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0); (void) InterpolatePixelInfo(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)* (QuantumScale*GetPixelAlpha(source_image,p)); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } canvas_view=DestroyCacheView(canvas_view); source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { canvas_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; if ((canvas_dissolve-MagickEpsilon) < 0.0) canvas_dissolve=0.0; } break; } case BlendCompositeOp: { value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; } break; } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) (void) ParseGeometry(value,&geometry_info); break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; MagickRealType blue, chroma, green, hue, luma, red; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } hue=0.0; chroma=0.0; luma=0.0; GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, Sa, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; switch (compose) { case AlphaCompositeOp: case ChangeMaskCompositeOp: case CopyAlphaCompositeOp: case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case OutCompositeOp: case SrcInCompositeOp: case SrcOutCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; break; } case ClearCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=0.0; break; } case BlendCompositeOp: case DissolveCompositeOp: { if (channel == AlphaPixelChannel) pixel=canvas_dissolve*GetPixelAlpha(source_image,source); else pixel=(MagickRealType) source[channel]; break; } default: { pixel=(MagickRealType) source[channel]; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); switch (compose) { case BumpmapCompositeOp: { alpha=GetPixelIntensity(source_image,p)*Sa; break; } case ColorBurnCompositeOp: case ColorDodgeCompositeOp: case DarkenCompositeOp: case DifferenceCompositeOp: case DivideDstCompositeOp: case DivideSrcCompositeOp: case ExclusionCompositeOp: case HardLightCompositeOp: case HardMixCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case LightenCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case ModulusAddCompositeOp: case ModulusSubtractCompositeOp: case MultiplyCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ScreenCompositeOp: case SoftLightCompositeOp: case VividLightCompositeOp: { alpha=RoundToUnity(Sa+Da-Sa*Da); break; } case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case SrcInCompositeOp: { alpha=Sa*Da; break; } case DissolveCompositeOp: { alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+ canvas_dissolve*Da; break; } case DstOverCompositeOp: case OverCompositeOp: case SrcOverCompositeOp: { alpha=Sa+Da-Sa*Da; break; } case DstOutCompositeOp: { alpha=Da*(1.0-Sa); break; } case OutCompositeOp: case SrcOutCompositeOp: { alpha=Sa*(1.0-Da); break; } case BlendCompositeOp: case PlusCompositeOp: { alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da); break; } case XorCompositeOp: { alpha=Sa+Da-2.0*Sa*Da; break; } default: { alpha=1.0; break; } } if (GetPixelReadMask(image,q) == 0) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: case SaturateCompositeOp: { GetPixelInfoPixel(source_image,p,&source_pixel); GetPixelInfoPixel(image,q,&canvas_pixel); break; } default: break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel, sans; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((source_traits == UndefinedPixelTrait) && (((compose != CopyAlphaCompositeOp) && (compose != ChangeMaskCompositeOp)) || (channel != AlphaPixelChannel))) continue; /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=Sc; continue; } if (channel == AlphaPixelChannel) { /* Set alpha channel. */ switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case CopyBlackCompositeOp: case CopyBlueCompositeOp: case CopyCyanCompositeOp: case CopyGreenCompositeOp: case CopyMagentaCompositeOp: case CopyRedCompositeOp: case CopyYellowCompositeOp: case SrcAtopCompositeOp: case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Da; break; } case ChangeMaskCompositeOp: { MagickBooleanType equivalent; if (Da < 0.5) { pixel=(MagickRealType) TransparentAlpha; break; } equivalent=IsFuzzyEquivalencePixel(source_image,p,image,q); if (equivalent != MagickFalse) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) OpaqueAlpha; break; } case ClearCompositeOp: { pixel=(MagickRealType) TransparentAlpha; break; } case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Da; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Sa; break; } if (Sa < Da) { pixel=QuantumRange*Da; break; } pixel=QuantumRange*Sa; break; } case CopyAlphaCompositeOp: { if ((source_traits & BlendPixelTrait) == 0) pixel=GetPixelIntensity(source_image,p); else pixel=QuantumRange*Sa; break; } case CopyCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: case DstAtopCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sa; break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case LightenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case ModulateCompositeOp: { pixel=QuantumRange*Da; break; } default: { pixel=QuantumRange*alpha; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; switch (compose) { case DarkenCompositeOp: case LightenCompositeOp: case ModulusSubtractCompositeOp: { gamma=PerceptibleReciprocal(1.0-alpha); break; } default: { gamma=PerceptibleReciprocal(alpha); break; } } pixel=Dc; switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case SrcAtopCompositeOp: { pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa)); break; } case BlendCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc); break; } case BlurCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } case DisplaceCompositeOp: case DistortCompositeOp: { pixel=Sc; break; } case BumpmapCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc; break; } case ChangeMaskCompositeOp: { pixel=Dc; break; } case ClearCompositeOp: { pixel=0.0; break; } case ColorBurnCompositeOp: { if ((Sca == 0.0) && (Dca == Da)) { pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa)); break; } if (Sca == 0.0) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-Dca/Da)*Sa/ Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorDodgeCompositeOp: { if ((Sca*Da+Dca*Sa) >= Sa*Da) pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); else pixel=QuantumRange*gamma*(Dca*Sa*Sa/(Sa-Sca)+Sca*(1.0-Da)+Dca* (1.0-Sa)); break; } case ColorizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &sans,&sans,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case CopyAlphaCompositeOp: { pixel=Dc; break; } case CopyBlackCompositeOp: { if (channel == BlackPixelChannel) pixel=(MagickRealType) (QuantumRange- GetPixelBlack(source_image,p)); break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { if (channel == BluePixelChannel) pixel=(MagickRealType) GetPixelBlue(source_image,p); break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { if (channel == GreenPixelChannel) pixel=(MagickRealType) GetPixelGreen(source_image,p); break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case DarkenCompositeOp: { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ if ((Sca*Da) < (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case DifferenceCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa)); break; } case DissolveCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa* canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc); break; } case DivideDstCompositeOp: { if ((fabs((double) Sca) < MagickEpsilon) && (fabs((double) Dca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (fabs((double) Dca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case DivideSrcCompositeOp: { if ((fabs((double) Dca) < MagickEpsilon) && (fabs((double) Sca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } if (fabs((double) Sca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa/Sca+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } case DstAtopCompositeOp: { pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da)); break; } case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Dca; break; } case DstInCompositeOp: { pixel=QuantumRange*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*(Dca*(1.0-Sa)); break; } case DstOverCompositeOp: { pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da)); break; } case ExclusionCompositeOp: { pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0- Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardMixCompositeOp: { pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange); break; } case HueCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&sans,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case InCompositeOp: case SrcInCompositeOp: { pixel=QuantumRange*(Sca*Da); break; } case LinearBurnCompositeOp: { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da); break; } case LinearDodgeCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc); break; } case LinearLightCompositeOp: { /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca); break; } case LightenCompositeOp: { if ((Sca*Da) > (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case LightenIntensityCompositeOp: { /* Lighten is equivalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case LuminizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&sans,&luma); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case MathematicsCompositeOp: { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+ geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+ geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case MinusDstCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa); break; } case MinusSrcCompositeOp: { /* Minus source from canvas. f(Sc,Dc) = Sc - Dc */ pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da); break; } case ModulateCompositeOp: { ssize_t offset; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint); if (offset == 0) { pixel=Dc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ModulusAddCompositeOp: { pixel=Sc+Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case ModulusSubtractCompositeOp: { pixel=Sc-Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case MultiplyCompositeOp: { pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case OutCompositeOp: case SrcOutCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)); break; } case OverCompositeOp: case SrcOverCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); break; } case OverlayCompositeOp: { if ((2.0*Dca) < Da) { pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0- Da)); break; } pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+ Sca*(1.0-Da)); break; } case PegtopLightCompositeOp: { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs((double) Da) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sca); break; } pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0- Da)+Dca*(1.0-Sa)); break; } case PinLightCompositeOp: { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if ((Dca*Sa) < (Da*(2.0*Sca-Sa))) { pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); break; } if ((Dca*Sa) > (2.0*Sca*Da)) { pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca); break; } case PlusCompositeOp: { pixel=QuantumRange*(Sca+Dca); break; } case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ScreenCompositeOp: { /* Screen: a negated multiply: f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca); break; } case SoftLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-(Dca/Da)))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*(Dca/Da)* (4.0*(Dca/Da)+1.0)*((Dca/Da)-1.0)+7.0*(Dca/Da))+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow((Dca/Da),0.5)- (Dca/Da))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ThresholdCompositeOp: { MagickRealType delta; delta=Sc-Dc; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) { pixel=gamma*Dc; break; } pixel=gamma*(Dc+delta*amount); break; } case VividLightCompositeOp: { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs((double) Sa) < MagickEpsilon) || (fabs((double) (Sca-Sa)) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if ((2.0*Sca) <= Sa) { pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)/(2.0*Sca))+Sca* (1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa/(2.0*(Sa-Sca))+Sca*(1.0-Da)+Dca* (1.0-Sa)); break; } case XorCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } default: { pixel=Sc; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); if (canvas_image != (Image * ) NULL) canvas_image=DestroyImage(canvas_image); else source_image=DestroyImage(source_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o texture_image: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture, ExceptionInfo *exception) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace,exception); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod, exception); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->alpha_trait != UndefinedPixelTrait) || (texture_image->alpha_trait != UndefinedPixelTrait))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,texture_image,image->compose, MagickTrue,x+texture_image->tile_offset.x,y+ texture_image->tile_offset.y,exception); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(texture_image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const Quantum *p, *pixels; register ssize_t x; register Quantum *q; size_t width; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x, (y+texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { register ssize_t j; p=pixels; width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; for (j=0; j < (ssize_t) width; j++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++) { PixelChannel channel=GetPixelChannelChannel(texture_image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait texture_traits=GetPixelChannelTraits(texture_image, channel); if ((traits == UndefinedPixelTrait) || (texture_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); } } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
StmtOpenMP.h
//===- StmtOpenMP.h - Classes for OpenMP directives ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file defines OpenMP AST classes for executable directives and /// clauses. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMTOPENMP_H #define LLVM_CLANG_AST_STMTOPENMP_H #include "clang/AST/Expr.h" #include "clang/AST/OpenMPClause.h" #include "clang/AST/Stmt.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" namespace clang { //===----------------------------------------------------------------------===// // AST classes for directives. //===----------------------------------------------------------------------===// /// This is a basic class for representing single OpenMP executable /// directive. /// class OMPExecutableDirective : public Stmt { friend class ASTStmtReader; /// Kind of the directive. OpenMPDirectiveKind Kind; /// Starting location of the directive (directive keyword). SourceLocation StartLoc; /// Ending location of the directive. SourceLocation EndLoc; /// Numbers of clauses. const unsigned NumClauses; /// Number of child expressions/stmts. const unsigned NumChildren; /// Offset from this to the start of clauses. /// There are NumClauses pointers to clauses, they are followed by /// NumChildren pointers to child stmts/exprs (if the directive type /// requires an associated stmt, then it has to be the first of them). const unsigned ClausesOffset; /// Get the clauses storage. MutableArrayRef<OMPClause *> getClauses() { OMPClause **ClauseStorage = reinterpret_cast<OMPClause **>( reinterpret_cast<char *>(this) + ClausesOffset); return MutableArrayRef<OMPClause *>(ClauseStorage, NumClauses); } protected: /// Build instance of directive of class \a K. /// /// \param SC Statement class. /// \param K Kind of OpenMP directive. /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending location of the directive. /// template <typename T> OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K, SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses, unsigned NumChildren) : Stmt(SC), Kind(K), StartLoc(std::move(StartLoc)), EndLoc(std::move(EndLoc)), NumClauses(NumClauses), NumChildren(NumChildren), ClausesOffset(llvm::alignTo(sizeof(T), alignof(OMPClause *))) {} /// Sets the list of variables for this clause. /// /// \param Clauses The list of clauses for the directive. /// void setClauses(ArrayRef<OMPClause *> Clauses); /// Set the associated statement for the directive. /// /// /param S Associated statement. /// void setAssociatedStmt(Stmt *S) { assert(hasAssociatedStmt() && "no associated statement."); *child_begin() = S; } public: /// Iterates over a filtered subrange of clauses applied to a /// directive. /// /// This iterator visits only clauses of type SpecificClause. template <typename SpecificClause> class specific_clause_iterator : public llvm::iterator_adaptor_base< specific_clause_iterator<SpecificClause>, ArrayRef<OMPClause *>::const_iterator, std::forward_iterator_tag, const SpecificClause *, ptrdiff_t, const SpecificClause *, const SpecificClause *> { ArrayRef<OMPClause *>::const_iterator End; void SkipToNextClause() { while (this->I != End && !isa<SpecificClause>(*this->I)) ++this->I; } public: explicit specific_clause_iterator(ArrayRef<OMPClause *> Clauses) : specific_clause_iterator::iterator_adaptor_base(Clauses.begin()), End(Clauses.end()) { SkipToNextClause(); } const SpecificClause *operator*() const { return cast<SpecificClause>(*this->I); } const SpecificClause *operator->() const { return **this; } specific_clause_iterator &operator++() { ++this->I; SkipToNextClause(); return *this; } }; template <typename SpecificClause> static llvm::iterator_range<specific_clause_iterator<SpecificClause>> getClausesOfKind(ArrayRef<OMPClause *> Clauses) { return {specific_clause_iterator<SpecificClause>(Clauses), specific_clause_iterator<SpecificClause>( llvm::makeArrayRef(Clauses.end(), 0))}; } template <typename SpecificClause> llvm::iterator_range<specific_clause_iterator<SpecificClause>> getClausesOfKind() const { return getClausesOfKind<SpecificClause>(clauses()); } /// Gets a single clause of the specified kind associated with the /// current directive iff there is only one clause of this kind (and assertion /// is fired if there is more than one clause is associated with the /// directive). Returns nullptr if no clause of this kind is associated with /// the directive. template <typename SpecificClause> const SpecificClause *getSingleClause() const { auto Clauses = getClausesOfKind<SpecificClause>(); if (Clauses.begin() != Clauses.end()) { assert(std::next(Clauses.begin()) == Clauses.end() && "There are at least 2 clauses of the specified kind"); return *Clauses.begin(); } return nullptr; } /// Returns true if the current directive has one or more clauses of a /// specific kind. template <typename SpecificClause> bool hasClausesOfKind() const { auto Clauses = getClausesOfKind<SpecificClause>(); return Clauses.begin() != Clauses.end(); } /// Returns starting location of directive kind. SourceLocation getLocStart() const { return StartLoc; } /// Returns ending location of directive. SourceLocation getLocEnd() const { return EndLoc; } /// Set starting location of directive kind. /// /// \param Loc New starting location of directive. /// void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// Set ending location of directive. /// /// \param Loc New ending location of directive. /// void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// Get number of clauses. unsigned getNumClauses() const { return NumClauses; } /// Returns specified clause. /// /// \param i Number of clause. /// OMPClause *getClause(unsigned i) const { return clauses()[i]; } /// Returns true if directive has associated statement. bool hasAssociatedStmt() const { return NumChildren > 0; } /// Returns statement associated with the directive. const Stmt *getAssociatedStmt() const { assert(hasAssociatedStmt() && "no associated statement."); return *child_begin(); } Stmt *getAssociatedStmt() { assert(hasAssociatedStmt() && "no associated statement."); return *child_begin(); } /// Returns the captured statement associated with the /// component region within the (combined) directive. // // \param RegionKind Component region kind. const CapturedStmt *getCapturedStmt(OpenMPDirectiveKind RegionKind) const { SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind()); assert(std::any_of( CaptureRegions.begin(), CaptureRegions.end(), [=](const OpenMPDirectiveKind K) { return K == RegionKind; }) && "RegionKind not found in OpenMP CaptureRegions."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (auto ThisCaptureRegion : CaptureRegions) { if (ThisCaptureRegion == RegionKind) return CS; CS = cast<CapturedStmt>(CS->getCapturedStmt()); } llvm_unreachable("Incorrect RegionKind specified for directive."); } /// Get innermost captured statement for the construct. CapturedStmt *getInnermostCapturedStmt() { assert(hasAssociatedStmt() && getAssociatedStmt() && "Must have associated statement."); SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind()); assert(!CaptureRegions.empty() && "At least one captured statement must be provided."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (unsigned Level = CaptureRegions.size(); Level > 1; --Level) CS = cast<CapturedStmt>(CS->getCapturedStmt()); return CS; } const CapturedStmt *getInnermostCapturedStmt() const { return const_cast<OMPExecutableDirective *>(this) ->getInnermostCapturedStmt(); } OpenMPDirectiveKind getDirectiveKind() const { return Kind; } static bool classof(const Stmt *S) { return S->getStmtClass() >= firstOMPExecutableDirectiveConstant && S->getStmtClass() <= lastOMPExecutableDirectiveConstant; } child_range children() { if (!hasAssociatedStmt()) return child_range(child_iterator(), child_iterator()); Stmt **ChildStorage = reinterpret_cast<Stmt **>(getClauses().end()); return child_range(ChildStorage, ChildStorage + NumChildren); } ArrayRef<OMPClause *> clauses() { return getClauses(); } ArrayRef<OMPClause *> clauses() const { return const_cast<OMPExecutableDirective *>(this)->getClauses(); } }; /// This represents '#pragma omp parallel' directive. /// /// \code /// #pragma omp parallel private(a,b) reduction(+: c,d) /// \endcode /// In this example directive '#pragma omp parallel' has clauses 'private' /// with the variables 'a' and 'b' and 'reduction' with operator '+' and /// variables 'c' and 'd'. /// class OMPParallelDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending Location of the directive. /// OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPParallelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement associated with the directive. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPParallelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPParallelDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelDirectiveClass; } }; /// This is a common base class for loop directives ('omp simd', 'omp /// for', 'omp for simd' etc.). It is responsible for the loop code generation. /// class OMPLoopDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Number of collapsed loops as specified by 'collapse' clause. unsigned CollapsedNum; /// Offsets to the stored exprs. /// This enumeration contains offsets to all the pointers to children /// expressions stored in OMPLoopDirective. /// The first 9 children are necessary for all the loop directives, /// the next 8 are specific to the worksharing ones, and the next 11 are /// used for combined constructs containing two pragmas associated to loops. /// After the fixed children, three arrays of length CollapsedNum are /// allocated: loop counters, their updates and final values. /// PrevLowerBound and PrevUpperBound are used to communicate blocking /// information in composite constructs which require loop blocking /// DistInc is used to generate the increment expression for the distribute /// loop when combined with a further nested loop /// PrevEnsureUpperBound is used as the EnsureUpperBound expression for the /// for loop when combined with a previous distribute loop in the same pragma /// (e.g. 'distribute parallel for') /// enum { AssociatedStmtOffset = 0, IterationVariableOffset = 1, LastIterationOffset = 2, CalcLastIterationOffset = 3, PreConditionOffset = 4, CondOffset = 5, InitOffset = 6, IncOffset = 7, PreInitsOffset = 8, // The '...End' enumerators do not correspond to child expressions - they // specify the offset to the end (and start of the following counters/ // updates/finals arrays). DefaultEnd = 9, // The following 8 exprs are used by worksharing and distribute loops only. IsLastIterVariableOffset = 9, LowerBoundVariableOffset = 10, UpperBoundVariableOffset = 11, StrideVariableOffset = 12, EnsureUpperBoundOffset = 13, NextLowerBoundOffset = 14, NextUpperBoundOffset = 15, NumIterationsOffset = 16, // Offset to the end for worksharing loop directives. WorksharingEnd = 17, PrevLowerBoundVariableOffset = 17, PrevUpperBoundVariableOffset = 18, DistIncOffset = 19, PrevEnsureUpperBoundOffset = 20, CombinedLowerBoundVariableOffset = 21, CombinedUpperBoundVariableOffset = 22, CombinedEnsureUpperBoundOffset = 23, CombinedInitOffset = 24, CombinedConditionOffset = 25, CombinedNextLowerBoundOffset = 26, CombinedNextUpperBoundOffset = 27, // Offset to the end (and start of the following counters/updates/finals // arrays) for combined distribute loop directives. CombinedDistributeEnd = 28, }; /// Get the counters storage. MutableArrayRef<Expr *> getCounters() { Expr **Storage = reinterpret_cast<Expr **>( &(*(std::next(child_begin(), getArraysOffset(getDirectiveKind()))))); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the private counters storage. MutableArrayRef<Expr *> getPrivateCounters() { Expr **Storage = reinterpret_cast<Expr **>(&*std::next( child_begin(), getArraysOffset(getDirectiveKind()) + CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the updates storage. MutableArrayRef<Expr *> getInits() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the updates storage. MutableArrayRef<Expr *> getUpdates() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 3 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the final counter updates storage. MutableArrayRef<Expr *> getFinals() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 4 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } protected: /// Build instance of loop directive of class \a Kind. /// /// \param SC Statement class. /// \param Kind Kind of OpenMP directive. /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed loops from 'collapse' clause. /// \param NumClauses Number of clauses. /// \param NumSpecialChildren Number of additional directive-specific stmts. /// template <typename T> OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses, unsigned NumSpecialChildren = 0) : OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses, numLoopChildren(CollapsedNum, Kind) + NumSpecialChildren), CollapsedNum(CollapsedNum) {} /// Offset to the start of children expression arrays. static unsigned getArraysOffset(OpenMPDirectiveKind Kind) { if (isOpenMPLoopBoundSharingDirective(Kind)) return CombinedDistributeEnd; if (isOpenMPWorksharingDirective(Kind) || isOpenMPTaskLoopDirective(Kind) || isOpenMPDistributeDirective(Kind)) return WorksharingEnd; return DefaultEnd; } /// Children number. static unsigned numLoopChildren(unsigned CollapsedNum, OpenMPDirectiveKind Kind) { return getArraysOffset(Kind) + 5 * CollapsedNum; // Counters, // PrivateCounters, Inits, // Updates and Finals } void setIterationVariable(Expr *IV) { *std::next(child_begin(), IterationVariableOffset) = IV; } void setLastIteration(Expr *LI) { *std::next(child_begin(), LastIterationOffset) = LI; } void setCalcLastIteration(Expr *CLI) { *std::next(child_begin(), CalcLastIterationOffset) = CLI; } void setPreCond(Expr *PC) { *std::next(child_begin(), PreConditionOffset) = PC; } void setCond(Expr *Cond) { *std::next(child_begin(), CondOffset) = Cond; } void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; } void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; } void setPreInits(Stmt *PreInits) { *std::next(child_begin(), PreInitsOffset) = PreInits; } void setIsLastIterVariable(Expr *IL) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), IsLastIterVariableOffset) = IL; } void setLowerBoundVariable(Expr *LB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), LowerBoundVariableOffset) = LB; } void setUpperBoundVariable(Expr *UB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), UpperBoundVariableOffset) = UB; } void setStrideVariable(Expr *ST) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), StrideVariableOffset) = ST; } void setEnsureUpperBound(Expr *EUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), EnsureUpperBoundOffset) = EUB; } void setNextLowerBound(Expr *NLB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NextLowerBoundOffset) = NLB; } void setNextUpperBound(Expr *NUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NextUpperBoundOffset) = NUB; } void setNumIterations(Expr *NI) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NumIterationsOffset) = NI; } void setPrevLowerBoundVariable(Expr *PrevLB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), PrevLowerBoundVariableOffset) = PrevLB; } void setPrevUpperBoundVariable(Expr *PrevUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), PrevUpperBoundVariableOffset) = PrevUB; } void setDistInc(Expr *DistInc) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), DistIncOffset) = DistInc; } void setPrevEnsureUpperBound(Expr *PrevEUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), PrevEnsureUpperBoundOffset) = PrevEUB; } void setCombinedLowerBoundVariable(Expr *CombLB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedLowerBoundVariableOffset) = CombLB; } void setCombinedUpperBoundVariable(Expr *CombUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedUpperBoundVariableOffset) = CombUB; } void setCombinedEnsureUpperBound(Expr *CombEUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedEnsureUpperBoundOffset) = CombEUB; } void setCombinedInit(Expr *CombInit) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedInitOffset) = CombInit; } void setCombinedCond(Expr *CombCond) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedConditionOffset) = CombCond; } void setCombinedNextLowerBound(Expr *CombNLB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedNextLowerBoundOffset) = CombNLB; } void setCombinedNextUpperBound(Expr *CombNUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedNextUpperBoundOffset) = CombNUB; } void setCounters(ArrayRef<Expr *> A); void setPrivateCounters(ArrayRef<Expr *> A); void setInits(ArrayRef<Expr *> A); void setUpdates(ArrayRef<Expr *> A); void setFinals(ArrayRef<Expr *> A); public: /// The expressions built to support OpenMP loops in combined/composite /// pragmas (e.g. pragma omp distribute parallel for) struct DistCombinedHelperExprs { /// DistributeLowerBound - used when composing 'omp distribute' with /// 'omp for' in a same construct. Expr *LB; /// DistributeUpperBound - used when composing 'omp distribute' with /// 'omp for' in a same construct. Expr *UB; /// DistributeEnsureUpperBound - used when composing 'omp distribute' /// with 'omp for' in a same construct, EUB depends on DistUB Expr *EUB; /// Distribute loop iteration variable init used when composing 'omp /// distribute' /// with 'omp for' in a same construct Expr *Init; /// Distribute Loop condition used when composing 'omp distribute' /// with 'omp for' in a same construct Expr *Cond; /// Update of LowerBound for statically scheduled omp loops for /// outer loop in combined constructs (e.g. 'distribute parallel for') Expr *NLB; /// Update of UpperBound for statically scheduled omp loops for /// outer loop in combined constructs (e.g. 'distribute parallel for') Expr *NUB; }; /// The expressions built for the OpenMP loop CodeGen for the /// whole collapsed loop nest. struct HelperExprs { /// Loop iteration variable. Expr *IterationVarRef; /// Loop last iteration number. Expr *LastIteration; /// Loop number of iterations. Expr *NumIterations; /// Calculation of last iteration. Expr *CalcLastIteration; /// Loop pre-condition. Expr *PreCond; /// Loop condition. Expr *Cond; /// Loop iteration variable init. Expr *Init; /// Loop increment. Expr *Inc; /// IsLastIteration - local flag variable passed to runtime. Expr *IL; /// LowerBound - local variable passed to runtime. Expr *LB; /// UpperBound - local variable passed to runtime. Expr *UB; /// Stride - local variable passed to runtime. Expr *ST; /// EnsureUpperBound -- expression UB = min(UB, NumIterations). Expr *EUB; /// Update of LowerBound for statically scheduled 'omp for' loops. Expr *NLB; /// Update of UpperBound for statically scheduled 'omp for' loops. Expr *NUB; /// PreviousLowerBound - local variable passed to runtime in the /// enclosing schedule or null if that does not apply. Expr *PrevLB; /// PreviousUpperBound - local variable passed to runtime in the /// enclosing schedule or null if that does not apply. Expr *PrevUB; /// DistInc - increment expression for distribute loop when found /// combined with a further loop level (e.g. in 'distribute parallel for') /// expression IV = IV + ST Expr *DistInc; /// PrevEUB - expression similar to EUB but to be used when loop /// scheduling uses PrevLB and PrevUB (e.g. in 'distribute parallel for' /// when ensuring that the UB is either the calculated UB by the runtime or /// the end of the assigned distribute chunk) /// expression UB = min (UB, PrevUB) Expr *PrevEUB; /// Counters Loop counters. SmallVector<Expr *, 4> Counters; /// PrivateCounters Loop counters. SmallVector<Expr *, 4> PrivateCounters; /// Expressions for loop counters inits for CodeGen. SmallVector<Expr *, 4> Inits; /// Expressions for loop counters update for CodeGen. SmallVector<Expr *, 4> Updates; /// Final loop counter values for GodeGen. SmallVector<Expr *, 4> Finals; /// Init statement for all captured expressions. Stmt *PreInits; /// Expressions used when combining OpenMP loop pragmas DistCombinedHelperExprs DistCombinedFields; /// Check if all the expressions are built (does not check the /// worksharing ones). bool builtAll() { return IterationVarRef != nullptr && LastIteration != nullptr && NumIterations != nullptr && PreCond != nullptr && Cond != nullptr && Init != nullptr && Inc != nullptr; } /// Initialize all the fields to null. /// \param Size Number of elements in the counters/finals/updates arrays. void clear(unsigned Size) { IterationVarRef = nullptr; LastIteration = nullptr; CalcLastIteration = nullptr; PreCond = nullptr; Cond = nullptr; Init = nullptr; Inc = nullptr; IL = nullptr; LB = nullptr; UB = nullptr; ST = nullptr; EUB = nullptr; NLB = nullptr; NUB = nullptr; NumIterations = nullptr; PrevLB = nullptr; PrevUB = nullptr; DistInc = nullptr; PrevEUB = nullptr; Counters.resize(Size); PrivateCounters.resize(Size); Inits.resize(Size); Updates.resize(Size); Finals.resize(Size); for (unsigned i = 0; i < Size; ++i) { Counters[i] = nullptr; PrivateCounters[i] = nullptr; Inits[i] = nullptr; Updates[i] = nullptr; Finals[i] = nullptr; } PreInits = nullptr; DistCombinedFields.LB = nullptr; DistCombinedFields.UB = nullptr; DistCombinedFields.EUB = nullptr; DistCombinedFields.Init = nullptr; DistCombinedFields.Cond = nullptr; DistCombinedFields.NLB = nullptr; DistCombinedFields.NUB = nullptr; } }; /// Get number of collapsed loops. unsigned getCollapsedNumber() const { return CollapsedNum; } Expr *getIterationVariable() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), IterationVariableOffset))); } Expr *getLastIteration() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), LastIterationOffset))); } Expr *getCalcLastIteration() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CalcLastIterationOffset))); } Expr *getPreCond() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PreConditionOffset))); } Expr *getCond() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset))); } Expr *getInit() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset))); } Expr *getInc() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset))); } const Stmt *getPreInits() const { return *std::next(child_begin(), PreInitsOffset); } Stmt *getPreInits() { return *std::next(child_begin(), PreInitsOffset); } Expr *getIsLastIterVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), IsLastIterVariableOffset))); } Expr *getLowerBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), LowerBoundVariableOffset))); } Expr *getUpperBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), UpperBoundVariableOffset))); } Expr *getStrideVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), StrideVariableOffset))); } Expr *getEnsureUpperBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), EnsureUpperBoundOffset))); } Expr *getNextLowerBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NextLowerBoundOffset))); } Expr *getNextUpperBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NextUpperBoundOffset))); } Expr *getNumIterations() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NumIterationsOffset))); } Expr *getPrevLowerBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevLowerBoundVariableOffset))); } Expr *getPrevUpperBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevUpperBoundVariableOffset))); } Expr *getDistInc() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), DistIncOffset))); } Expr *getPrevEnsureUpperBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevEnsureUpperBoundOffset))); } Expr *getCombinedLowerBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedLowerBoundVariableOffset))); } Expr *getCombinedUpperBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedUpperBoundVariableOffset))); } Expr *getCombinedEnsureUpperBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedEnsureUpperBoundOffset))); } Expr *getCombinedInit() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedInitOffset))); } Expr *getCombinedCond() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedConditionOffset))); } Expr *getCombinedNextLowerBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedNextLowerBoundOffset))); } Expr *getCombinedNextUpperBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedNextUpperBoundOffset))); } const Stmt *getBody() const { // This relies on the loop form is already checked by Sema. const Stmt *Body = getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); Body = cast<ForStmt>(Body)->getBody(); for (unsigned Cnt = 1; Cnt < CollapsedNum; ++Cnt) { Body = Body->IgnoreContainers(); Body = cast<ForStmt>(Body)->getBody(); } return Body; } ArrayRef<Expr *> counters() { return getCounters(); } ArrayRef<Expr *> counters() const { return const_cast<OMPLoopDirective *>(this)->getCounters(); } ArrayRef<Expr *> private_counters() { return getPrivateCounters(); } ArrayRef<Expr *> private_counters() const { return const_cast<OMPLoopDirective *>(this)->getPrivateCounters(); } ArrayRef<Expr *> inits() { return getInits(); } ArrayRef<Expr *> inits() const { return const_cast<OMPLoopDirective *>(this)->getInits(); } ArrayRef<Expr *> updates() { return getUpdates(); } ArrayRef<Expr *> updates() const { return const_cast<OMPLoopDirective *>(this)->getUpdates(); } ArrayRef<Expr *> finals() { return getFinals(); } ArrayRef<Expr *> finals() const { return const_cast<OMPLoopDirective *>(this)->getFinals(); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSimdDirectiveClass || T->getStmtClass() == OMPForDirectiveClass || T->getStmtClass() == OMPForSimdDirectiveClass || T->getStmtClass() == OMPParallelForDirectiveClass || T->getStmtClass() == OMPParallelForSimdDirectiveClass || T->getStmtClass() == OMPTaskLoopDirectiveClass || T->getStmtClass() == OMPTaskLoopSimdDirectiveClass || T->getStmtClass() == OMPDistributeDirectiveClass || T->getStmtClass() == OMPTargetParallelForDirectiveClass || T->getStmtClass() == OMPDistributeParallelForDirectiveClass || T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPDistributeSimdDirectiveClass || T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass || T->getStmtClass() == OMPTargetSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeDirectiveClass || T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeParallelForDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp simd' directive. /// /// \code /// #pragma omp simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp simd' has clauses 'private' /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'. /// class OMPSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSimdDirectiveClass; } }; /// This represents '#pragma omp for' directive. /// /// \code /// #pragma omp for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp for' has clauses 'private' with the /// variables 'a' and 'b' and 'reduction' with operator '+' and variables 'c' /// and 'd'. /// class OMPForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPForDirectiveClass; } }; /// This represents '#pragma omp for simd' directive. /// /// \code /// #pragma omp for simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp for simd' has clauses 'private' /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'. /// class OMPForSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPForSimdDirectiveClass; } }; /// This represents '#pragma omp sections' directive. /// /// \code /// #pragma omp sections private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp sections' has clauses 'private' with /// the variables 'a' and 'b' and 'reduction' with operator '+' and variables /// 'c' and 'd'. /// class OMPSectionsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPSectionsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner directive. /// static OMPSectionsDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPSectionsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSectionsDirectiveClass; } }; /// This represents '#pragma omp section' directive. /// /// \code /// #pragma omp section /// \endcode /// class OMPSectionDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPSectionDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section, StartLoc, EndLoc, 0, 1), HasCancel(false) {} /// Build an empty directive. /// explicit OMPSectionDirective() : OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section, SourceLocation(), SourceLocation(), 0, 1), HasCancel(false) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner directive. /// static OMPSectionDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive. /// /// \param C AST context. /// static OMPSectionDirective *CreateEmpty(const ASTContext &C, EmptyShell); /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSectionDirectiveClass; } }; /// This represents '#pragma omp single' directive. /// /// \code /// #pragma omp single private(a,b) copyprivate(c,d) /// \endcode /// In this example directive '#pragma omp single' has clauses 'private' with /// the variables 'a' and 'b' and 'copyprivate' with variables 'c' and 'd'. /// class OMPSingleDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPSingleDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPSingleDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPSingleDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSingleDirectiveClass; } }; /// This represents '#pragma omp master' directive. /// /// \code /// #pragma omp master /// \endcode /// class OMPMasterDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master, StartLoc, EndLoc, 0, 1) {} /// Build an empty directive. /// explicit OMPMasterDirective() : OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master, SourceLocation(), SourceLocation(), 0, 1) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPMasterDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt); /// Creates an empty directive. /// /// \param C AST context. /// static OMPMasterDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPMasterDirectiveClass; } }; /// This represents '#pragma omp critical' directive. /// /// \code /// #pragma omp critical /// \endcode /// class OMPCriticalDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Name of the directive. DeclarationNameInfo DirName; /// Build directive with the given start and end location. /// /// \param Name Name of the directive. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPCriticalDirective(const DeclarationNameInfo &Name, SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical, StartLoc, EndLoc, NumClauses, 1), DirName(Name) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPCriticalDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical, SourceLocation(), SourceLocation(), NumClauses, 1), DirName() {} /// Set name of the directive. /// /// \param Name Name of the directive. /// void setDirectiveName(const DeclarationNameInfo &Name) { DirName = Name; } public: /// Creates directive. /// /// \param C AST context. /// \param Name Name of the directive. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPCriticalDirective * Create(const ASTContext &C, const DeclarationNameInfo &Name, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPCriticalDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return name of the directive. /// DeclarationNameInfo getDirectiveName() const { return DirName; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCriticalDirectiveClass; } }; /// This represents '#pragma omp parallel for' directive. /// /// \code /// #pragma omp parallel for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel for' has clauses 'private' /// with the variables 'a' and 'b' and 'reduction' with operator '+' and /// variables 'c' and 'd'. /// class OMPParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if current region has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelForDirectiveClass; } }; /// This represents '#pragma omp parallel for simd' directive. /// /// \code /// #pragma omp parallel for simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel for simd' has clauses /// 'private' with the variables 'a' and 'b', 'linear' with variables 'i', 'j' /// and linear step 's', 'reduction' with operator '+' and variables 'c' and /// 'd'. /// class OMPParallelForSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass, OMPD_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass, OMPD_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPParallelForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp parallel sections' directive. /// /// \code /// #pragma omp parallel sections private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel sections' has clauses /// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+' /// and variables 'c' and 'd'. /// class OMPParallelSectionsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass, OMPD_parallel_sections, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPParallelSectionsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass, OMPD_parallel_sections, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPParallelSectionsDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPParallelSectionsDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelSectionsDirectiveClass; } }; /// This represents '#pragma omp task' directive. /// /// \code /// #pragma omp task private(a,b) final(d) /// \endcode /// In this example directive '#pragma omp task' has clauses 'private' with the /// variables 'a' and 'b' and 'final' with condition 'd'. /// class OMPTaskDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if this directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTaskDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true, if current directive has inner cancel directive. /// static OMPTaskDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTaskDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskDirectiveClass; } }; /// This represents '#pragma omp taskyield' directive. /// /// \code /// #pragma omp taskyield /// \endcode /// class OMPTaskyieldDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield, StartLoc, EndLoc, 0, 0) {} /// Build an empty directive. /// explicit OMPTaskyieldDirective() : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield, SourceLocation(), SourceLocation(), 0, 0) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPTaskyieldDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates an empty directive. /// /// \param C AST context. /// static OMPTaskyieldDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskyieldDirectiveClass; } }; /// This represents '#pragma omp barrier' directive. /// /// \code /// #pragma omp barrier /// \endcode /// class OMPBarrierDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier, StartLoc, EndLoc, 0, 0) {} /// Build an empty directive. /// explicit OMPBarrierDirective() : OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier, SourceLocation(), SourceLocation(), 0, 0) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPBarrierDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates an empty directive. /// /// \param C AST context. /// static OMPBarrierDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPBarrierDirectiveClass; } }; /// This represents '#pragma omp taskwait' directive. /// /// \code /// #pragma omp taskwait /// \endcode /// class OMPTaskwaitDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait, StartLoc, EndLoc, 0, 0) {} /// Build an empty directive. /// explicit OMPTaskwaitDirective() : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait, SourceLocation(), SourceLocation(), 0, 0) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPTaskwaitDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates an empty directive. /// /// \param C AST context. /// static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskwaitDirectiveClass; } }; /// This represents '#pragma omp taskgroup' directive. /// /// \code /// #pragma omp taskgroup /// \endcode /// class OMPTaskgroupDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup, StartLoc, EndLoc, NumClauses, 2) {} /// Build an empty directive. /// \param NumClauses Number of clauses. /// explicit OMPTaskgroupDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup, SourceLocation(), SourceLocation(), NumClauses, 2) {} /// Sets the task_reduction return variable. void setReductionRef(Expr *RR) { *std::next(child_begin(), 1) = RR; } public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param ReductionRef Reference to the task_reduction return variable. /// static OMPTaskgroupDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *ReductionRef); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTaskgroupDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Returns reference to the task_reduction return variable. const Expr *getReductionRef() const { return static_cast<const Expr *>(*std::next(child_begin(), 1)); } Expr *getReductionRef() { return static_cast<Expr *>(*std::next(child_begin(), 1)); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskgroupDirectiveClass; } }; /// This represents '#pragma omp flush' directive. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has 2 arguments- variables 'a' /// and 'b'. /// 'omp flush' directive does not have clauses but have an optional list of /// variables to flush. This list of variables is stored within some fake clause /// FlushClause. class OMPFlushDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush, StartLoc, EndLoc, NumClauses, 0) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPFlushDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush, SourceLocation(), SourceLocation(), NumClauses, 0) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses (only single OMPFlushClause clause is /// allowed). /// static OMPFlushDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPFlushDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPFlushDirectiveClass; } }; /// This represents '#pragma omp ordered' directive. /// /// \code /// #pragma omp ordered /// \endcode /// class OMPOrderedDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPOrderedDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPOrderedDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPOrderedDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPOrderedDirectiveClass; } }; /// This represents '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has clause 'capture'. /// class OMPAtomicDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Used for 'atomic update' or 'atomic capture' constructs. They may /// have atomic expressions of forms /// \code /// x = x binop expr; /// x = expr binop x; /// \endcode /// This field is true for the first form of the expression and false for the /// second. Required for correct codegen of non-associative operations (like /// << or >>). bool IsXLHSInRHSPart; /// Used for 'atomic update' or 'atomic capture' constructs. They may /// have atomic expressions of forms /// \code /// v = x; <update x>; /// <update x>; v = x; /// \endcode /// This field is true for the first(postfix) form of the expression and false /// otherwise. bool IsPostfixUpdate; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic, StartLoc, EndLoc, NumClauses, 5), IsXLHSInRHSPart(false), IsPostfixUpdate(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPAtomicDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic, SourceLocation(), SourceLocation(), NumClauses, 5), IsXLHSInRHSPart(false), IsPostfixUpdate(false) {} /// Set 'x' part of the associated expression/statement. void setX(Expr *X) { *std::next(child_begin()) = X; } /// Set helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. void setUpdateExpr(Expr *UE) { *std::next(child_begin(), 2) = UE; } /// Set 'v' part of the associated expression/statement. void setV(Expr *V) { *std::next(child_begin(), 3) = V; } /// Set 'expr' part of the associated expression/statement. void setExpr(Expr *E) { *std::next(child_begin(), 4) = E; } public: /// Creates directive with a list of \a Clauses and 'x', 'v' and 'expr' /// parts of the atomic construct (see Section 2.12.6, atomic Construct, for /// detailed description of 'x', 'v' and 'expr'). /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param X 'x' part of the associated expression/statement. /// \param V 'v' part of the associated expression/statement. /// \param E 'expr' part of the associated expression/statement. /// \param UE Helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. /// \param IsXLHSInRHSPart true if \a UE has the first form and false if the /// second. /// \param IsPostfixUpdate true if original value of 'x' must be stored in /// 'v', not an updated one. static OMPAtomicDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V, Expr *E, Expr *UE, bool IsXLHSInRHSPart, bool IsPostfixUpdate); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPAtomicDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Get 'x' part of the associated expression/statement. Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); } const Expr *getX() const { return cast_or_null<Expr>(*std::next(child_begin())); } /// Get helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. Expr *getUpdateExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 2)); } const Expr *getUpdateExpr() const { return cast_or_null<Expr>(*std::next(child_begin(), 2)); } /// Return true if helper update expression has form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } /// Return true if 'v' expression must be updated to original value of /// 'x', false if 'v' must be updated to the new value of 'x'. bool isPostfixUpdate() const { return IsPostfixUpdate; } /// Get 'v' part of the associated expression/statement. Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); } const Expr *getV() const { return cast_or_null<Expr>(*std::next(child_begin(), 3)); } /// Get 'expr' part of the associated expression/statement. Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 4)); } const Expr *getExpr() const { return cast_or_null<Expr>(*std::next(child_begin(), 4)); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPAtomicDirectiveClass; } }; /// This represents '#pragma omp target' directive. /// /// \code /// #pragma omp target if(a) /// \endcode /// In this example directive '#pragma omp target' has clause 'if' with /// condition 'a'. /// class OMPTargetDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetDirectiveClass; } }; /// This represents '#pragma omp target data' directive. /// /// \code /// #pragma omp target data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target data' has clauses 'device' /// with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetDataDirectiveClass; } }; /// This represents '#pragma omp target enter data' directive. /// /// \code /// #pragma omp target enter data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target enter data' has clauses /// 'device' with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetEnterDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass, OMPD_target_enter_data, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetEnterDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass, OMPD_target_enter_data, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetEnterDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetEnterDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetEnterDataDirectiveClass; } }; /// This represents '#pragma omp target exit data' directive. /// /// \code /// #pragma omp target exit data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target exit data' has clauses /// 'device' with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetExitDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass, OMPD_target_exit_data, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetExitDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass, OMPD_target_exit_data, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetExitDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetExitDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetExitDataDirectiveClass; } }; /// This represents '#pragma omp target parallel' directive. /// /// \code /// #pragma omp target parallel if(a) /// \endcode /// In this example directive '#pragma omp target parallel' has clause 'if' with /// condition 'a'. /// class OMPTargetParallelDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass, OMPD_target_parallel, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass, OMPD_target_parallel, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetParallelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetParallelDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelDirectiveClass; } }; /// This represents '#pragma omp target parallel for' directive. /// /// \code /// #pragma omp target parallel for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp target parallel for' has clauses /// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+' /// and variables 'c' and 'd'. /// class OMPTargetParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if current region has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass, OMPD_target_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass, OMPD_target_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPTargetParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelForDirectiveClass; } }; /// This represents '#pragma omp teams' directive. /// /// \code /// #pragma omp teams if(a) /// \endcode /// In this example directive '#pragma omp teams' has clause 'if' with /// condition 'a'. /// class OMPTeamsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTeamsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTeamsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDirectiveClass; } }; /// This represents '#pragma omp cancellation point' directive. /// /// \code /// #pragma omp cancellation point for /// \endcode /// /// In this example a cancellation point is created for innermost 'for' region. class OMPCancellationPointDirective : public OMPExecutableDirective { friend class ASTStmtReader; OpenMPDirectiveKind CancelRegion; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass, OMPD_cancellation_point, StartLoc, EndLoc, 0, 0), CancelRegion(OMPD_unknown) {} /// Build an empty directive. /// explicit OMPCancellationPointDirective() : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass, OMPD_cancellation_point, SourceLocation(), SourceLocation(), 0, 0), CancelRegion(OMPD_unknown) {} /// Set cancel region for current cancellation point. /// \param CR Cancellation region. void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; } public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPCancellationPointDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Creates an empty directive. /// /// \param C AST context. /// static OMPCancellationPointDirective *CreateEmpty(const ASTContext &C, EmptyShell); /// Get cancellation region for the current cancellation point. OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCancellationPointDirectiveClass; } }; /// This represents '#pragma omp cancel' directive. /// /// \code /// #pragma omp cancel for /// \endcode /// /// In this example a cancel is created for innermost 'for' region. class OMPCancelDirective : public OMPExecutableDirective { friend class ASTStmtReader; OpenMPDirectiveKind CancelRegion; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel, StartLoc, EndLoc, NumClauses, 0), CancelRegion(OMPD_unknown) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. explicit OMPCancelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel, SourceLocation(), SourceLocation(), NumClauses, 0), CancelRegion(OMPD_unknown) {} /// Set cancel region for current cancellation point. /// \param CR Cancellation region. void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; } public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// static OMPCancelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, OpenMPDirectiveKind CancelRegion); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPCancelDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Get cancellation region for the current cancellation point. OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCancelDirectiveClass; } }; /// This represents '#pragma omp taskloop' directive. /// /// \code /// #pragma omp taskloop private(a,b) grainsize(val) num_tasks(num) /// \endcode /// In this example directive '#pragma omp taskloop' has clauses 'private' /// with the variables 'a' and 'b', 'grainsize' with expression 'val' and /// 'num_tasks' with expression 'num'. /// class OMPTaskLoopDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTaskLoopDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTaskLoopDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTaskLoopDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskLoopDirectiveClass; } }; /// This represents '#pragma omp taskloop simd' directive. /// /// \code /// #pragma omp taskloop simd private(a,b) grainsize(val) num_tasks(num) /// \endcode /// In this example directive '#pragma omp taskloop simd' has clauses 'private' /// with the variables 'a' and 'b', 'grainsize' with expression 'val' and /// 'num_tasks' with expression 'num'. /// class OMPTaskLoopSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass, OMPD_taskloop_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass, OMPD_taskloop_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTaskLoopSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTaskLoopSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskLoopSimdDirectiveClass; } }; /// This represents '#pragma omp distribute' directive. /// /// \code /// #pragma omp distribute private(a,b) /// \endcode /// In this example directive '#pragma omp distribute' has clauses 'private' /// with the variables 'a' and 'b' /// class OMPDistributeDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeDirectiveClass; } }; /// This represents '#pragma omp target update' directive. /// /// \code /// #pragma omp target update to(a) from(b) device(1) /// \endcode /// In this example directive '#pragma omp target update' has clause 'to' with /// argument 'a', clause 'from' with argument 'b' and clause 'device' with /// argument '1'. /// class OMPTargetUpdateDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass, OMPD_target_update, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetUpdateDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass, OMPD_target_update, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetUpdateDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses The number of clauses. /// static OMPTargetUpdateDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetUpdateDirectiveClass; } }; /// This represents '#pragma omp distribute parallel for' composite /// directive. /// /// \code /// #pragma omp distribute parallel for private(a,b) /// \endcode /// In this example directive '#pragma omp distribute parallel for' has clause /// 'private' with the variables 'a' and 'b' /// class OMPDistributeParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel = false; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass, OMPD_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass, OMPD_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp distribute parallel for simd' composite /// directive. /// /// \code /// #pragma omp distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp distribute parallel for simd' has /// clause 'private' with the variables 'x' /// class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, OMPD_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, OMPD_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeParallelForSimdDirective *Create( const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeParallelForSimdDirective *CreateEmpty( const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp distribute simd' composite directive. /// /// \code /// #pragma omp distribute simd private(x) /// \endcode /// In this example directive '#pragma omp distribute simd' has clause /// 'private' with the variables 'x' /// class OMPDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp target parallel for simd' directive. /// /// \code /// #pragma omp target parallel for simd private(a) map(b) safelen(c) /// \endcode /// In this example directive '#pragma omp target parallel for simd' has clauses /// 'private' with the variable 'a', 'map' with the variable 'b' and 'safelen' /// with the variable 'c'. /// class OMPTargetParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass, OMPD_target_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass, OMPD_target_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetParallelForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp target simd' directive. /// /// \code /// #pragma omp target simd private(a) map(b) safelen(c) /// \endcode /// In this example directive '#pragma omp target simd' has clauses 'private' /// with the variable 'a', 'map' with the variable 'b' and 'safelen' with /// the variable 'c'. /// class OMPTargetSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, SourceLocation(),SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute' directive. /// /// \code /// #pragma omp teams distribute private(a,b) /// \endcode /// In this example directive '#pragma omp teams distribute' has clauses /// 'private' with the variables 'a' and 'b' /// class OMPTeamsDistributeDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, OMPD_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, OMPD_teams_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeDirectiveClass; } }; /// This represents '#pragma omp teams distribute simd' /// combined directive. /// /// \code /// #pragma omp teams distribute simd private(a,b) /// \endcode /// In this example directive '#pragma omp teams distribute simd' /// has clause 'private' with the variables 'a' and 'b' /// class OMPTeamsDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass, OMPD_teams_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass, OMPD_teams_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute parallel for simd' composite /// directive. /// /// \code /// #pragma omp teams distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp teams distribute parallel for simd' /// has clause 'private' with the variables 'x' /// class OMPTeamsDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPD_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPD_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeParallelForSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute parallel for' composite /// directive. /// /// \code /// #pragma omp teams distribute parallel for private(x) /// \endcode /// In this example directive '#pragma omp teams distribute parallel for' /// has clause 'private' with the variables 'x' /// class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel = false; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass, OMPD_teams_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass, OMPD_teams_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPTeamsDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeParallelForDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp target teams' directive. /// /// \code /// #pragma omp target teams if(a>0) /// \endcode /// In this example directive '#pragma omp target teams' has clause 'if' with /// condition 'a>0'. /// class OMPTargetTeamsDirective final : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass, OMPD_target_teams, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass, OMPD_target_teams, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDirectiveClass; } }; /// This represents '#pragma omp target teams distribute' combined directive. /// /// \code /// #pragma omp target teams distribute private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute' has clause /// 'private' with the variables 'x' /// class OMPTargetTeamsDistributeDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass, OMPD_target_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass, OMPD_target_teams_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass; } }; /// This represents '#pragma omp target teams distribute parallel for' combined /// directive. /// /// \code /// #pragma omp target teams distribute parallel for private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute parallel /// for' has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeParallelForDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel = false; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPD_target_teams_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective( this, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPD_target_teams_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPTargetTeamsDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeParallelForDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp target teams distribute parallel for simd' /// combined directive. /// /// \code /// #pragma omp target teams distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute parallel /// for simd' has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPD_target_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeParallelForSimdDirective( unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective( this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPD_target_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeParallelForSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp target teams distribute simd' combined /// directive. /// /// \code /// #pragma omp target teams distribute simd private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute simd' /// has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass, OMPD_target_teams_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass, OMPD_target_teams_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass; } }; } // end namespace clang #endif
GB_unaryop__abs_uint16_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint16_uint8 // op(A') function: GB_tran__abs_uint16_uint8 // C type: uint16_t // A type: uint8_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT16 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint16_uint8 ( uint16_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint16_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_reduce_each_vector.c
//------------------------------------------------------------------------------ // GB_reduce_each_vector: Tx(j)=reduce(A(:,j)), reduce a matrix to a vector //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Reduce a matrix to a vector. The kth vector A(:,k) is reduced to the kth // scalar Tx(k). Each thread computes the reductions on roughly the same number // of entries, which means that a vector A(:,k) may be reduced by more than one // thread. The first vector A(:,kfirst) reduced by thread tid may be partial, // where the prior thread tid-1 (and other prior threads) may also do some of // the reductions for this same vector A(:,kfirst). The thread tid fully // reduces all vectors A(:,k) for k in the range kfirst+1 to klast-1. The last // vector A(:,klast) reduced by thread tid may also be partial. Thread tid+1, // and following threads, may also do some of the reduces for A(:,klast). #ifndef GB_GET_J #define GB_GET_J ; #endif { // Ah, Ai, asize, avlen, avdim unused for some uses of this template #include "GB_unused.h" //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; const GB_ATYPE *restrict Ax = A->x ; size_t asize = A->type->size ; int64_t avlen = A->vlen ; int64_t avdim = A->vdim ; //-------------------------------------------------------------------------- // workspace for first and last vectors of each slice //-------------------------------------------------------------------------- // ztype Wfirst [ntasks], Wlast [ntasks] ; GB_CTYPE *restrict Wfirst = (GB_CTYPE *) Wfirst_space ; GB_CTYPE *restrict Wlast = (GB_CTYPE *) Wlast_space ; //-------------------------------------------------------------------------- // reduce each slice //-------------------------------------------------------------------------- // each thread reduces its own part in parallel #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (int tid = 0 ; tid < ntasks ; tid++) { // if kfirst > klast then thread tid does no work at all int64_t kfirst = kfirst_slice [tid] ; int64_t klast = klast_slice [tid] ; //---------------------------------------------------------------------- // reduce vectors kfirst to klast //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of A(:,k) to be reduced by this thread //------------------------------------------------------------------ GB_GET_J ; int64_t pA_start, pA_end ; GB_get_pA_and_pC (&pA_start, &pA_end, NULL, tid, k, kfirst, klast, pstart_slice, NULL, NULL, Ap) ; //------------------------------------------------------------------ // reduce Ax [pA_start ... pA_end-1] to a scalar, if non-empty //------------------------------------------------------------------ if (pA_start < pA_end) { //-------------------------------------------------------------- // reduce the vector to the scalar s //-------------------------------------------------------------- // ztype s = (ztype) Ax [pA_start], with typecast GB_SCALAR (s) ; GB_CAST_ARRAY_TO_SCALAR (s, Ax, pA_start) ; for (int64_t p = pA_start+1 ; p < pA_end ; p++) { // check for early exit GB_BREAK_IF_TERMINAL (s) ; // s += (ztype) Ax [p], with typecast GB_ADD_CAST_ARRAY_TO_SCALAR (s, Ax, p) ; } //-------------------------------------------------------------- // save the result s //-------------------------------------------------------------- if (k == kfirst) { // Wfirst [tid] = s ; no typecast GB_COPY_SCALAR_TO_ARRAY (Wfirst, tid, s) ; } else if (k == klast) { // Wlast [tid] = s ; no typecast GB_COPY_SCALAR_TO_ARRAY (Wlast, tid, s) ; } else { // Tx [k] = s ; no typecast GB_COPY_SCALAR_TO_ARRAY (Tx, k, s) ; } } } } //-------------------------------------------------------------------------- // reduce the first and last vector of each slice using a single thread //-------------------------------------------------------------------------- // This step is sequential, but it takes only O(ntasks) time. The only // case where this could be a problem is if a user-defined operator was // a very costly one. int64_t kprior = -1 ; for (int tid = 0 ; tid < ntasks ; tid++) { //---------------------------------------------------------------------- // sum up the partial result that thread tid computed for kfirst //---------------------------------------------------------------------- int64_t kfirst = kfirst_slice [tid] ; int64_t klast = klast_slice [tid] ; if (kfirst <= klast) { int64_t pA_start = pstart_slice [tid] ; int64_t pA_end = GB_IMIN (Ap [kfirst+1], pstart_slice [tid+1]) ; if (pA_start < pA_end) { if (kprior < kfirst) { // This thread is the first one that did work on // A(:,kfirst), so use it to start the reduction. // Tx [kfirst] = Wfirst [tid], no typecast GB_COPY_ARRAY_TO_ARRAY (Tx, kfirst, Wfirst, tid) ; } else { // Tx [kfirst] += Wfirst [tid], no typecast GB_ADD_ARRAY_TO_ARRAY (Tx, kfirst, Wfirst, tid) ; } kprior = kfirst ; } } //---------------------------------------------------------------------- // sum up the partial result that thread tid computed for klast //---------------------------------------------------------------------- if (kfirst < klast) { int64_t pA_start = Ap [klast] ; int64_t pA_end = pstart_slice [tid+1] ; if (pA_start < pA_end) { /* if */ ASSERT (kprior < klast) ; { // This thread is the first one that did work on // A(:,klast), so use it to start the reduction. // Tx [klast] = Wlast [tid], no typecast GB_COPY_ARRAY_TO_ARRAY (Tx, klast, Wlast, tid) ; } /* else { // If kfirst < klast and A(:,klast is not empty, then this // task is always the first one to do work on A(:,klast), // so this case is never used. ASSERT (GB_DEAD_CODE) ; // Tx [klast] += Wlast [tid], no typecast GB_ADD_ARRAY_TO_ARRAY (Tx, klast, Wlast, tid) ; } */ kprior = klast ; } } } }
GB_binop__land_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__land_int64) // A.*B function (eWiseMult): GB (_AemultB_08__land_int64) // A.*B function (eWiseMult): GB (_AemultB_02__land_int64) // A.*B function (eWiseMult): GB (_AemultB_04__land_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__land_int64) // A*D function (colscale): GB (_AxD__land_int64) // D*A function (rowscale): GB (_DxB__land_int64) // C+=B function (dense accum): GB (_Cdense_accumB__land_int64) // C+=b function (dense accum): GB (_Cdense_accumb__land_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__land_int64) // C=scalar+B GB (_bind1st__land_int64) // C=scalar+B' GB (_bind1st_tran__land_int64) // C=A+scalar GB (_bind2nd__land_int64) // C=A'+scalar GB (_bind2nd_tran__land_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_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) \ int64_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) \ 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 != 0) && (y != 0)) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LAND || GxB_NO_INT64 || GxB_NO_LAND_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__land_int64) ( 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__land_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__land_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__land_int64) ( 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 int64_t *restrict Cx = (int64_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__land_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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 } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__land_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 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) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_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__land_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__land_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__land_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__land_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__land_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 != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__land_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 != 0) && (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__land_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 != 0) && (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__land_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
grid.c
/* * Copyright (C) 2016 Leo Fang <leofang@phy.duke.edu> * * This program is free software. It comes without any warranty, * to the extent permitted by applicable law. You can redistribute * it and/or modify it under the terms of the WTFPL, Version 2, as * published by Sam Hocevar. See the accompanying LICENSE file or * http://www.wtfpl.net/ for more details. */ #include <stdlib.h> #include <string.h> #include "kv.h" #include "grid.h" #include "special_function.h" #include "dynamics.h" #include "NM_measure.h" double getRealTime(); //defined in getRealTime.c extern double complex W; //declared in main.c #ifdef __FDTD_OPENMP_SUPPORT__ void initialize_OpenMP_team(grid * simulation) { int temp; #pragma omp parallel { #pragma omp single { temp = omp_get_num_threads(); } } //caveat: it could be possible that users forget to set Nth in the input, //and in this case Nth is set as 1 if(temp != simulation->Nth) { fprintf(stderr, "%s: OMP_NUM_THREADS is inconsistent with Nth. Using the latter...\n", __func__); omp_set_num_threads(simulation->Nth); } #pragma omp parallel { #pragma omp single { printf("FDTD: Using %i threads...\n", omp_get_num_threads()); } } } #endif //This function returns the normalization constant A for the two-photon initial state used for init_cond=3 void calculate_normalization_const(grid * simulation) { if(simulation->identical_photons) //skip the math simulation->A = 1./sqrt(2.); else { double k1 = simulation->k1 / simulation->Gamma; double k2 = simulation->k2 / simulation->Gamma; double alpha1 = simulation->alpha1; double alpha2 = simulation->alpha2; simulation->A = sqrt( (4.*pow(k1-k2,2) + pow(alpha1+alpha2,2)) / \ (4.*pow(k1-k2,2) + (pow(alpha1,2) + 6.*alpha1*alpha2 + pow(alpha2,2))) ); } } // This function returns the solution psi[j][i] in x<-a subject to two-photon plane wave double complex plane_wave_BC(int j, int i, grid * simulation) { double x = (i-simulation->origin_index)*simulation->Delta; //check!!! double t = j*simulation->Delta; double td = simulation->nx*simulation->Delta; double w0 = simulation->w0; double Gamma = simulation->Gamma; double complex K = I*simulation->k; double complex p = -I*(K - W); //W = I*w0 + 0.5*Gamma; double complex e_t = I*sqrt(0.5*Gamma)*(cexp(-K*t)-cexp(-W*t))/p; double complex sum = 0; for(int n=1; n<=(j/simulation->nx); n++) { double complex temp = ( cexp( n*log(t-n*td) - W*(t-n*td) - lgamma(n+1) ) \ - (I*K+w0) * incomplete_gamma_e(n+1, -I*p*(t-n*td), n*clog(I) - (n+1)*clog(p) - K*(t-n*td) ) ); temp *= cpow(0.5*Gamma, n-0.5); // based on my observation, the wavefunction should converge very fast, // so one can just cut the summation off if the precision is reached. // this also helps prevent some overflow issue a bit. if( cabs(temp) < DBL_EPSILON*cabs(sum) || isnan(cabs(temp)) ) break; else sum += temp; } e_t -= sum; e_t *= sqrt(2.)*cexp(K*(x-t)); // psi(x,t) = sqrt(2)e^{ik(x-t)}*e(t) e_t *= cexp(-0.5*K*td); //TODO: this phase factor can be eliminated by absorbing into the wavepacket if(!isnan(cabs(e_t))) return e_t; else { fprintf(stderr, "%s: NaN is produced (at j=%i and i=%i). Abort!\n", __func__, j, i); exit(EXIT_FAILURE); } } // This function returns the solution psi[j][i] in x<-a subject to single-photon exponential wavepacket double complex exponential_BC(int j, int i, grid * simulation) { // psi(x,t) = psi(x-t, 0) * e(t) return simulation->e1[j] * one_photon_exponential(i-simulation->origin_index-j, simulation->k, simulation->alpha, simulation); } // This function returns the solution psi[j][i] in x<-a subject to two-photon exponential wavepacket double complex two_exponential_BC(int j, int i, grid * simulation) { // psi(x,t) = [ \varphi^2(x-t, 0) * e0^1(t) + (1<->2) ]/\sqrt{2} when photon 1 != photon 2 if(simulation->identical_photons) return sqrt(2.) * simulation->A * simulation->e0[j] \ * one_photon_exponential(i-simulation->origin_index-j, simulation->k, simulation->alpha, simulation); else { static double complex varphi_1, varphi_2; //TODO: make sure both are static varphi_1 = one_photon_exponential(i-simulation->origin_index-j, simulation->k1, simulation->alpha1, simulation); varphi_2 = one_photon_exponential(i-simulation->origin_index-j, simulation->k2, simulation->alpha2, simulation); return (simulation->e0_1[j] * varphi_2 + simulation->e0_2[j] * varphi_1) * simulation->A / sqrt(2.); } } //TODO: this should be generalized to acommadate different I.C. void prepare_qubit_wavefunction(grid * simulation) { //do this only if the exponential wavepacket is used if(simulation->init_cond == 2 || simulation->init_cond == 3) { initialize_e0(simulation); initialize_e1(simulation); } } void initialize_e0(grid * simulation) { if(simulation->identical_photons) //one wavepacket or two identical exponential wavepackets { simulation->e0 = calloc(simulation->Ny, sizeof(*simulation->e0)); if(!simulation->e0) { fprintf(stderr, "%s: cannot allocate memory. Abort!\n", __func__); exit(EXIT_FAILURE); } for(int j=0; j<simulation->Ny; j++) { simulation->e0[j] = e0(j, simulation); } } else //two different exponential wavepackets { simulation->e0_1 = calloc(simulation->Ny, sizeof(*simulation->e0_1)); simulation->e0_2 = calloc(simulation->Ny, sizeof(*simulation->e0_2)); if(!simulation->e0_1 || !simulation->e0_2) { fprintf(stderr, "%s: cannot allocate memory. Abort!\n", __func__); exit(EXIT_FAILURE); } for(int j=0; j<simulation->Ny; j++) { simulation->k = simulation->k1; simulation->alpha = simulation->alpha1; simulation->e0_1[j] = e0(j, simulation); simulation->k = simulation->k2; simulation->alpha = simulation->alpha2; simulation->e0_2[j] = e0(j, simulation); } } //TODO: add other I.C. here } //e1 is the solution of spontaneous emission and is independent of incident wavepackets void initialize_e1(grid * simulation) { simulation->e1 = calloc(simulation->Ny, sizeof(*simulation->e1)); if(!simulation->e1) { fprintf(stderr, "%s: cannot allocate memory. Abort!\n", __func__); exit(EXIT_FAILURE); } for(int j=0; j<simulation->Ny; j++) { simulation->e1[j] = e1(j, simulation); } } void initial_condition(grid * simulation) {// the initial condition is given in-between x/Delta = [-Nx, Nx] for simplicity simulation->psit0 = calloc(2*simulation->Nx+1, sizeof(*simulation->psit0)); if(!simulation->psit0) { perror("initial_condition: cannot allocate memory. Abort!\n"); exit(EXIT_FAILURE); } simulation->psit0_size = 2*simulation->Nx+1; //for nonzero initial conditions if(simulation->init_cond == 2) //single-photon exponential wavepacket { for(int i=0; i<simulation->psit0_size; i++) simulation->psit0[i] = one_photon_exponential(i-simulation->Nx, simulation->k, simulation->alpha, simulation); } //TODO: add other I.C. here } void boundary_condition(grid * simulation) {// the boundary conditions is given for first nx+1 columns with // x/Delta=[-(Nx+nx+1),-(Nx+1)] due to the delay term simulation->psix0 = malloc( simulation->Ny*sizeof(*simulation->psix0) ); if(!simulation->psix0) { perror("boundary_condition: cannot allocate memory. Abort!\n"); exit(EXIT_FAILURE); } simulation->psix0_x_size = simulation->nx+1; simulation->psix0_y_size = 0; for(int j=0; j<simulation->Ny; j++) { simulation->psix0[j] = calloc(simulation->nx+1, sizeof(*simulation->psix0[j])); if(!simulation->psix0[j]) { fprintf(stderr, "%s: cannot allocate memory at t=%d*Delta. Abort!\n", __func__, j); exit(EXIT_FAILURE); } simulation->psix0_y_size++; } double start = getRealTime(); #ifdef __FDTD_OPENMP_SUPPORT__ #pragma omp parallel { #pragma omp for collapse(2) #endif for(int j=0; j<simulation->psix0_y_size; j++) { for(int i=0; i<simulation->psix0_x_size; i++) { switch(simulation->init_cond) { //two-photon plane wave case 1: { simulation->psix0[j][i] = plane_wave_BC(j, i, simulation); } break; //single-photon exponential wavepacket case 2: { simulation->psix0[j][i] = exponential_BC(j, i, simulation); } break; //two-photon exponential wavepacket case 3: { simulation->psix0[j][i] = two_exponential_BC(j, i, simulation); } break; default: { /* bad input, but sanity_check ensures we never arrives here */ } } } } #ifdef __FDTD_OPENMP_SUPPORT__ } #endif double end = getRealTime(); printf("FDTD: %s spent: %f s (getRealTime)\n", __func__, end-start); } void initialize_psi(grid * simulation) { simulation->psi = malloc( simulation->Ny*sizeof(*simulation->psi) ); if(!simulation->psi) { perror("initialize_psi: cannot allocate memory. Abort!\n"); exit(EXIT_FAILURE); } simulation->psi_x_size = simulation->Ntotal; simulation->psi_y_size = 0; for(int j=0; j<simulation->Ny; j++) { simulation->psi[j] = calloc( simulation->Ntotal, sizeof(*simulation->psi[j]) ); if(!simulation->psi[j]) { fprintf(stderr, "%s: cannot allocate memory at t=%d*Delta. Abort!\n", __func__, j); exit(EXIT_FAILURE); } simulation->psi_y_size++; // take boundary conditions for(int i=0; i<simulation->psix0_x_size; i++) simulation->psi[j][i] = simulation->psix0[j][i]; } // take the initial condition for(int i=0; i<simulation->psit0_size; i++) simulation->psi[0][i+simulation->psix0_x_size] = simulation->psit0[i]; } //a set of checks (poka-yoke) that make sure the input file is sane void sanity_check(grid * simulation) { //nx must be multiple of 2 if(simulation->nx % 2) { fprintf(stderr, "%s: nx must be an integer multiple of 2. Abort!\n", __func__); exit(EXIT_FAILURE); } //nx<=2Nx if(simulation->nx > 2*simulation->Nx) { fprintf(stderr, "%s: nx must be smaller than, or at most equal to, twice of Nx (nx<=2Nx). Abort!\n", __func__); exit(EXIT_FAILURE); } //Nyquist limit if(simulation->k >= M_PI/simulation->Delta || simulation->w0 >= M_PI/simulation->Delta) { fprintf(stderr, "%s: k or w0 must be smaller than pi/Delta in order not to reach the Nyquist limit. Abort!\n", __func__); exit(EXIT_FAILURE); } //it is meaningless if one performs the computation without saving any result if(!simulation->save_chi && !simulation->save_chi_map && !simulation->save_psi\ && !simulation->save_psi_square_integral && !simulation->save_psi_binary && !simulation->measure_NM) { //fprintf(stderr, "%s: either save_chi or save_psi has to be 1. Abort!\n", __func__); fprintf(stderr, "%s: need to specify the output options (available: save_chi, save_chi_map, save_psi, save_psi_square_integral, save_psi_binary, measure_NM). Abort!\n", __func__); exit(EXIT_FAILURE); } ////if Ny is too small then no result will be written to file //if(simulation->save_chi && (simulation->Ny <= simulation->Nx + simulation->nx/2)) //{ // fprintf(stderr, "%s: Ny needs to be larger than Nx+nx/2, or \"chi\" will not be stored. Abort!\n", __func__); // exit(EXIT_FAILURE); //} //check if the initial condition is not correctly given //currently the allowed values are: //1 (two-photon plane wave) //2 (single-photon exponential wavepacket) //3 (two-photon exponential wavepackets) if(simulation->init_cond < 1 || simulation->init_cond > 3) { fprintf(stderr, "%s: init_cond has to be 1, 2 or 3. Abort!\n", __func__); exit(EXIT_FAILURE); } if((simulation->init_cond == 1 || simulation->init_cond == 2) && !lookupValue(simulation->parameters_key_value_pair, "k")) { //k is a mandatory parameter when init_cond is 1 or 2 fprintf(stderr, "%s: the incident frequency k must be given when init_cond is 1 or 2. Abort!\n", __func__); exit(EXIT_FAILURE); } if(simulation->init_cond == 1 && simulation->save_psi_square_integral == 1) { fprintf(stderr, "%s: no support (yet) for save_psi_square_integral with init_cond=1. Abort!\n", __func__); exit(EXIT_FAILURE); } if(simulation->init_cond == 2) { //want to use exponential wavepacket but forget to set alpha's value if(!lookupValue(simulation->parameters_key_value_pair, "alpha")) { fprintf(stderr, "%s: alpha is not given. Abort!\n", __func__); exit(EXIT_FAILURE); } //always 1 in this case, in case the user prepared it wrong simulation->identical_photons = 1; } if(simulation->init_cond == 3) { //make it failed if identical_photons is not explicitly specified for this case //so that identical_photons can be safely set to 1 as default if(!lookupValue(simulation->parameters_key_value_pair, "identical_photons")) { fprintf(stderr, "%s: for two-photon wavapacket calculations, identical_photons needs to be specified (either 0 or 1). Abort!\n", __func__); exit(EXIT_FAILURE); } //two identical photons if(simulation->identical_photons && (!lookupValue(simulation->parameters_key_value_pair, "k") || !lookupValue(simulation->parameters_key_value_pair, "alpha")) ) { fprintf(stderr, "%s: for two identical photons, k and alpha need to be specified. Abort!\n", __func__); exit(EXIT_FAILURE); } //two different photons if(!simulation->identical_photons && (!lookupValue(simulation->parameters_key_value_pair, "k1") || !lookupValue(simulation->parameters_key_value_pair, "k2") || !lookupValue(simulation->parameters_key_value_pair, "alpha1") || !lookupValue(simulation->parameters_key_value_pair, "alpha2")) ) { fprintf(stderr, "%s: for two different photons, k1, k2, alpha1 and alpha2 need to be specified. Abort!\n", __func__); exit(EXIT_FAILURE); } } //calculate_NM_measure only supports well-defined (normalized) single-photon wavepacket if(simulation->measure_NM && (simulation->init_cond!=2)) { fprintf(stderr, "%s: to calculate lambda and mu for NM measures, set init_cond to be 2. Abort!\n", __func__); exit(EXIT_FAILURE); } if(simulation->Nth<=0) { fprintf(stderr, "%s: the number of threads (Nth) must be at least 1. Abort!\n", __func__); exit(EXIT_FAILURE); } } void free_initial_boundary_conditions(grid * simulation) {//free psit0 and psix0 to save memory free(simulation->psit0); for(int j=0; j<simulation->Ny; j++) free(simulation->psix0[j]); free(simulation->psix0); //reset simulation->psix0 = NULL; simulation->psit0 = NULL; simulation->psix0_x_size = 0; simulation->psix0_y_size = 0; simulation->psit0_size = 0; } void free_grid(grid * simulation) { freeKVs(simulation->parameters_key_value_pair); //free psit0 and psix0 //free_initial_boundary_conditions(simulation); //free psi for(int j=0; j<simulation->Ny; j++) free(simulation->psi[j]); free(simulation->psi); //free e0 & e1 //TODO: take care of this part if the code grows! if(simulation->init_cond == 2 || simulation->init_cond == 3) { if(simulation->identical_photons) free(simulation->e0); else { free(simulation->e0_1); free(simulation->e0_2); } free(simulation->e1); } free(simulation); } grid * initialize_grid(const char * filename) { grid * FDTDsimulation = malloc(sizeof(*FDTDsimulation)); if(!FDTDsimulation) { perror("initialize_grid: could not allocate memory. Abort!\n"); exit(EXIT_FAILURE); } //read from input FDTDsimulation->parameters_key_value_pair = readKVs(filename); //initialize from the input parameters FDTDsimulation->nx = atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "nx")); FDTDsimulation->Nx = atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "Nx")); FDTDsimulation->Ntotal = 2 * FDTDsimulation->Nx + FDTDsimulation->nx + 2; FDTDsimulation->Ny = atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "Ny")); FDTDsimulation->Delta = strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "Delta"), NULL); //FDTDsimulation->k = strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "k"), NULL); FDTDsimulation->k = (lookupValue(FDTDsimulation->parameters_key_value_pair, "k") ? \ strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "k"), NULL) : 0); //default: 0 FDTDsimulation->k1 = (lookupValue(FDTDsimulation->parameters_key_value_pair, "k1") ? \ strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "k1"), NULL) : 0); //default: 0 FDTDsimulation->k2 = (lookupValue(FDTDsimulation->parameters_key_value_pair, "k2") ? \ strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "k2"), NULL) : 0); //default: 0 FDTDsimulation->w0 = strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "w0"), NULL); FDTDsimulation->Gamma = strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "gamma"), NULL); FDTDsimulation->Lx = 2 * FDTDsimulation->Nx * FDTDsimulation->Delta; FDTDsimulation->Ly = (FDTDsimulation->Ny-1) * FDTDsimulation->Delta; FDTDsimulation->plus_a_index = FDTDsimulation->Nx + 3*FDTDsimulation->nx/2 + 1; FDTDsimulation->minus_a_index = FDTDsimulation->Nx + FDTDsimulation->nx/2 + 1; FDTDsimulation->origin_index = FDTDsimulation->Nx + FDTDsimulation->nx + 1; FDTDsimulation->save_chi = (lookupValue(FDTDsimulation->parameters_key_value_pair, "save_chi") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "save_chi")) : 0); //default: off FDTDsimulation->save_chi_map = (lookupValue(FDTDsimulation->parameters_key_value_pair, "save_chi_map") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "save_chi_map")) : 0); //default: off FDTDsimulation->save_psi = (lookupValue(FDTDsimulation->parameters_key_value_pair, "save_psi") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "save_psi")) : 0); //default: off FDTDsimulation->save_psi_square_integral = (lookupValue(FDTDsimulation->parameters_key_value_pair, "save_psi_square_integral") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "save_psi_square_integral")) : 0); //default: off FDTDsimulation->save_psi_binary = (lookupValue(FDTDsimulation->parameters_key_value_pair, "save_psi_binary") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "save_psi_binary")) : 0); //default: off FDTDsimulation->init_cond = (lookupValue(FDTDsimulation->parameters_key_value_pair, "init_cond") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "init_cond")) : 0); //default: 0 (unspecified) FDTDsimulation->identical_photons = (lookupValue(FDTDsimulation->parameters_key_value_pair, "identical_photons") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "identical_photons")) : 1); //default: 1 (yes) FDTDsimulation->alpha = (lookupValue(FDTDsimulation->parameters_key_value_pair, "alpha") ? \ strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "alpha"), NULL) : 0); //default: 0 FDTDsimulation->alpha1 = (lookupValue(FDTDsimulation->parameters_key_value_pair, "alpha1") ? \ strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "alpha1"), NULL) : 0); //default: 0 FDTDsimulation->alpha2 = (lookupValue(FDTDsimulation->parameters_key_value_pair, "alpha2") ? \ strtod(lookupValue(FDTDsimulation->parameters_key_value_pair, "alpha2"), NULL) : 0); //default: 0 FDTDsimulation->Tstep = (lookupValue(FDTDsimulation->parameters_key_value_pair, "Tstep") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "Tstep")) : 0); //default: 0 FDTDsimulation->Nth = (lookupValue(FDTDsimulation->parameters_key_value_pair, "Nth") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "Nth")) : 1); //default: 1 FDTDsimulation->measure_NM = (lookupValue(FDTDsimulation->parameters_key_value_pair, "measure_NM") ? \ atoi(lookupValue(FDTDsimulation->parameters_key_value_pair, "measure_NM")) : 0); //default: off W = I*FDTDsimulation->w0 + 0.5*FDTDsimulation->Gamma; //declared in main.c //check the validity of parameters sanity_check(FDTDsimulation); #ifdef __FDTD_OPENMP_SUPPORT__ initialize_OpenMP_team(FDTDsimulation); #endif //calculate the normalization constant if(FDTDsimulation->init_cond==3) calculate_normalization_const(FDTDsimulation); //initialize arrays prepare_qubit_wavefunction(FDTDsimulation); initial_condition(FDTDsimulation); boundary_condition(FDTDsimulation); initialize_psi(FDTDsimulation); //save memory free_initial_boundary_conditions(FDTDsimulation); return FDTDsimulation; } void print_initial_condition(grid * simulation) { printf("t=0 "); for(int i=0; i<simulation->psit0_size; i++) printf("%.2f+%.2fI ", creal(simulation->psit0[i]), cimag(simulation->psit0[i])); printf("\n "); for(int i=-simulation->Nx; i<=simulation->Nx; i++) printf("x=%.2f ", i*simulation->Delta); printf("\n"); } void print_boundary_condition(grid * simulation) { for(int j=simulation->Ny-1; j>=0; j--) { printf(" t = %f\n", j*simulation->Delta); for(int i=0; i<simulation->psix0_x_size; i++) { const char * c; if(cimag(simulation->psi[j][i])<0) { c = ""; } else { c = "+"; } printf("x=%.3f: %.7f%s%.7fI\n", -(simulation->Nx+simulation->nx+1-i)*simulation->Delta, \ creal(simulation->psi[j][i]), c, cimag(simulation->psi[j][i])); } printf("\n"); } } void print_psi(grid * simulation) { for(int j=simulation->Ny-1; j>=0; j--) { printf(" t = %f\n", j*simulation->Delta); for(int i=0; i<simulation->Ntotal; i++) { const char * c; if(cimag(simulation->psi[j][i])<0) { c = ""; } else { c = "+"; } //char c[] = (cimag(simulation->psi[j][i])<0?" ":"+"); printf("x=%.3f: %.7f%s%.7fI\n", -(simulation->Nx+simulation->nx+1-i)*simulation->Delta, \ creal(simulation->psi[j][i]), c, cimag(simulation->psi[j][i])); } printf("\n"); } } //this function stores the computed wavefunction into a file; //the third argument "part" can be any function converting a //double complex to a double, e.g., creal, cimag, cabs, etc. void save_psi(grid * simulation, const char * filename, double (*part)(double complex)) { char * str = strdup(filename); str = realloc(str, (strlen(filename)+10)*sizeof(char) ); if(part == &creal) strcat(str, ".re.out"); else if(part == &cimag) strcat(str, ".im.out"); else if(part == &cabs) strcat(str, ".abs.out"); else { fprintf(stderr, "%s: Warning: default filename is used.\n", __func__); strcat(str, ".out"); } FILE * f = fopen(str, "w"); for(int j=0; j<simulation->Ny; j+=(simulation->Tstep+1)) { for(int i=0; i<simulation->Ntotal; i++) { fprintf( f, "%.5g ", part(simulation->psi[j][i]) ); } // for(int i=0; i<simulation->Ntotal; i++) // { // fprintf( f, "%.5f ", part(simulation->psi[j][i]) ); // } fprintf( f, "\n"); } fclose(f); free(str); } //this function stores the computed wavefunction into a binary file //note that each data point is a complex number which takes 16 bytes! void save_psi_binary(grid * simulation, const char * filename) { char * str = strdup(filename); str = realloc(str, (strlen(filename)+10)*sizeof(char) ); strcat(str, ".bin"); FILE * f = fopen(str, "wb"); if(!f) { fprintf(stderr, "%s: file cannot be created!", __func__); exit(EXIT_FAILURE); } size_t array_size = simulation->Ntotal - simulation->minus_a_index; for(int j=0; j<simulation->Ny; j+=(simulation->Tstep+1)) { fwrite((simulation->psi[j] + simulation->minus_a_index), sizeof(double complex), array_size, f); } fclose(f); free(str); } //this function computes the two-photon wavefunction on the fly and //then writes to a file, so no extra memory is allocated; //the third argument "part" can be any function converting a //complex to a double, e.g., creal, cimag, cabs, etc. void save_chi(grid * simulation, const char * filename, double (*part)(double complex)) { char * str = strdup(filename); str = realloc(str, (strlen(filename)+15)*sizeof(char) ); if(part == &creal) strcat(str, ".re_chi.out"); else if(part == &cimag) strcat(str, ".im_chi.out"); else if(part == &cabs) strcat(str, ".abs_chi.out"); else { fprintf(stderr, "%s: Warning: default filename is used.\n", __func__); strcat(str, ".chi.out"); } FILE * f = fopen(str, "w"); //compute chi(a+Delta, a+Delta+tau, t) with tau=i*Delta and t=j*Delta: //to make all terms in chi well-defined requires 0 <= i <= Nx-nx/2. // //Update: To access transient dynamics for two photons, j now starts from 0 instead of minus_a_index (=Nx+nx/2+1) // //(In the previous version, j >= simulation->minus_a_index in order to let signal from the 1st qubit reach the boundary; //put it differently, one cannot take data before the first light cone intersects with the boundary x=Nx*Delta.) for(int j=0; j<=simulation->Ny; j+=(simulation->Tstep+1)) { for(int i=0; i<=simulation->Nx-simulation->nx/2; i++) { double complex chi = 0; double complex temp = 0; if(simulation->init_cond == 1 || simulation->init_cond == 3) chi += two_photon_input(simulation->nx/2+1-j, simulation->nx/2+1+i-j, simulation); if( j>=(simulation->nx+i+1) ) temp += simulation->psi[j-(simulation->nx+i+1)][simulation->minus_a_index-i]; if( j>=(i+1) ) temp -= simulation->psi[j-(i+1)][simulation->plus_a_index-i]; if( j>=(simulation->nx+1) ) temp += simulation->psi[j-(simulation->nx+1)][simulation->minus_a_index+i]; if( j>=1 ) temp -= simulation->psi[j-1][simulation->plus_a_index+i]; chi -= sqrt(simulation->Gamma)/2.0 * temp; fprintf( f, "%.5g ", part(chi) ); } fprintf( f, "\n"); } fclose(f); free(str); } //this function computes the two-photon wavefunction as a 2D map, // // \chi (x1, x2, T), //T is taken such that the wavefronts are aligned at the boundary // //the calculation of which is done on the fly and then writes to a file, //so no extra memory is allocated; the third argument "part" can be any //function converting a complex to a double, e.g., creal, cimag, cabs, etc. //STILL UNDER CONSTRUCTION!!!!!! void save_chi_map(grid * simulation, const char * filename, double (*part)(double complex)) { char * str = strdup(filename); str = realloc(str, (strlen(filename)+19)*sizeof(char) ); if(part == &creal) strcat(str, ".re_chi_map.out"); else if(part == &cimag) strcat(str, ".im_chi_map.out"); else if(part == &cabs) strcat(str, ".abs_chi_map.out"); else { fprintf(stderr, "%s: Warning: default filename is used.\n", __func__); strcat(str, ".chi_map.out"); } FILE * f = fopen(str, "w"); //determine the map size //int j = simulation->Ny-1; //the time slice ////int j = (simulation->Ny-1 < simulation->Nx - simulation->nx/2 ? simulation->Ny-1 : simulation->Nx - simulation->nx/2); //the time slice //int temp_1 = (int)ceil(simulation->Nx/2.0-simulation->nx/4.0); //int temp_2 = j - simulation->nx/2; //int L = (temp_1<temp_2 ? temp_1 : temp_2); int j = (int)ceil(simulation->Nx/2.0-3*simulation->nx/4.0); int L = (int)ceil(simulation->Nx/2.0-simulation->nx/4.0); for(int i=0; i<=L; i+=simulation->Tstep+1) //change L to largest integer multiple of Tstep+1 for nonzero Tstep { if(i+simulation->Tstep+1>L) { L=i; break; } } printf("FDTD: %s: the box is of dimension 2L*2L with L=%i.\n", __func__, L); //compute chi(x1, x2, t) //be careful: x1 & x2 here are array indices!!! for(int x2=simulation->origin_index-L; x2<=simulation->origin_index+L; x2+=(simulation->Tstep+1)) { for(int x1=simulation->origin_index-L; x1<=simulation->origin_index+L; x1+=(simulation->Tstep+1)) { fprintf( f, "%.5g ", part(chi(j, x1, x2, simulation)) ); } fprintf( f, "\n"); } fclose(f); free(str); } void print_grid(grid * simulation) { printf("nx = %d\n", simulation->nx); printf("Nx = %d\n", simulation->Nx); printf("Ntotal = %d\n", simulation->Ntotal); printf("Ny = %d\n", simulation->Ny); printf("Delta = %.3f\n", simulation->Delta); printf("k = %.3f\n", simulation->k); printf("w0 = %.3f\n", simulation->w0); printf("Gamma = %.3f\n", simulation->Gamma); printf("Lx = %.3f\n", simulation->Lx); printf("Ly = %.3f\n", simulation->Ly); for(int j=simulation->Ny-1; j>=0; j--) { for(int i=0; i<simulation->Ntotal; i++) { printf("%.2f+%.2fI ", creal(simulation->psi[j][i]), cimag(simulation->psi[j][i])); } printf("\n"); } } void save_psi_square_integral(grid * simulation, const char * filename) { char * str = strdup(filename); str = realloc(str, (strlen(filename)+18)*sizeof(char) ); strcat(str, ".psi_square.out"); int Tmax = (simulation->Ny-1 < simulation->Nx - simulation->nx/2 ? simulation->Ny-1 : simulation->Nx - simulation->nx/2); FILE * f = fopen(str, "w"); double * result = malloc(Tmax *sizeof(*result)); if(!result) { fprintf(stderr, "rare event: malloc fails in %s, save the result serially...\n", __func__); for(int j=0; j<Tmax; j++) fprintf( f, "%.10g\n", psi_square_integral(j, simulation) ); } else { #pragma omp parallel for for(int j=0; j<Tmax; j++) result[j] = psi_square_integral(j, simulation); for(int j=0; j<Tmax; j++) fprintf( f, "%.10g\n", result[j] ); } free(result); fclose(f); free(str); } //check the normalization factor in the two-excitation sector //\int dx |\psi(x,t)|^2 + \iint dx1 dx2 |\chi(x1, x2, t)|^2 = 1 should hold for all time t void check_normalization(grid * simulation) { //determine the map size int L = (int)ceil(simulation->Nx/2.0-simulation->nx/4.0); int j = L-simulation->nx/2; //after this time the two photons will go outside of box printf("FDTD: %s: the box is of dimension 2L*2L with L=%i.\n", __func__, L); printf("FDTD: %s: perform the check at t=%i Delta...\n", __func__, j); double abs_psi_square = psi_square_integral(j, simulation); double abs_chi_square = 0; //compute \iint_{-L}^{+L} dx1 dx2 |chi(x1, x2, t=j*Delta)|^2 //be careful: x1 & x2 here are array indices!!! #pragma omp parallel for collapse(2), reduction(+:abs_chi_square) for(int x2=simulation->origin_index-L; x2<=simulation->origin_index+L; x2++) { for(int x1=simulation->origin_index-L; x1<=simulation->origin_index+L; x1++) { double abs_chi = cabs(chi(j, x1, x2, simulation)); double trapezoidal_2D = 1.0; if(x1==simulation->origin_index-L || x1==simulation->origin_index+L) trapezoidal_2D *= 0.5; if(x2==simulation->origin_index-L || x2==simulation->origin_index+L) trapezoidal_2D *= 0.5; abs_chi_square += trapezoidal_2D*abs_chi*abs_chi; } } abs_chi_square *= simulation->Delta * simulation->Delta; printf("FDTD: %s: the 1-photon part is %.5f, and the 2-photon part is %.5f,\n", __func__, abs_psi_square, abs_chi_square); printf("FDTD: %s: so the normalization factor (sum of them) is %.5f.\n", __func__, abs_psi_square+abs_chi_square); if(fabs(1.0-abs_psi_square-abs_chi_square)>0.01) // <1% error is acceptable fprintf(stderr, "FDTD: %s: *** WARNING: normalization factor deviates too much, the result may not be faithful ***\n", __func__); } //EXPERIMENTAL!!!! void save_BIC(grid * simulation, const char * filename) { char * str = strdup(filename); str = realloc(str, (strlen(filename)+11)*sizeof(char) ); strcat(str, ".BIC.out"); int Tmax = 0; if(2*simulation->Nx >= 3*simulation->nx) Tmax = (simulation->Ny-1 < simulation->Nx - 3*simulation->nx/2 ? simulation->Ny-1 : simulation->Nx - 3*simulation->nx/2); //Tmax = simulation->Nx - 3*simulation->nx/2; else { fprintf(stderr, "FDTD: %s: 2Nx>=3nx is not satisfied, skip this function.\n", __func__); return; } FILE * f = fopen(str, "w"); //#pragma omp parallel for //each function call is parallelized, so don't parallelize this loop for(int j=0; j<Tmax; j+=simulation->Tstep+1) { double psi_part=0, chi_part=0; psi_part = psi_square_integral(j, simulation); chi_part = chi_square_double_integral(j, simulation); fprintf( f, "%.10g\n", psi_part+chi_part ); } fclose(f); free(str); } //calculate the photon intensity <a^\dagger(x)a(x)> with x in [-L, L] void save_photon_intensity(grid * simulation, const char * filename) { char * str1 = strdup(filename); char * str2 = strdup(filename); str1 = realloc(str1, (strlen(filename)+22)*sizeof(char) ); str2 = realloc(str2, (strlen(filename)+23)*sizeof(char) ); strcat(str1, ".intensity_diag.out"); strcat(str2, ".intensity_cross.out"); FILE * f1 = fopen(str1, "w"); FILE * f2 = fopen(str2, "w"); //double * chi_part = malloc((L+simulation->nx+1)*sizeof(*chi_part)); //if(!chi_part) //{ // fprintf(stderr, "FDTD: %s: malloc fails, skip this function...\n", __func__); // return; //} //integration limit //int L = simulation->Nx - simulation->nx; int L = (int)ceil(simulation->Nx/2.0-simulation->nx/4.0); for(int i=0; i<=L; i+=simulation->Tstep+1) //change L to largest integer multiple of Tstep+1 for nonzero Tstep { if(i+simulation->Tstep+1>L) { L=i; break; } } printf("FDTD: %s: the 1D box is of size 2L with L=%i.\n", __func__, L); //take the last time slice at which \chi is meaningful; in line with save_chi_map int j = (int)ceil(simulation->Nx/2.0-3*simulation->nx/4.0); //int j = 0; //if(2*simulation->Nx >= 3*simulation->nx) // j = (simulation->Ny-1 < simulation->Nx - 3*simulation->nx/2 ? simulation->Ny-1 : simulation->Nx - 3*simulation->nx/2); //else //{ // fprintf(stderr, "FDTD: %s: 2Nx>=3nx is not satisfied, skip this function.\n", __func__); // return; //} //chi_square_single_integral is parallelized, so don't parallelize this loop for(int i=simulation->origin_index-L; i<simulation->origin_index+L; i+=(simulation->Tstep+1)) { double complex psi = simulation->psi[j][i]; fprintf(f1, "%.10g\n", cabs(psi)*cabs(psi) + chi_square_single_integral(j, i, simulation)); double complex psi_m = simulation->psi[j][2*simulation->origin_index-i]; double complex temp = conj(psi)*psi_m + chi_square_single_integral_mirrored(j, i, simulation); fprintf(f2, "%.10g + %.10g *I\n", creal(temp), cimag(temp)); } //free(chi_part); fclose(f1); fclose(f2); free(str1); free(str2); }
print.c
// RUN: %libomp-tool -DFIRST_TOOL -o %t.first.tool.so %s && \ // RUN: %libomp-tool -DSECOND_TOOL -o %t.second.tool.so %s && \ // RUN: %libomp-compile && \ // RUN: env OMP_TOOL_LIBRARIES=%t.first.tool.so \ // RUN: PRINT_TOOL_LIBRARIES=%t.second.tool.so \ // RUN: %libomp-run | %sort-threads | FileCheck %s // For GCC we don't get an event for master, // see runtime/test/ompt/sycnchronization/master.c // UNSUPPORTED: gcc #if defined(FIRST_TOOL) #include "first-tool.h" #elif defined(SECOND_TOOL) #include "second-tool.h" #else /* APP */ #include "../ompt-signal.h" #include "omp.h" #include <stdio.h> int main() { int x, s = 0; #pragma omp parallel num_threads(2) shared(s) { #pragma omp master { #pragma omp task shared(s) { omp_control_tool(5, 1, NULL); OMPT_SIGNAL(s); } } if (omp_get_thread_num() == 1) OMPT_WAIT(s, 1); } return 0; } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}0: NULL_POINTER=[[NULL]] // CHECK: {{^}}0: ompt_event_runtime_shutdown // CHECK: {{^}}0: ompt_event_runtime_shutdown // CHECK: {{^}}[[_1ST_MSTR_TID:[0-9]+]]: _first_tool: ompt_event_thread_begin: // CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[_1ST_MSTR_TID]] // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_initial_task_begin: // CHECK-SAME: parallel_id=[[_FIRST_INIT_PARALLEL_ID:[0-9]+]], // CHECK-SAME: task_id=[[_FIRST_INITIAL_TASK_ID:[0-9]+]], // CHECK-SAME: actual_parallelism=1, index=1, flags=1 // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_parallel_begin: // CHECK-SAME: parent_task_id=[[_FIRST_INITIAL_TASK_ID]], // CHECK-SAME: parent_task_frame.exit=(nil), // CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}, // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID:[0-9]+]], // CHECK-SAME: requested_team_size=2, codeptr_ra={{0x[0-f]+}}, invoker // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_implicit_task_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID:[0-9]+]], team_size=2, // CHECK-SAME: thread_num=0 // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_masked_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_task_create: // CHECK-SAME: parent_task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: parent_task_frame.exit={{0x[0-f]+}}, // CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}, // CHECK-SAME: new_task_id=[[_FIRST_EXPLICIT_TASK_ID:[0-9]+]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit=4, // CHECK-SAME: has_dependences=no // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_masked_end: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_barrier_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_wait_barrier_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_task_schedule: // CHECK-SAME: first_task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: second_task_id=[[_FIRST_EXPLICIT_TASK_ID]], // CHECK-SAME: prior_task_status=ompt_task_switch=7 // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_control_tool: // CHECK-SAME: command=5, modifier=1, arg=(nil), codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: task level 0: // CHECK-SAME: task_id=[[_FIRST_EXPLICIT_TASK_ID]] // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: task level 1: // CHECK-SAME: task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]] // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: task level 2: // CHECK-SAME: task_id=[[_FIRST_INITIAL_TASK_ID]] // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: parallel level 0: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]] // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: parallel level 1: // CHECK-SAME: parallel_id={{[0-9]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_task_schedule: // CHECK-SAME: first_task_id=[[_FIRST_EXPLICIT_TASK_ID]], // CHECK-SAME: second_task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: prior_task_status=ompt_task_complete=1 // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_task_end: // CHECK-SAME: task_id=[[_FIRST_EXPLICIT_TASK_ID]] // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_wait_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_implicit_task_end: // CHECK-SAME: parallel_id=0, task_id=[[_FIRST_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: team_size=2, thread_num=0 // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_parallel_end: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_INITIAL_TASK_ID]], invoker // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_1ST_MSTR_TID]]: _first_tool: ompt_event_thread_end: // CHECK-SAME: thread_id=[[_1ST_MSTR_TID]] // CHECK: {{^}}[[_2ND_MSTR_TID:[0-9]+]]: second_tool: ompt_event_thread_begin: // CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[_2ND_MSTR_TID]] // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_initial_task_begin: // CHECK-SAME: parallel_id=[[SECOND_INIT_PARALLEL_ID:[0-9]+]], // CHECK-SAME: task_id=[[SECOND_INITIAL_TASK_ID:[0-9]+]], // CHECK-SAME: actual_parallelism=1, index=1, flags=1 // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_parallel_begin: // CHECK-SAME: parent_task_id=[[SECOND_INITIAL_TASK_ID]], // CHECK-SAME: parent_task_frame.exit=(nil), // CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}, // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID:[0-9]+]], // CHECK-SAME: requested_team_size=2, codeptr_ra={{0x[0-f]+}}, invoker // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_implicit_task_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID:[0-9]+]], team_size=2, // CHECK-SAME: thread_num=0 // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_masked_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_task_create: // CHECK-SAME: parent_task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: parent_task_frame.exit={{0x[0-f]+}}, // CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}, // CHECK-SAME: new_task_id=[[SECOND_EXPLICIT_TASK_ID:[0-9]+]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit=4, // CHECK-SAME: has_dependences=no // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_masked_end: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_barrier_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_wait_barrier_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_task_schedule: // CHECK-SAME: first_task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: second_task_id=[[SECOND_EXPLICIT_TASK_ID]], // CHECK-SAME: prior_task_status=ompt_task_switch=7 // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_control_tool: // CHECK-SAME: command=5, modifier=1, arg=(nil), codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: task level 0: // CHECK-SAME: task_id=[[SECOND_EXPLICIT_TASK_ID]] // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: task level 1: // CHECK-SAME: task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]] // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: task level 2: // CHECK-SAME: task_id=[[SECOND_INITIAL_TASK_ID]] // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: parallel level 0: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]] // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: parallel level 1: // CHECK-SAME: parallel_id={{[0-9]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_task_schedule: // CHECK-SAME: first_task_id=[[SECOND_EXPLICIT_TASK_ID]], // CHECK-SAME: second_task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: prior_task_status=ompt_task_complete=1 // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_task_end: // CHECK-SAME: task_id=[[SECOND_EXPLICIT_TASK_ID]] // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_wait_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_implicit_task_end: // CHECK-SAME: parallel_id=0, task_id=[[SECOND_MASTER_IMPLICIT_TASK_ID]], // CHECK-SAME: team_size=2, thread_num=0 // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_parallel_end: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_INITIAL_TASK_ID]], invoker // CHECK-SAME: codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[_2ND_MSTR_TID]]: second_tool: ompt_event_thread_end: // CHECK-SAME: thread_id=[[_2ND_MSTR_TID]] // CHECK: {{^}}[[_1ST_WRKR_TID:[0-9]+]]: _first_tool: ompt_event_thread_begin: // CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[_1ST_WRKR_TID]] // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_implicit_task_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_WORKER_IMPLICIT_TASK_ID:[0-9]+]], team_size=2, // CHECK-SAME: thread_num=1 // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_barrier_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_WORKER_IMPLICIT_TASK_ID]], codeptr_ra=(nil) // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_wait_barrier_begin: // CHECK-SAME: parallel_id=[[_FIRST_PARALLEL_ID]], // CHECK-SAME: task_id=[[_FIRST_WORKER_IMPLICIT_TASK_ID]], codeptr_ra=(nil) // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_wait_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[_FIRST_WORKER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[_FIRST_WORKER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_implicit_task_end: // CHECK-SAME: parallel_id=0, task_id=[[_FIRST_WORKER_IMPLICIT_TASK_ID]], // CHECK-SAME: team_size=0, thread_num=1 // CHECK: {{^}}[[_1ST_WRKR_TID]]: _first_tool: ompt_event_thread_end: // CHECK-SAME: thread_id=[[_1ST_WRKR_TID]] // CHECK: {{^}}[[_2ND_WRKR_TID:[0-9]+]]: second_tool: ompt_event_thread_begin: // CHECK-SAME: thread_type=ompt_thread_worker=2, // CHECK-SAME: thread_id=[[_2ND_WRKR_TID]] // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_implicit_task_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_WORKER_IMPLICIT_TASK_ID:[0-9]+]], // CHECK-SAME: team_size=2, thread_num=1 // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_barrier_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_WORKER_IMPLICIT_TASK_ID]], codeptr_ra=(nil) // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_wait_barrier_begin: // CHECK-SAME: parallel_id=[[SECOND_PARALLEL_ID]], // CHECK-SAME: task_id=[[SECOND_WORKER_IMPLICIT_TASK_ID]], codeptr_ra=(nil) // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_wait_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[SECOND_WORKER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_barrier_end: // CHECK-SAME: parallel_id=0, task_id=[[SECOND_WORKER_IMPLICIT_TASK_ID]], // CHECK-SAME: codeptr_ra=(nil) // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_implicit_task_end: // CHECK-SAME: parallel_id=0, task_id=[[SECOND_WORKER_IMPLICIT_TASK_ID]], // CHECK-SAME: team_size=0, thread_num=1 // CHECK: {{^}}[[_2ND_WRKR_TID]]: second_tool: ompt_event_thread_end: // CHECK-SAME: thread_id=[[_2ND_WRKR_TID]] #endif /* APP */
GrB_init.c
//------------------------------------------------------------------------------ // GrB_init: initialize GraphBLAS //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // GrB_init must called before any other GraphBLAS operation. GrB_finalize // must be called as the last GraphBLAS operation. // GrB_init defines the mode that GraphBLAS will use: blocking or // non-blocking. With blocking mode, all operations finish before returning to // the user application. With non-blocking mode, operations can be left // pending, and are computed only when needed. // The GrB_wait function forces all pending operations to complete. Blocking // mode is as if the GrB_wait operation is called whenever a GraphBLAS // operation returns to the user. // The non-blocking mode can have side effects if user-defined functions have // side effects or if they rely on global variables, which are not under the // control of GraphBLAS. Suppose the user creates a user-defined operator that // accesses a global variable. That operator is then used in a GraphBLAS // operation, which is left pending. If the user then changes the global // variable, the pending operations will be eventually computed with this // different value. // Worse yet, a user-defined operator can be freed before it is needed to // finish a pending operation. To avoid this, call GrB_wait before modifying // any global variables relied upon by user-defined operators and before // freeing any user-defined types, operators, monoids, or semirings. #include "GB.h" //------------------------------------------------------------------------------ // Thread local storage //------------------------------------------------------------------------------ // Thread local storage is used to to record the details of the last error // encountered for GrB_error. If the user application is multi-threaded, each // thread that calls GraphBLAS needs its own private copy of this report. #if defined (USER_POSIX_THREADS) // thread-local storage for POSIX THREADS pthread_key_t GB_thread_local_report ; #elif defined (USER_WINDOWS_THREADS) // for user applications that use Windows threads: #error Windows threading not yet supported #elif defined (USER_ANSI_THREADS) // for user applications that use ANSI C11 threads: // (this should work per the ANSI C11 specification but is not yet supported) _Thread_local char GB_thread_local_report [GB_RLEN+1] = "" ; #else // USER_OPENMP_THREADS, or USER_NO_THREADS // OpenMP user threads, or no user threads: this is the default #pragma omp threadprivate (GB_thread_local_report) char GB_thread_local_report [GB_RLEN+1] = "" ; #endif //------------------------------------------------------------------------------ // All Global storage is declared and initialized here //------------------------------------------------------------------------------ // If the user creates threads that work on GraphBLAS matrices, then all of // those threads must share the same matrix queue, and the same mode. GB_Global_struct GB_Global = { // queued matrices with work to do .queue_head = NULL, // pointer to first queued matrix // GraphBLAS mode .mode = GrB_NONBLOCKING, // default is nonblocking // initialization flag .GrB_init_called = false, // GrB_init has not yet been called // default format .hyper_ratio = GB_HYPER_DEFAULT, .is_csc = (GB_FORMAT_DEFAULT != GxB_BY_ROW) // default is GxB_BY_ROW #ifdef GB_MALLOC_TRACKING // malloc tracking, for testing, statistics, and debugging only , .nmalloc = 0 // memory block counter , .malloc_debug = false // do not test memory handling , .malloc_debug_count = 0 // counter for testing memory handling , .inuse = 0 // memory space current in use , .maxused = 0 // high water memory usage #endif } ; //------------------------------------------------------------------------------ // GrB_init //------------------------------------------------------------------------------ // If GraphBLAS is used by multiple user threads, only one can call GrB_init. GrB_Info GrB_init // start up GraphBLAS ( const GrB_Mode mode // blocking or non-blocking mode ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE ("GrB_init (mode)") ; //-------------------------------------------------------------------------- // create the global queue and thread-local storage //-------------------------------------------------------------------------- GB_CRITICAL (GB_queue_create ( )) ; //-------------------------------------------------------------------------- // initialize the global queue //-------------------------------------------------------------------------- // Only one thread should initialize these settings. If multiple threads // call GrB_init, only the first thread does this work. if (! (mode == GrB_BLOCKING || mode == GrB_NONBLOCKING)) { // mode is invalid; also report the error for GrB_error. return (GB_ERROR (GrB_INVALID_VALUE, (GB_LOG, "Unknown mode: %d; must be %d (GrB_NONBLOCKING) or %d" " (GrB_BLOCKING)", (int) mode, (int) GrB_NONBLOCKING, (int) GrB_BLOCKING))) ; } bool I_was_first ; GB_CRITICAL (GB_queue_init (mode, &I_was_first)) ; if (! I_was_first) { return (GB_ERROR (GrB_INVALID_VALUE, (GB_LOG, "GrB_init must not be called twice"))) ; } //-------------------------------------------------------------------------- // set the global default format //-------------------------------------------------------------------------- // set the default hypersparsity ratio and CSR/CSC format; any thread // can do this later as well, so there is no race condition danger. GB_Global.hyper_ratio = GB_HYPER_DEFAULT ; GB_Global.is_csc = (GB_FORMAT_DEFAULT != GxB_BY_ROW) ; //-------------------------------------------------------------------------- // initialize malloc tracking (testing and debugging only) //-------------------------------------------------------------------------- #ifdef GB_MALLOC_TRACKING // malloc tracking. This is only for statistics and development. { GB_Global.nmalloc = 0 ; GB_Global.malloc_debug = false ; GB_Global.malloc_debug_count = 0 ; GB_Global.inuse = 0 ; GB_Global.maxused = 0 ; } #endif //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- return (GrB_SUCCESS) ; }
6316.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4096x4096. */ #include "convolution-2d.h" /* Array initialization. */ static void init_array (int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { // printf("Initializing Array\n"); int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) (i + j) / nj); } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nj, DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]); if ((i * NJ + 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_conv2d(int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; #pragma scop #pragma omp target teams distribute parallel for schedule(static) private(j) for (i = 1; i < _PB_NI - 1; ++i) { #pragma omp target teams distribute parallel for num_threads(2) dist_schedule(static, 1) for (j = 1; j < _PB_NJ - 1; ++j) { B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1] + -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1] + 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1]; } } #pragma endscop // printf("Kernal computation complete !!\n"); } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj); /* Initialize array(s). */ init_array (ni, nj, POLYBENCH_ARRAY(A)); /* Start timer. */ //polybench_start_instruments; polybench_timer_start(); /* Run kernel. */ kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B)); /* Stop and print timer. */ polybench_timer_stop(); polybench_timer_print(); //polybench_stop_instruments; //polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); return 0; }
icd3d.c
#include <math.h> #include <stdio.h> #include <time.h> #include <omp.h> #include "icd3d.h" #include "allocate.h" void ICDStep3DCone(struct Sino *sino, struct Image *img, struct SysMatrix *A, struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams, struct ReconAux *reconAux) { /** * Updates one voxel. Voxel change is stored in icdInfo->Delta_xj. */ /** * Compute forward model term of theta1 and theta2: * * theta1_f = -e^t W A_{*,j} * theta2_f = A_{*,j}^t W A _{*,j} */ computeTheta1Theta2ForwardTerm(sino, A, icdInfo, reconParams); /** * Compute prior model term of theta1 and theta2: * */ if(reconParams->priorWeight_QGGMRF >= 0) computeTheta1Theta2PriorTermQGGMRF(icdInfo, reconParams); if(reconParams->priorWeight_proxMap >= 0) computeTheta1Theta2PriorTermProxMap(icdInfo, reconParams); computeDeltaXjAndUpdate(icdInfo, reconParams, img, reconAux); updateErrorSinogram(sino, A, icdInfo); } void prepareICDInfo(long int j_x, long int j_y, long int j_z, struct ICDInfo3DCone *icdInfo, struct Image *img, struct ReconAux *reconAux, struct ReconParams *reconParams) { icdInfo->old_xj = img->vox[index_3D(j_x,j_y,j_z,img->params.N_y,img->params.N_z)]; if(reconParams->priorWeight_proxMap >= 0) icdInfo->proxMapInput_j = img->proxMapInput[index_3D(j_x,j_y,j_z,img->params.N_y,img->params.N_z)]; icdInfo->j_x = j_x; icdInfo->j_y = j_y; icdInfo->j_z = j_z; extractNeighbors(icdInfo, img, reconParams); icdInfo->theta1_f = 0; icdInfo->theta2_f = 0; icdInfo->theta1_p_QGGMRF = 0; icdInfo->theta2_p_QGGMRF = 0; icdInfo->theta1_p_proxMap = 0; icdInfo->theta2_p_proxMap = 0; } void extractNeighbors(struct ICDInfo3DCone *icdInfo, struct Image *img, struct ReconParams *reconParams) { long int j_x, j_y, j_z; long int N_x, N_y, N_z; long int PLx, MIx; long int PLy, MIy; long int PLz, MIz; j_x = icdInfo->j_x; j_y = icdInfo->j_y; j_z = icdInfo->j_z; N_x = img->params.N_x; N_y = img->params.N_y; N_z = img->params.N_z; /** * Use reflective boundary conditions to find the indices of the neighbors */ PLx = (j_x == N_x-1) ? N_x-2 : j_x+1; PLy = (j_y == N_y-1) ? N_y-2 : j_y+1; PLz = (j_z == N_z-1) ? N_z-2 : j_z+1; MIx = (j_x == 0) ? 1 : j_x-1; MIy = (j_y == 0) ? 1 : j_y-1; MIz = (j_z == 0) ? 1 : j_z-1; /** * Compute the neighbor pixel values * * Note that all the pixels of the first half of the arrays * have a corresponding pixel in the second half of the array * that is on the spacially opposite side. * Example: neighborsFace[0] opposite of neighborsFace[3] */ if (reconParams->bFace>=0) { /* Face Neighbors (primal) */ //icdInfo->neighborsFace[0] = img->vox[PLx][j_y][j_z]; //icdInfo->neighborsFace[1] = img->vox[j_x][PLy][j_z]; //icdInfo->neighborsFace[2] = img->vox[j_x][j_y][PLz]; icdInfo->neighborsFace[0] = img->vox[index_3D(PLx,j_y,j_z,img->params.N_y,img->params.N_z)]; icdInfo->neighborsFace[1] = img->vox[index_3D(j_x,PLy,j_z,img->params.N_y,img->params.N_z)]; icdInfo->neighborsFace[2] = img->vox[index_3D(j_x,j_y,PLz,img->params.N_y,img->params.N_z)]; /* Face Neighbors (opposite) */ //icdInfo->neighborsFace[3] = img->vox[MIx][j_y][j_z]; //icdInfo->neighborsFace[4] = img->vox[j_x][MIy][j_z]; //icdInfo->neighborsFace[5] = img->vox[j_x][j_y][MIz]; icdInfo->neighborsFace[3] = img->vox[index_3D(MIx,j_y,j_z,img->params.N_y,img->params.N_z)]; icdInfo->neighborsFace[4] = img->vox[index_3D(j_x,MIy,j_z,img->params.N_y,img->params.N_z)]; icdInfo->neighborsFace[5] = img->vox[index_3D(j_x,j_y,MIz,img->params.N_y,img->params.N_z)]; } if (reconParams->bEdge>=0) { /* Edge Neighbors (primal) */ //icdInfo->neighborsEdge[ 0] = img->vox[j_x][PLy][PLz]; //icdInfo->neighborsEdge[ 1] = img->vox[j_x][PLy][MIz]; //icdInfo->neighborsEdge[ 2] = img->vox[PLx][j_y][PLz]; //icdInfo->neighborsEdge[ 3] = img->vox[PLx][j_y][MIz]; //icdInfo->neighborsEdge[ 4] = img->vox[PLx][PLy][j_z]; //icdInfo->neighborsEdge[ 5] = img->vox[PLx][MIy][j_z]; icdInfo->neighborsEdge[0] = img->vox[index_3D(j_x,PLy,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[1] = img->vox[index_3D(j_x,PLy,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[2] = img->vox[index_3D(PLx,j_y,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[3] = img->vox[index_3D(PLx,j_y,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[4] = img->vox[index_3D(PLx,PLy,j_z,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[5] = img->vox[index_3D(PLx,MIy,j_z,img->params.N_y,img->params.N_z)]; /* Edge Neighbors (opposite) */ //icdInfo->neighborsEdge[ 6] = img->vox[j_x][MIy][MIz]; //icdInfo->neighborsEdge[ 7] = img->vox[j_x][MIy][PLz]; //icdInfo->neighborsEdge[ 8] = img->vox[MIx][j_y][MIz]; //icdInfo->neighborsEdge[ 9] = img->vox[MIx][j_y][PLz]; //icdInfo->neighborsEdge[10] = img->vox[MIx][MIy][j_z]; //icdInfo->neighborsEdge[11] = img->vox[MIx][PLy][j_z]; icdInfo->neighborsEdge[6] = img->vox[index_3D(j_x,MIy,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[7] = img->vox[index_3D(j_x,MIy,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[8] = img->vox[index_3D(MIx,j_y,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[9] = img->vox[index_3D(MIx,j_y,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[10] = img->vox[index_3D(MIx,MIy,j_z,img->params.N_y,img->params.N_z)]; icdInfo->neighborsEdge[11] = img->vox[index_3D(MIx,PLy,j_z,img->params.N_y,img->params.N_z)]; } if (reconParams->bVertex>=0) { /* Vertex Neighbors (primal) */ //icdInfo->neighborsVertex[0] = img->vox[PLx][PLy][PLz]; //icdInfo->neighborsVertex[1] = img->vox[PLx][PLy][MIz]; //icdInfo->neighborsVertex[2] = img->vox[PLx][MIy][PLz]; //icdInfo->neighborsVertex[3] = img->vox[PLx][MIy][MIz]; icdInfo->neighborsVertex[0] = img->vox[index_3D(PLx,PLy,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsVertex[1] = img->vox[index_3D(PLx,PLy,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsVertex[2] = img->vox[index_3D(PLx,MIy,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsVertex[3] = img->vox[index_3D(PLx,MIy,MIz,img->params.N_y,img->params.N_z)]; /* Vertex Neighbors (opposite) */ //icdInfo->neighborsVertex[4] = img->vox[MIx][MIy][MIz]; //icdInfo->neighborsVertex[5] = img->vox[MIx][MIy][PLz]; //icdInfo->neighborsVertex[6] = img->vox[MIx][PLy][MIz]; //icdInfo->neighborsVertex[7] = img->vox[MIx][PLy][PLz]; icdInfo->neighborsVertex[4] = img->vox[index_3D(MIx,MIy,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsVertex[5] = img->vox[index_3D(MIx,MIy,PLz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsVertex[6] = img->vox[index_3D(MIx,PLy,MIz,img->params.N_y,img->params.N_z)]; icdInfo->neighborsVertex[7] = img->vox[index_3D(MIx,PLy,PLz,img->params.N_y,img->params.N_z)]; } } void computeTheta1Theta2ForwardTerm(struct Sino *sino, struct SysMatrix *A, struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams) { /** * Compute forward model term of theta1 and theta2: * * theta1_f = -e^t W A_{*,j} * theta2_f = A_{*,j}^t W A _{*,j} */ long int i_beta, i_v, i_w; long int j_x, j_y, j_z, j_u; float B_ij, A_ij; j_x = icdInfo->j_x; j_y = icdInfo->j_y; j_z = icdInfo->j_z; for (i_beta = 0; i_beta < sino->params.N_beta; ++i_beta) { j_u = A->j_u[j_x][j_y][i_beta]; for (i_v = A->i_vstart[j_x][j_y][i_beta]; i_v < A->i_vstart[j_x][j_y][i_beta]+A->i_vstride[j_x][j_y][i_beta]; ++i_v) { B_ij = A->B_ij_scaler * A->B[j_x][j_y][i_beta*A->i_vstride_max + i_v-A->i_vstart[j_x][j_y][i_beta]]; for (i_w = A->i_wstart[j_u][j_z]; i_w < A->i_wstart[j_u][j_z]+A->i_wstride[j_u][j_z]; ++i_w) { A_ij = B_ij * A->C_ij_scaler * A->C[j_u][j_z*A->i_wstride_max + i_w-A->i_wstart[j_u][j_z]]; icdInfo->theta1_f -= sino->e[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * sino->wgt[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * A_ij; icdInfo->theta2_f += A_ij * sino->wgt[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * A_ij; } } } if(strcmp(reconParams->weightScaler_domain,"spatiallyInvariant") == 0) { icdInfo->theta1_f /= sino->params.weightScaler_value; icdInfo->theta2_f /= sino->params.weightScaler_value; } else { fprintf(stderr, "ERROR in computeTheta1Theta2ForwardTerm: can't recongnize weightScaler_domain.\n"); exit(-1); } } void computeTheta1Theta2PriorTermQGGMRF(struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams) { /** * Compute prior model term of theta1 and theta2: * * theta1_p_QGGMRF = sum 2 b_{j,r} * surrCoeff(x_j - x_r) * (x_j - x_r) * {r E ∂j} * * theta2_p_QGGMRF = sum 2 b_{j,r} * surrCoeff(x_j - x_r) * {r E ∂j} */ int i; float delta, surrogateCoeff; float sum1Face = 0; float sum1Edge = 0; float sum1Vertex = 0; float sum2Face = 0; float sum2Edge = 0; float sum2Vertex = 0; if (reconParams->bFace>=0) { for (i = 0; i < 6; ++i) { delta = icdInfo->old_xj - icdInfo->neighborsFace[i]; surrogateCoeff = surrogateCoeffQGGMRF(delta, reconParams); sum1Face += surrogateCoeff * delta; sum2Face += surrogateCoeff; } } if (reconParams->bEdge>=0) { for (i = 0; i < 12; ++i) { delta = icdInfo->old_xj - icdInfo->neighborsEdge[i]; surrogateCoeff = surrogateCoeffQGGMRF(delta, reconParams); sum1Edge += surrogateCoeff * delta; sum2Edge += surrogateCoeff; } } if (reconParams->bVertex>=0) { for (i = 0; i < 8; ++i) { delta = icdInfo->old_xj - icdInfo->neighborsVertex[i]; surrogateCoeff = surrogateCoeffQGGMRF(delta, reconParams); sum1Vertex += surrogateCoeff * delta; sum2Vertex += surrogateCoeff; } } icdInfo->theta1_p_QGGMRF = 2 * reconParams->bFace * sum1Face + 2 * reconParams->bEdge * sum1Edge + 2 * reconParams->bVertex * sum1Vertex; icdInfo->theta2_p_QGGMRF = 2 * reconParams->bFace * sum2Face + 2 * reconParams->bEdge * sum2Edge + 2 * reconParams->bVertex * sum2Vertex; } void computeTheta1Theta2PriorTermProxMap(struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams) { /** * theta1_p_proxMap = (x_j - ~x_j) / (sigma_lambda^2) * * * theta2_p_proxMap = 1 / (sigma_lambda^2) * */ icdInfo->theta1_p_proxMap = (icdInfo->old_xj - icdInfo->proxMapInput_j) / (reconParams->sigma_lambda * reconParams->sigma_lambda); icdInfo->theta2_p_proxMap = 1.0 / (reconParams->sigma_lambda * reconParams->sigma_lambda); } float surrogateCoeffQGGMRF(float Delta, struct ReconParams *reconParams) { /** * / rho'(Delta) / (2 Delta) if Delta != 0 * surrCoeff(Delta) = { * \ rho''(0) / 2 if Delta = 0 */ float p, q, T, sigmaX, qmp; float num, denom, temp; p = reconParams->p; q = reconParams->q; T = reconParams->T; sigmaX = reconParams->sigmaX; qmp = q - p; if(fabs(Delta) < 1e-5) { /** * rho''(0) 1 * -------- = ----------------- * 2 p sigmaX^q T^(q-p) */ return 1.0 / ( p * pow(sigmaX, q) * pow(T, qmp) ); } else /* Delta != 0 */ { /** * rho'(Delta) |Delta|^(p-2) # (q/p + #) * ----------- = ------------- ------------ * 2 Delta 2 sigmaX^p (1 + #)^2 * * where | Delta |^(q-p) * # = |--------| * |T sigmaX| */ temp = pow(fabs(Delta / (T*sigmaX)), qmp); /* this is the # from above */ num = pow(fabs(Delta), p-2) * temp * (q/p + temp); denom = 2 * pow(sigmaX,p) * (1.0 + temp) * (1.0 + temp); return num / denom; } } void updateErrorSinogram(struct Sino *sino, struct SysMatrix *A, struct ICDInfo3DCone *icdInfo) { /** * Update error sinogram * * e <- e - A_{*,j} * Delta_xj */ long int i_beta, i_v, i_w; long int j_x, j_y, j_z, j_u; float B_ij; j_x = icdInfo->j_x; j_y = icdInfo->j_y; j_z = icdInfo->j_z; for (i_beta = 0; i_beta < sino->params.N_beta; ++i_beta) { j_u = A->j_u[j_x][j_y][i_beta]; for (i_v = A->i_vstart[j_x][j_y][i_beta]; i_v < A->i_vstart[j_x][j_y][i_beta]+A->i_vstride[j_x][j_y][i_beta]; ++i_v) { B_ij = A->B_ij_scaler * A->B[j_x][j_y][i_beta*A->i_vstride_max + i_v-A->i_vstart[j_x][j_y][i_beta]]; for (i_w = A->i_wstart[j_u][j_z]; i_w < A->i_wstart[j_u][j_z]+A->i_wstride[j_u][j_z]; ++i_w) { sino->e[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] -= B_ij * A->C_ij_scaler * A->C[j_u][j_z*A->i_wstride_max + i_w-A->i_wstart[j_u][j_z]] * icdInfo->Delta_xj; } } } } void updateIterationStats(struct ReconAux *reconAux, struct ICDInfo3DCone *icdInfo, struct Image *img) { reconAux->TotalValueChange += fabs(icdInfo->Delta_xj); //reconAux->TotalVoxelValue += _MAX_(img->vox[icdInfo->j_x][icdInfo->j_y][icdInfo->j_z], icdInfo->old_xj); reconAux->TotalVoxelValue += _MAX_(img->vox[index_3D(icdInfo->j_x,icdInfo->j_y,icdInfo->j_z,img->params.N_y,img->params.N_z)], icdInfo->old_xj); reconAux->NumUpdatedVoxels++; } void resetIterationStats(struct ReconAux *reconAux) { reconAux->TotalValueChange = 0; reconAux->TotalVoxelValue = 0; reconAux->NumUpdatedVoxels = 0; } void RandomAux_ShuffleOrderXYZ(struct RandomAux *aux, struct ImageParams *params) { fprintf(stdout, "zipline mode 0\n"); shuffleLongIntArray(aux->orderXYZ, params->N_x * params->N_y * params->N_z); } void indexExtraction3D(long int j_xyz, long int *j_x, long int N_x, long int *j_y, long int N_y, long int *j_z, long int N_z) { /* j_xyz = j_z + N_z j_y + N_z N_y j_x */ long int j_temp; j_temp = j_xyz; /* Now, j_temp = j_z + N_z j_y + N_z N_y j_x */ *j_z = j_temp % N_z; j_temp = (j_temp-*j_z) / N_z; /* Now, j_temp = j_y + N_y j_x */ *j_y = j_temp % N_y; j_temp = (j_temp-*j_y) / N_y; /* Now, j_temp = j_x */ *j_x = j_temp; return; } float MAPCost3D(struct Sino *sino, struct Image *img, struct ReconParams *reconParams) { /** * Computes MAP cost function */ float cost; // Initialize cost with forward model cost cost = MAPCostForward(sino); // if prior is used, add prior cost if(reconParams->priorWeight_QGGMRF >= 0) cost += MAPCostPrior_QGGMRF(img, reconParams); // if proximal map is used, add proximal map cost if(reconParams->priorWeight_proxMap >= 0) cost += MAPCostPrior_ProxMap(img, reconParams); return cost; } float MAPCostForward(struct Sino *sino) { /** * ForwardCost = 1/2 ||e||^{2}_{W} */ long int i_beta, i_v, i_w; float cost; cost = 0; for (i_beta = 0; i_beta < sino->params.N_beta; ++i_beta) { for (i_v = 0; i_v < sino->params.N_dv; ++i_v) { for (i_w = 0; i_w < sino->params.N_dw; ++i_w) { cost += sino->e[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * sino->wgt[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * sino->e[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)]; } } } return cost / (2.0 * sino->params.weightScaler_value); } float MAPCostPrior_QGGMRF(struct Image *img, struct ReconParams *reconParams) { /** * cost = sum b_{s,r} rho(x_s-x_r) * {s,r} E P */ long int j_x, j_y, j_z; struct ICDInfo3DCone icdInfo; float cost; float temp; cost = 0; for (j_x = 0; j_x < img->params.N_x; ++j_x) { for (j_y = 0; j_y < img->params.N_y; ++j_y) for (j_z = 0; j_z < img->params.N_z; ++j_z) { /** * Prepare icdInfo */ icdInfo.j_x = j_x; icdInfo.j_y = j_y; icdInfo.j_z = j_z; extractNeighbors(&icdInfo, img, reconParams); icdInfo.old_xj = img->vox[index_3D(j_x,j_y,j_z,img->params.N_y,img->params.N_z)]; temp = MAPCostPrior_QGGMRFSingleVoxel_HalfNeighborhood(&icdInfo, reconParams); cost += temp; } } return cost * reconParams->priorWeight_QGGMRF; } float MAPCostPrior_ProxMap(struct Image *img, struct ReconParams *reconParams) { /** * Compute proximal mapping prior cost * 1 || ||2 * cost += ---------------- || x - x~ || * 2 sigma_lambda^2 || ||2 * */ long int j_x, j_y, j_z; float cost, diff_voxel; cost = 0; for (j_x = 0; j_x < img->params.N_x; ++j_x) { for (j_y = 0; j_y < img->params.N_y; ++j_y) { for (j_z = 0; j_z < img->params.N_z; ++j_z) { //diff_voxel = img->vox[j_x][j_y][j_z] - img->proxMapInput[j_x][j_y][j_z]; diff_voxel = img->vox[index_3D(j_x,j_y,j_z,img->params.N_y,img->params.N_z)] - img->proxMapInput[index_3D(j_x,j_y,j_z,img->params.N_y,img->params.N_z)]; cost += diff_voxel*diff_voxel*isInsideMask(j_x, j_y, img->params.N_x, img->params.N_y); } } } cost /= 2 * reconParams->sigma_lambda * reconParams->sigma_lambda; return cost; } float MAPCostPrior_QGGMRFSingleVoxel_HalfNeighborhood(struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams) { /** * Compute prior model term of theta1 and theta2: * * cost += sum b_{j,r} * rho(x_j - x_r) * {r E ∂j^half} * */ int i; float sum1Face, sum1Edge, sum1Vertex; sum1Face = 0; sum1Edge = 0; sum1Vertex = 0; if (reconParams->bFace>=0) for (i = 0; i < 3; ++i) /* Note: only use first half of the neighbors */ sum1Face += QGGMRFPotential(icdInfo->old_xj - icdInfo->neighborsFace[i], reconParams); if (reconParams->bEdge>=0) for (i = 0; i < 6; ++i) /* Note: only use first half of the neighbors */ sum1Edge += QGGMRFPotential(icdInfo->old_xj - icdInfo->neighborsEdge[i], reconParams); if (reconParams->bVertex>=0) for (i = 0; i < 4; ++i) /* Note: only use first half of the neighbors */ sum1Vertex += QGGMRFPotential(icdInfo->old_xj - icdInfo->neighborsVertex[i], reconParams); return reconParams->bFace * sum1Face + reconParams->bEdge * sum1Edge + reconParams->bVertex * sum1Vertex; } /* the potential function of the QGGMRF prior model. p << q <= 2 */ float QGGMRFPotential(float delta, struct ReconParams *reconParams) { float p, q, T, sigmaX; float temp, GGMRF_Pot; p = reconParams->p; q = reconParams->q; T = reconParams->T; sigmaX = reconParams->sigmaX; GGMRF_Pot = pow(fabs(delta),p)/(p*pow(sigmaX,p)); temp = pow(fabs(delta/(T*sigmaX)), q-p); return ( GGMRF_Pot * temp/(1.0+temp) ); } void partialZipline_computeStartStopIndex(long int *j_z_start, long int *j_z_stop, long int indexZiplines, long int numVoxelsPerZipline, long int N_z) { *j_z_start = indexZiplines*numVoxelsPerZipline; *j_z_stop = _MIN_(*j_z_start+numVoxelsPerZipline-1, N_z-1); } int partialZipline_computeZiplineIndex(long int j_z, long int numVoxelsPerZipline) { return floor(j_z / numVoxelsPerZipline); } void prepareICDInfoRandGroup(long int j_x, long int j_y, struct RandomZiplineAux *randomZiplineAux, struct ICDInfo3DCone *icdInfo, struct Image *img, struct ReconParams *reconParams, struct ReconAux *reconAux) { /* j = j_y + N_y j_x */ long int j_z, k_M; long int j_z_start, j_z_stop; long int indexZiplines; k_M = 0; for (indexZiplines = 0; indexZiplines < reconParams->numZiplines; ++indexZiplines) { if (!reconAux->NHICD_isPartialUpdateActive || reconAux->NHICD_isPartialZiplineHot[indexZiplines]) { partialZipline_computeStartStopIndex(&j_z_start, &j_z_stop, indexZiplines, reconParams->numVoxelsPerZipline, img->params.N_z); for (j_z = j_z_start; j_z <= j_z_stop; ++j_z) { if(randomZiplineAux->groupIndex[j_x][j_y][j_z] == randomZiplineAux->k_G) { prepareICDInfo(j_x, j_y, j_z, &icdInfo[k_M], img, reconAux, reconParams); /* Increment k_M. After loop terminates k_M = No. members */ k_M++; } } } } randomZiplineAux->N_M = k_M; } void computeDeltaXjAndUpdate(struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams, struct Image *img, struct ReconAux *reconAux) { /** * Compute voxel increment Delta_xj. * Delta_xj >= -x_j accomplishes positivity constraint: * * Delta_xj = clip{ -theta1/theta2, [-x_j, inf) } */ float theta1, theta2; theta1 = icdInfo->theta1_f + reconParams->priorWeight_QGGMRF*icdInfo->theta1_p_QGGMRF + reconParams->priorWeight_proxMap*icdInfo->theta1_p_proxMap; theta2 = icdInfo->theta2_f + reconParams->priorWeight_QGGMRF*icdInfo->theta2_p_QGGMRF + reconParams->priorWeight_proxMap*icdInfo->theta2_p_proxMap; if (theta2 != 0) { icdInfo->Delta_xj = -theta1/theta2; if(reconParams->is_positivity_constraint) icdInfo->Delta_xj = _MAX_(icdInfo->Delta_xj, -icdInfo->old_xj); } else { icdInfo->Delta_xj = _MAX_(icdInfo->old_xj, 0); } if(icdInfo->Delta_xj != icdInfo->Delta_xj) { printf("theta1_f = %e\n", icdInfo->theta1_f); printf("theta2_f = %e\n", icdInfo->theta2_f); printf("theta1_p_QGGMRF = %e\n", icdInfo->theta1_p_QGGMRF); printf("theta2_p_QGGMRF = %e\n", icdInfo->theta2_p_QGGMRF); printf("theta1_p_proxMap = %e\n", icdInfo->theta1_p_proxMap); printf("theta2_p_proxMap = %e\n", icdInfo->theta2_p_proxMap); printf("theta2 = %e\n", theta2); printf("theta2 = %e\n", theta2); printf("-t1/t2 = %e\n", -theta1/theta2); printf("Delta_xj = %e\n", icdInfo->Delta_xj); printf("------------------------\n"); } /** * Update voxel: * * x_j <- x_j + Delta_xj */ //img->vox[icdInfo->j_x][icdInfo->j_y][icdInfo->j_z] += icdInfo->Delta_xj; img->vox[index_3D(icdInfo->j_x,icdInfo->j_y,icdInfo->j_z,img->params.N_y,img->params.N_z)] += icdInfo->Delta_xj; } void computeDeltaXjAndUpdateGroup(struct ICDInfo3DCone *icdInfo, struct RandomZiplineAux *randomZiplineAux, struct ReconParams *reconParams, struct Image *img, struct ReconAux *reconAux) { long int N_M, k_M; struct ICDInfo3DCone *info; N_M = randomZiplineAux->N_M; for (k_M = 0; k_M < N_M; ++k_M) { info = &icdInfo[k_M]; computeDeltaXjAndUpdate(info, reconParams, img, reconAux); } } void updateIterationStatsGroup(struct ReconAux *reconAux, struct ICDInfo3DCone *icdInfoArray, struct RandomZiplineAux *randomZiplineAux, struct Image *img, struct ReconParams *reconParams) { long int N_M, k_M; float absDelta, totValue; struct ICDInfo3DCone *icdInfo; long int j_x, j_y, j_z; long int indexZiplines; j_x = icdInfoArray[0].j_x; j_y = icdInfoArray[0].j_y; N_M = randomZiplineAux->N_M; for (k_M = 0; k_M < N_M; ++k_M) { icdInfo = &icdInfoArray[k_M]; j_z = icdInfo->j_z; indexZiplines = partialZipline_computeZiplineIndex(j_z, reconParams->numVoxelsPerZipline); absDelta = fabs(icdInfo->Delta_xj); //totValue = _MAX_(img->vox[j_x][j_y][j_z], icdInfo->old_xj); totValue = _MAX_(img->vox[index_3D(j_x,j_y,j_z,img->params.N_y,img->params.N_z)], icdInfo->old_xj); reconAux->TotalValueChange += absDelta; reconAux->TotalVoxelValue += totValue; reconAux->NumUpdatedVoxels++; reconAux->NHICD_numUpdatedVoxels[indexZiplines]++; reconAux->NHICD_totalValueChange[indexZiplines] += absDelta; } } void disp_iterationInfo(struct ReconAux *reconAux, struct ReconParams *reconParams, int itNumber, int MaxIterations, float cost, float relUpdate, float stopThresholdChange, float weightScaler_value, float voxelsPerSecond, float ticToc_iteration, float weightedNormSquared_e, float ratioUpdated, float totalEquits) { printf("************************** Iteration %-2d (max. %d) **************************\n", itNumber, MaxIterations); printf("* Cost = %-10.10e\n", cost); printf("* Rel. Update = %-10.10e %% (threshold = %-10.10e %%)\n", relUpdate*100, stopThresholdChange*100); printf("* RWFE = ||e||_W/||y||_W = %-10.10e %% (threshold = %-10.10e %%)\n", reconAux->relativeWeightedForwardError*100, reconParams->stopThesholdRWFE_pct); printf("* RUFE = ||e|| / ||y|| = %-10.10e %% (threshold = %-10.10e %%)\n", reconAux->relativeUnweightedForwardError*100, reconParams->stopThesholdRUFE_pct); printf("* ----------------------------------------------------------------------------\n"); printf("* 1/M ||e||^2_W = %-10.10e = 1/%-10.10f\n", weightedNormSquared_e, 1/weightedNormSquared_e); printf("* weightScaler_value = %-10.10e = 1/%-10.10f\n", weightScaler_value, 1/weightScaler_value); printf("* ----------------------------------------------------------------------------\n"); printf("* voxelsPerSecond = %-10.10e \n", voxelsPerSecond); printf("* time icd update = %-10.10e s\n", ticToc_iteration); printf("* ratioUpdated = %-10.10e %%\n", ratioUpdated*100); printf("* totalEquits = %-10.10e \n", totalEquits); printf("******************************************************************************\n\n"); } float computeRelUpdate(struct ReconAux *reconAux, struct ReconParams *reconParams, struct Image *img) { float relUpdate; float AvgValueChange, AvgVoxelValue; float scaler; int subsampleFactor = 10; /* when chosen 1 this is completely accurate. User can mess with this to some extend*/ if(reconAux->NumUpdatedVoxels>0) { AvgValueChange = reconAux->TotalValueChange / reconAux->NumUpdatedVoxels; AvgVoxelValue = reconAux->TotalVoxelValue / reconAux->NumUpdatedVoxels; } else { AvgValueChange = 0; AvgVoxelValue = 0; } if(AvgVoxelValue>0) { /* [relativeChangeMode] 'meanImage' or 'fixedScaler' or 'percentile' */ if (strcmp(reconParams->relativeChangeMode, "meanImage")==0) { relUpdate = AvgValueChange / AvgVoxelValue; } else if (strcmp(reconParams->relativeChangeMode, "fixedScaler")==0) { relUpdate = AvgValueChange / reconParams->relativeChangeScaler; } else if (strcmp(reconParams->relativeChangeMode, "percentile")==0) { //scaler = prctile_copyFast(&img->vox[0][0][0], img->params.N_x*img->params.N_y*img->params.N_z, reconParams->relativeChangePercentile, subsampleFactor); scaler = prctile_copyFast(&img->vox[0], img->params.N_x*img->params.N_y*img->params.N_z, reconParams->relativeChangePercentile, subsampleFactor); relUpdate = AvgValueChange / scaler; } else { printf("Error: relativeChangeMode unknown\n"); exit(-1); } } else { relUpdate = 0; } return relUpdate; } /* * * * * * * * * * * * parallel * * * * * * * * * * * * **/ void prepareParallelAux(struct ParallelAux *parallelAux, long int N_M_max) { int numThreads; #pragma omp parallel { #pragma omp master { parallelAux->numThreads = numThreads = omp_get_num_threads(); } } parallelAux->N_M_max = N_M_max; parallelAux->partialTheta = (struct PartialTheta**) multialloc(sizeof(struct PartialTheta), 2, numThreads, N_M_max); parallelAux->j_u = mget_spc(numThreads, sizeof(long int)); parallelAux->i_v = mget_spc(numThreads, sizeof(long int)); parallelAux->B_ij = mget_spc(numThreads, sizeof(float)); parallelAux->k_M = mget_spc(numThreads, sizeof(long int)); parallelAux->j_z = mget_spc(numThreads, sizeof(long int)); parallelAux->i_w = mget_spc(numThreads, sizeof(long int)); parallelAux->A_ij = mget_spc(numThreads, sizeof(float)); } void freeParallelAux(struct ParallelAux *parallelAux) { multifree((void**)parallelAux->partialTheta, 2); free((void*)parallelAux->j_u); free((void*)parallelAux->i_v); free((void*)parallelAux->B_ij); free((void*)parallelAux->k_M); free((void*)parallelAux->j_z); free((void*)parallelAux->i_w); free((void*)parallelAux->A_ij); } void ICDStep3DConeGroup(struct Sino *sino, struct Image *img, struct SysMatrix *A, struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams, struct RandomZiplineAux *randomZiplineAux, struct ParallelAux *parallelAux, struct ReconAux *reconAux) { if (randomZiplineAux->N_M>0) { computeTheta1Theta2ForwardTermGroup(sino, A, icdInfo, randomZiplineAux, parallelAux, reconParams); if(reconParams->priorWeight_QGGMRF >= 0) computeTheta1Theta2PriorTermQGGMRFGroup(icdInfo, reconParams, randomZiplineAux); if(reconParams->priorWeight_proxMap >= 0) computeTheta1Theta2PriorTermProxMapGroup(icdInfo, reconParams, randomZiplineAux); computeDeltaXjAndUpdateGroup(icdInfo, randomZiplineAux, reconParams, img, reconAux); updateErrorSinogramGroup(sino, A, icdInfo, randomZiplineAux); } } void computeTheta1Theta2ForwardTermGroup(struct Sino *sino, struct SysMatrix *A, struct ICDInfo3DCone *icdInfo, struct RandomZiplineAux *randomZiplineAux, struct ParallelAux *parallelAux, struct ReconParams *reconParams) { /** * Compute forward model term of theta1 and theta2 for all members: * * theta1_f = -e^t W A_{*,j} * theta2_f = A_{*,j}^t W A _{*,j} */ long int i_beta, i_v, i_w; long int j_x, j_y, j_z, j_u; float B_ij, A_ij; long int N_M, k_M; int threadID; N_M = randomZiplineAux->N_M; j_x = (icdInfo[0]).j_x; j_y = (icdInfo[0]).j_y; for (threadID = 0; threadID < parallelAux->numThreads; ++threadID) { for (k_M = 0; k_M < N_M; ++k_M) { parallelAux->partialTheta[threadID][k_M].t1 = 0; parallelAux->partialTheta[threadID][k_M].t2 = 0; } } #pragma omp parallel private(threadID, j_u, i_v, B_ij, k_M, j_z, i_w, A_ij) { threadID = omp_get_thread_num(); #pragma omp for for (i_beta = 0; i_beta < sino->params.N_beta; ++i_beta) { j_u = A->j_u[j_x][j_y][i_beta]; for (i_v = A->i_vstart[j_x][j_y][i_beta]; i_v < A->i_vstart[j_x][j_y][i_beta]+A->i_vstride[j_x][j_y][i_beta]; ++i_v) { B_ij = A->B_ij_scaler * A->B[j_x][j_y][i_beta*A->i_vstride_max + i_v-A->i_vstart[j_x][j_y][i_beta]]; /* Loop through all the members along zip line */ for (k_M = 0; k_M < N_M; ++k_M) { j_z = icdInfo[k_M].j_z; for (i_w = A->i_wstart[j_u][j_z]; i_w < A->i_wstart[j_u][j_z]+A->i_wstride[j_u][j_z]; ++i_w) { A_ij = B_ij * A->C_ij_scaler * A->C[j_u][j_z*A->i_wstride_max + i_w-A->i_wstart[j_u][j_z]]; parallelAux->partialTheta[threadID][k_M].t1 -= sino->e[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * sino->wgt[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * A_ij; parallelAux->partialTheta[threadID][k_M].t2 += A_ij * sino->wgt[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] * A_ij; } } } } } for (threadID = 0; threadID < parallelAux->numThreads; ++threadID) { for (k_M = 0; k_M < N_M; ++k_M) { icdInfo[k_M].theta1_f += parallelAux->partialTheta[threadID][k_M].t1; icdInfo[k_M].theta2_f += parallelAux->partialTheta[threadID][k_M].t2; } } if(strcmp(reconParams->weightScaler_domain,"spatiallyInvariant") == 0) { for (k_M = 0; k_M < N_M; ++k_M) { icdInfo[k_M].theta1_f /= sino->params.weightScaler_value; icdInfo[k_M].theta2_f /= sino->params.weightScaler_value; } } else { fprintf(stderr, "ERROR in computeTheta1Theta2ForwardTerm: can't recongnize weightScaler_domain.\n"); exit(-1); } } void computeTheta1Theta2PriorTermQGGMRFGroup(struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams, struct RandomZiplineAux *randomZiplineAux) { long int N_M, k_M; N_M = randomZiplineAux->N_M; #pragma omp parallel for for (k_M = 0; k_M < N_M; ++k_M) { computeTheta1Theta2PriorTermQGGMRF(&icdInfo[k_M], reconParams); } } void updateErrorSinogramGroup(struct Sino *sino, struct SysMatrix *A, struct ICDInfo3DCone *icdInfo, struct RandomZiplineAux *randomZiplineAux) { /** * Update error sinogram * * e <- e - A_{*,j} * Delta_xj */ long int N_M, k_M; long int i_beta, i_v, i_w; long int j_x, j_y, j_z, j_u; float B_ij; N_M = randomZiplineAux->N_M; j_x = icdInfo[0].j_x; j_y = icdInfo[0].j_y; #pragma omp parallel for private(j_u, i_v, B_ij, k_M, j_z, i_w) for (i_beta = 0; i_beta < sino->params.N_beta; ++i_beta) { j_u = A->j_u[j_x][j_y][i_beta]; for (i_v = A->i_vstart[j_x][j_y][i_beta]; i_v < A->i_vstart[j_x][j_y][i_beta]+A->i_vstride[j_x][j_y][i_beta]; ++i_v) { B_ij = A->B_ij_scaler * A->B[j_x][j_y][i_beta*A->i_vstride_max + i_v-A->i_vstart[j_x][j_y][i_beta]]; for (k_M = 0; k_M < N_M; ++k_M) { j_z = icdInfo[k_M].j_z; for (i_w = A->i_wstart[j_u][j_z]; i_w < A->i_wstart[j_u][j_z]+A->i_wstride[j_u][j_z]; ++i_w) { sino->e[index_3D(i_beta,i_v,i_w,sino->params.N_dv,sino->params.N_dw)] -= B_ij * A->C_ij_scaler * A->C[j_u][j_z*A->i_wstride_max + i_w-A->i_wstart[j_u][j_z]] * icdInfo[k_M].Delta_xj; } } } } } void computeTheta1Theta2PriorTermProxMapGroup(struct ICDInfo3DCone *icdInfo, struct ReconParams *reconParams, struct RandomZiplineAux *randomZiplineAux) { long int N_M, k_M; N_M = randomZiplineAux->N_M; for (k_M = 0; k_M < N_M; ++k_M) { icdInfo[k_M].theta1_p_proxMap = (icdInfo[k_M].old_xj - icdInfo[k_M].proxMapInput_j) / (reconParams->sigma_lambda * reconParams->sigma_lambda); icdInfo[k_M].theta2_p_proxMap = 1.0 / (reconParams->sigma_lambda * reconParams->sigma_lambda); } } /* * * * * * * * * * * * time aux ICD * * * * * * * * * * * * **/ void speedAuxICD_reset(struct SpeedAuxICD *speedAuxICD) { speedAuxICD->numberUpdatedVoxels = 0; speedAuxICD->tic = omp_get_wtime(); speedAuxICD->toc = -1.0; speedAuxICD->voxelsPerSecond = -1.0; } void speedAuxICD_update(struct SpeedAuxICD *speedAuxICD, long int incrementNumber) { speedAuxICD->numberUpdatedVoxels += incrementNumber; } void speedAuxICD_computeSpeed(struct SpeedAuxICD *speedAuxICD) { if (speedAuxICD->numberUpdatedVoxels > 0) { speedAuxICD->toc = omp_get_wtime(); speedAuxICD->voxelsPerSecond = ((float)speedAuxICD->numberUpdatedVoxels) / (speedAuxICD->toc - speedAuxICD->tic); } else { speedAuxICD->voxelsPerSecond = 0; } } /* * * * * * * * * * * * NHICD * * * * * * * * * * * * **/ int NHICD_isVoxelHot(struct ReconParams *reconParams, struct Image *img, long int j_x, long int j_y, long int j_z, float lastChangeThreshold) { if(img->lastChange[j_x][j_y][j_z] > lastChangeThreshold) return 1; if(bernoulli(reconParams->NHICD_random/100)==1) return 1; return 0; } int NHICD_activatePartialUpdate(struct ReconParams *reconParams, float relativeWeightedForwardError) { if (relativeWeightedForwardError*100<reconParams->NHICD_ThresholdAllVoxels_ErrorPercent && strcmp(reconParams->NHICD_Mode, "off")!=0) return 1; else return 0; } int NHICD_checkPartialZiplineHot(struct ReconAux *reconAux, long int j_x, long int j_y, long int indexZiplines, struct Image *img) { if (reconAux->NHICD_isPartialUpdateActive) { if (img->lastChange[j_x][j_y][indexZiplines]>=reconAux->lastChangeThreshold || img->timeToChange[j_x][j_y][indexZiplines]==0) { return 1; } else { img->timeToChange[j_x][j_y][indexZiplines] = _MAX_(img->timeToChange[j_x][j_y][indexZiplines]-1, 0); return 0; } } else { return 1; } } void NHICD_checkPartialZiplinesHot(struct ReconAux *reconAux, long int j_x, long int j_y, struct ReconParams *reconParams, struct Image *img) { long int indexZiplines; for (indexZiplines = 0; indexZiplines < reconParams->numZiplines; ++indexZiplines) { reconAux->NHICD_isPartialZiplineHot[indexZiplines] = NHICD_checkPartialZiplineHot(reconAux, j_x, j_y, indexZiplines, img); reconAux->NHICD_numUpdatedVoxels[indexZiplines] = 0; reconAux->NHICD_totalValueChange[indexZiplines] = 0; } } void updateNHICDStats(struct ReconAux *reconAux, long int j_x, long int j_y, struct Image *img, struct ReconParams *reconParams) { long int jj_x, jj_y, jj_x_min, jj_y_min, jj_x_max, jj_y_max; float avgChange; float mean_timeToChange; long int sigma_timeToChange; long int indexZiplines; float w_self = 1; float w_past = 0.5; float w_neighbors = 0.5; mean_timeToChange = 100.0/reconParams->NHICD_random-1; sigma_timeToChange = round(mean_timeToChange*0.5); jj_x_min = _MAX_(j_x-1, 0); jj_y_min = _MAX_(j_y-1, 0); jj_x_max = _MIN_(j_x+1, img->params.N_x-1); jj_y_max = _MIN_(j_y+1, img->params.N_y-1); for (indexZiplines = 0; indexZiplines < reconParams->numZiplines; ++indexZiplines) { if (reconAux->NHICD_isPartialZiplineHot[indexZiplines]) { avgChange = reconAux->NHICD_numUpdatedVoxels[indexZiplines] > 0 ? reconAux->NHICD_totalValueChange[indexZiplines]/reconAux->NHICD_numUpdatedVoxels[indexZiplines] : 0; img->lastChange[j_x][j_y][indexZiplines] = w_past * img->lastChange[j_x][j_y][indexZiplines] + w_self * avgChange; for (jj_x = jj_x_min; jj_x <= jj_x_max; ++jj_x) { for (jj_y = jj_y_min; jj_y <= jj_y_max; ++jj_y) { img->lastChange[jj_x][jj_y][indexZiplines] += w_neighbors * reconAux->NHICD_neighborFilter[1+jj_x-j_x][1+jj_y-j_y] * avgChange; } } img->timeToChange[j_x][j_y][indexZiplines] = almostUniformIntegerRV(mean_timeToChange, sigma_timeToChange); } } }
shear.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS H H EEEEE AAA RRRR % % SS H H E A A R R % % SSS HHHHH EEE AAAAA RRRR % % SS H H E A A R R % % SSSSS H H EEEEE A A R R % % % % % % MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The XShearImage() and YShearImage() methods are based on the paper "A Fast % Algorithm for General Raster Rotation" by Alan W. Paeth, Graphics % Interface '86 (Vancouver). ShearRotateImage() is adapted from a similar % method based on the Paeth paper written by Michael Halle of the Spatial % Imaging Group, MIT Media Lab. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache-private.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/shear.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C r o p T o F i t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropToFitImage() crops the sheared image as determined by the bounding box % as defined by width and height and shearing angles. % % The format of the CropToFitImage method is: % % MagickBooleanType CropToFitImage(Image **image, % const double x_shear,const double x_shear, % const double width,const double height, % const MagickBooleanType rotate,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear, width, height: Defines a region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CropToFitImage(Image **image, const double x_shear,const double y_shear, const double width,const double height, const MagickBooleanType rotate,ExceptionInfo *exception) { Image *crop_image; PointInfo extent[4], min, max; RectangleInfo geometry, page; register ssize_t i; /* Calculate the rotated image size. */ extent[0].x=(double) (-width/2.0); extent[0].y=(double) (-height/2.0); extent[1].x=(double) width/2.0; extent[1].y=(double) (-height/2.0); extent[2].x=(double) (-width/2.0); extent[2].y=(double) height/2.0; extent[3].x=(double) width/2.0; extent[3].y=(double) height/2.0; for (i=0; i < 4; i++) { extent[i].x+=x_shear*extent[i].y; extent[i].y+=y_shear*extent[i].x; if (rotate != MagickFalse) extent[i].x+=x_shear*extent[i].y; extent[i].x+=(double) (*image)->columns/2.0; extent[i].y+=(double) (*image)->rows/2.0; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } geometry.x=(ssize_t) ceil(min.x-0.5); geometry.y=(ssize_t) ceil(min.y-0.5); geometry.width=(size_t) floor(max.x-min.x+0.5); geometry.height=(size_t) floor(max.y-min.y+0.5); page=(*image)->page; (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page); crop_image=CropImage(*image,&geometry,exception); if (crop_image == (Image *) NULL) return(MagickFalse); crop_image->page=page; *image=DestroyImage(*image); *image=crop_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s k e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeskewImage() removes skew from the image. Skew is an artifact that % occurs in scanned images because of the camera being misaligned, % imperfections in the scanning or surface, or simply because the paper was % not placed completely flat when scanned. % % The result will be auto-croped if the artifact "deskew:auto-crop" is % defined, while the amount the image is to be deskewed, in degrees is also % saved as the artifact "deskew:angle". % % The format of the DeskewImage method is: % % Image *DeskewImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: separate background from foreground. % % o exception: return any errors or warnings in this structure. % */ static void RadonProjection(const Image *image,MatrixInfo *source_matrixs, MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection) { MatrixInfo *swap; register MatrixInfo *p, *q; register ssize_t x; size_t step; p=source_matrixs; q=destination_matrixs; for (step=1; step < GetMatrixColumns(p); step*=2) { for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step) { register ssize_t i; ssize_t y; unsigned short element, neighbor; for (i=0; i < (ssize_t) step; i++) { for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse) continue; } for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } for ( ; y < (ssize_t) GetMatrixRows(p); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } } } swap=p; p=q; q=swap; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,GetMatrixColumns(p),1) #endif for (x=0; x < (ssize_t) GetMatrixColumns(p); x++) { register ssize_t y; size_t sum; sum=0; for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++) { ssize_t delta; unsigned short element, neighbor; if (GetMatrixElement(p,x,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse) continue; delta=(ssize_t) element-(ssize_t) neighbor; sum+=delta*delta; } projection[GetMatrixColumns(p)+sign*x-1]=sum; } } static MagickBooleanType RadonTransform(const Image *image, const double threshold,size_t *projection,ExceptionInfo *exception) { CacheView *image_view; MatrixInfo *destination_matrixs, *source_matrixs; MagickBooleanType status; size_t count, width; ssize_t j, y; unsigned char c; unsigned short bits[256]; for (width=1; width < ((image->columns+7)/8); width<<=1) ; source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); destination_matrixs=AcquireMatrixInfo(width,image->rows, sizeof(unsigned short),exception); if ((source_matrixs == (MatrixInfo *) NULL) || (destination_matrixs == (MatrixInfo *) NULL)) { if (destination_matrixs != (MatrixInfo *) NULL) destination_matrixs=DestroyMatrixInfo(destination_matrixs); if (source_matrixs != (MatrixInfo *) NULL) source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } if (NullMatrix(source_matrixs) == MagickFalse) { destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } for (j=0; j < 256; j++) { c=(unsigned char) j; for (count=0; c != 0; c>>=1) count+=c & 0x01; bits[j]=(unsigned short) count; } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=(ssize_t) (image->columns+7)/8; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,-1,projection); (void) NullMatrix(source_matrixs); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,1,projection); image_view=DestroyCacheView(image_view); destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickTrue); } static void GetImageBackgroundColor(Image *image,const ssize_t offset, ExceptionInfo *exception) { CacheView *image_view; PixelInfo background; double count; ssize_t y; /* Compute average background color. */ if (offset <= 0) return; GetPixelInfo(image,&background); count=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if ((y >= offset) && (y < ((ssize_t) image->rows-offset))) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) continue; for (x=0; x < (ssize_t) image->columns; x++) { if ((x >= offset) && (x < ((ssize_t) image->columns-offset))) continue; background.red+=QuantumScale*GetPixelRed(image,p); background.green+=QuantumScale*GetPixelGreen(image,p); background.blue+=QuantumScale*GetPixelBlue(image,p); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) background.alpha+=QuantumScale*GetPixelAlpha(image,p); count++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->background_color.red=(double) ClampToQuantum(QuantumRange* background.red/count); image->background_color.green=(double) ClampToQuantum(QuantumRange* background.green/count); image->background_color.blue=(double) ClampToQuantum(QuantumRange* background.blue/count); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->background_color.alpha=(double) ClampToQuantum(QuantumRange* background.alpha/count); } MagickExport Image *DeskewImage(const Image *image,const double threshold, ExceptionInfo *exception) { AffineMatrix affine_matrix; const char *artifact; double degrees; Image *clone_image, *crop_image, *deskew_image, *median_image; MagickBooleanType status; RectangleInfo geometry; register ssize_t i; size_t max_projection, *projection, width; ssize_t skew; /* Compute deskew angle. */ for (width=1; width < ((image->columns+7)/8); width<<=1) ; projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1), sizeof(*projection)); if (projection == (size_t *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); status=RadonTransform(image,threshold,projection,exception); if (status == MagickFalse) { projection=(size_t *) RelinquishMagickMemory(projection); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } max_projection=0; skew=0; for (i=0; i < (ssize_t) (2*width-1); i++) { if (projection[i] > max_projection) { skew=i-(ssize_t) width+1; max_projection=projection[i]; } } projection=(size_t *) RelinquishMagickMemory(projection); degrees=RadiansToDegrees(-atan((double) skew/width/8)); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Deskew angle: %g",degrees); /* Deskew image. */ clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); { char angle[MagickPathExtent]; (void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees); (void) SetImageArtifact(clone_image,"deskew:angle",angle); } (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod, exception); affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0)))); affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.tx=0.0; affine_matrix.ty=0.0; artifact=GetImageArtifact(image,"deskew:auto-crop"); if (IsStringTrue(artifact) == MagickFalse) { deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); return(deskew_image); } /* Auto-crop image. */ GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact), exception); deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); if (deskew_image == (Image *) NULL) return((Image *) NULL); median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception); if (median_image == (Image *) NULL) { deskew_image=DestroyImage(deskew_image); return((Image *) NULL); } geometry=GetImageBoundingBox(median_image,exception); median_image=DestroyImage(median_image); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule()," Deskew geometry: " "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); crop_image=CropImage(deskew_image,&geometry,exception); deskew_image=DestroyImage(deskew_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e g r a l R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IntegralRotateImage() rotates the image an integral of 90 degrees. It % allocates the memory necessary for the new Image structure and returns a % pointer to the rotated image. % % The format of the IntegralRotateImage method is: % % Image *IntegralRotateImage(const Image *image,size_t rotations, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o rotations: Specifies the number of 90 degree rotations. % */ MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations, ExceptionInfo *exception) { #define RotateImageTag "Rotate/Image" CacheView *image_view, *rotate_view; Image *rotate_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; /* Initialize rotated image attributes. */ assert(image != (Image *) NULL); page=image->page; rotations%=4; switch (rotations) { case 0: { rotate_image=CloneImage(image,0,0,MagickTrue,exception); break; } case 2: { rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); break; } case 1: case 3: { rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); break; } } if (rotate_image == (Image *) NULL) return((Image *) NULL); /* Integral rotate the image. */ status=MagickTrue; progress=0; if (rotations != 0) { image_view=AcquireVirtualCacheView(image,exception); rotate_view=AcquireAuthenticCacheView(rotate_image,exception); } switch (rotations) { case 1: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 90 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,rotate_image,image->rows/tile_height,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t) (rotate_image->columns-(tile_y+height)),y+tile_x,height,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 2: { register ssize_t y; /* Rotate 180 degrees. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,rotate_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; 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(rotate_view,0,(ssize_t) (image->rows-y- 1),image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(rotate_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; q-=GetPixelChannels(rotate_image); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } case 3: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 270 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,rotate_image,image->rows/tile_height,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+ rotate_image->rows-(tile_x+width)),height,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((width-1)-y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } default: break; } if (rotations != 0) { rotate_view=DestroyCacheView(rotate_view); image_view=DestroyCacheView(image_view); } rotate_image->type=image->type; rotate_image->page=page; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + X S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % XShearImage() shears the image in the X direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a vertical % Y-axis. X shears will widen an image creating 'empty' triangles on the left % and right sides of the source image. % % The format of the XShearImage method is: % % MagickBooleanType XShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the X % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType XShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define XShearImageTag "XShear/Image" typedef enum { LEFT, RIGHT } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t y; /* X shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; background=image->background_color; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,height,1) #endif for (y=0; y < (ssize_t) height; y++) { PixelInfo pixel, source, destination; double area, displacement; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=x_offset*GetPixelChannels(image); displacement=degrees*(double) (y-height/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=RIGHT; else { displacement*=(-1.0); direction=LEFT; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case LEFT: { /* Transfer pixels left-to-right. */ if (step > x_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { if ((x_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case RIGHT: { /* Transfer pixels right-to-left. */ p+=width*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (x_offset+width+step-i) > image->columns) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,XShearImageTag,progress,height); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Y S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % YShearImage shears the image in the Y direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a % horizontal X-axis. Y shears will increase the height of an image creating % 'empty' triangles on the top and bottom of the source image. % % The format of the YShearImage method is: % % MagickBooleanType YShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the Y % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType YShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define YShearImageTag "YShear/Image" typedef enum { UP, DOWN } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t x; /* Y Shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; background=image->background_color; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { double area, displacement; PixelInfo pixel, source, destination; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=y_offset*GetPixelChannels(image); displacement=degrees*(double) (x-width/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=DOWN; else { displacement*=(-1.0); direction=UP; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case UP: { /* Transfer pixels top-to-bottom. */ if (step > y_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { if ((y_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case DOWN: { /* Transfer pixels bottom-to-top. */ p+=height*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (y_offset+height+step-i) > image->rows) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,YShearImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearImage() creates a new image that is a shear_image copy of an existing % one. Shearing slides one edge of an image along the X or Y axis, creating % a parallelogram. An X direction shear slides an edge along the X axis, % while a Y direction shear slides an edge along the Y axis. The amount of % the shear is controlled by a shear angle. For X direction shears, x_shear % is measured relative to the Y axis, and similarly, for Y direction shears % y_shear is measured relative to the X axis. Empty triangles left over from % shearing the image are filled with the background color defined by member % 'background_color' of the image.. ShearImage() allocates the memory % necessary for the new Image structure and returns a pointer to the new image. % % ShearImage() is based on the paper "A Fast Algorithm for General Raster % Rotatation" by Alan W. Paeth. % % The format of the ShearImage method is: % % Image *ShearImage(const Image *image,const double x_shear, % const double y_shear,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear: Specifies the number of degrees to shear the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearImage(const Image *image,const double x_shear, const double y_shear,ExceptionInfo *exception) { Image *integral_image, *shear_image; MagickBooleanType status; PointInfo shear; RectangleInfo border_info, bounds; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); /* Initialize shear angle. */ integral_image=CloneImage(image,0,0,MagickTrue,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0)))); shear.y=tan(DegreesToRadians(fmod(y_shear,360.0))); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute image size. */ bounds.width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5); bounds.x=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)- image->columns)/2.0-0.5); bounds.y=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*bounds.width)- image->rows)/2.0-0.5); /* Surround image with border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; shear_image=BorderImage(integral_image,&border_info,image->compose,exception); integral_image=DestroyImage(integral_image); if (shear_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Shear the image. */ if (shear_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception); status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x, (ssize_t) (shear_image->rows-image->rows)/2,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t) (shear_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType) image->columns,(MagickRealType) image->rows,MagickFalse,exception); shear_image->alpha_trait=image->alpha_trait; shear_image->compose=image->compose; shear_image->page.width=0; shear_image->page.height=0; if (status == MagickFalse) shear_image=DestroyImage(shear_image); return(shear_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearRotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. ShearRotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % ShearRotateImage() is based on the paper "A Fast Algorithm for General % Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a % similar method based on the Paeth paper written by Michael Halle of the % Spatial Imaging Group, MIT Media Lab. % % The format of the ShearRotateImage method is: % % Image *ShearRotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearRotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *integral_image, *rotate_image; MagickBooleanType status; MagickRealType angle; PointInfo shear; RectangleInfo border_info, bounds; size_t height, rotations, shear_width, width; /* Adjust rotation angle. */ 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); angle=fmod(degrees,360.0); if (angle < -45.0) angle+=360.0; for (rotations=0; angle > 45.0; rotations++) angle-=90.0; rotations%=4; /* Calculate shear equations. */ integral_image=IntegralRotateImage(image,rotations,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan((double) DegreesToRadians(angle)/2.0)); shear.y=sin((double) DegreesToRadians(angle)); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute maximum bounds for 3 shear operations. */ width=integral_image->columns; height=integral_image->rows; bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5); bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5); shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+ bounds.width+0.5); bounds.x=(ssize_t) floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5); bounds.y=(ssize_t) floor(((double) bounds.height-height+2)/2.0+0.5); /* Surround image with a border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; rotate_image=BorderImage(integral_image,&border_info,image->compose, exception); integral_image=DestroyImage(integral_image); if (rotate_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Rotate the image. */ status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t) (rotate_image->rows-height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t) (rotate_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t) (rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows- bounds.height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width, (MagickRealType) height,MagickTrue,exception); rotate_image->alpha_trait=image->alpha_trait; rotate_image->compose=image->compose; rotate_image->page.width=0; rotate_image->page.height=0; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); }
colormap.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO L OOO RRRR M M AAA PPPP % % C O O L O O R R MM MM A A P P % % C O O L O O RRRR M M M AAAAA PPPP % % C O O L O O R R M M A A P % % CCCC OOO LLLLL OOO R R M M A A P % % % % % % MagickCore Colormap Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % We use linked-lists because splay-trees do not currently support duplicate % key / value pairs (.e.g X11 green compliance and SVG green compliance). % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/client.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.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/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/xml-tree.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageColormap() allocates an image colormap and initializes % it to a linear gray colorspace. If the image already has a colormap, % it is replaced. AcquireImageColormap() returns MagickTrue if successful, % otherwise MagickFalse if there is not enough memory. % % The format of the AcquireImageColormap method is: % % MagickBooleanType AcquireImageColormap(Image *image,const size_t colors, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colors: the number of colors in the image colormap. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AcquireImageColormap(Image *image, const size_t colors,ExceptionInfo *exception) { register ssize_t i; /* Allocate image colormap. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->colors=MagickMax(colors,1); if (image->colormap == (PixelInfo *) NULL) image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); else image->colormap=(PixelInfo *) ResizeQuantumMemory(image->colormap, image->colors+1,sizeof(*image->colormap)); if (image->colormap == (PixelInfo *) NULL) { image->colors=0; image->storage_class=DirectClass; ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } for (i=0; i < (ssize_t) image->colors; i++) { double pixel; GetPixelInfo(image,image->colormap+i); pixel=(double) (i*(QuantumRange/MagickMax(colors-1,1))); image->colormap[i].red=pixel; image->colormap[i].green=pixel; image->colormap[i].blue=pixel; image->colormap[i].alpha=(MagickRealType) OpaqueAlpha; image->colormap[i].alpha_trait=BlendPixelTrait; } return(SetImageStorageClass(image,PseudoClass,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C y c l e C o l o r m a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CycleColormap() displaces an image's colormap by a given number of % positions. If you cycle the colormap a number of times you can produce % a psychodelic effect. % % WARNING: this assumes an images colormap is in a well know and defined % order. Currently Imagemagick has no way of setting that order. % % The format of the CycleColormapImage method is: % % MagickBooleanType CycleColormapImage(Image *image,const ssize_t displace, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o displace: displace the colormap this amount. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CycleColormapImage(Image *image, const ssize_t displace,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == DirectClass) (void) SetImageType(image,PaletteType,exception); status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; ssize_t index; 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++) { index=(ssize_t) (GetPixelIndex(image,q)+displace) % image->colors; if (index < 0) index+=(ssize_t) image->colors; SetPixelIndex(image,(Quantum) index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S o r t C o l o r m a p B y I n t e n s i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SortColormapByIntensity() sorts the colormap of a PseudoClass image by % decreasing color intensity. % % The format of the SortColormapByIntensity method is: % % MagickBooleanType SortColormapByIntensity(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: A pointer to an Image structure. % % 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) { const PixelInfo *color_1, *color_2; int intensity; color_1=(const PixelInfo *) x; color_2=(const PixelInfo *) y; intensity=(int) GetPixelInfoIntensity((const Image *) NULL,color_2)-(int) GetPixelInfoIntensity((const Image *) NULL,color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport MagickBooleanType SortColormapByIntensity(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; register ssize_t i; ssize_t y; unsigned short *pixels; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->storage_class != PseudoClass) return(MagickTrue); /* Allocate memory for pixel indexes. */ pixels=(unsigned short *) AcquireQuantumMemory((size_t) image->colors, sizeof(*pixels)); if (pixels == (unsigned short *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Assign index values to colormap entries. */ for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].alpha=(double) i; /* Sort image colormap by decreasing color popularity. */ qsort((void *) image->colormap,(size_t) image->colors, sizeof(*image->colormap),IntensityCompare); /* Update image colormap indexes to sorted colormap order. */ for (i=0; i < (ssize_t) image->colors; i++) pixels[(ssize_t) image->colormap[i].alpha]=(unsigned short) i; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { Quantum index; register ssize_t x; register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { index=(Quantum) pixels[(ssize_t) GetPixelIndex(image,q)]; SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (status == MagickFalse) break; } image_view=DestroyCacheView(image_view); pixels=(unsigned short *) RelinquishMagickMemory(pixels); return(status); }
bstep.c
#include "q_incs.h" #include "dnn_types.h" #include "act_fns.h" #include "avx.h" #include "bstep.h" int compute_da_last( float ** restrict a, /* 'a' value for last layer */ float ** restrict out, /* Xout */ float ** restrict da, /* 'da' value for last layer */ int n_in_last, /* number of neurons in last layer */ int nI ) { int status = 0; for ( int j = 0; j < n_in_last; j++ ) { // for neurons in last layer float *out_j = out[j]; float *a_j = a[j]; float *da_j = da[j]; #pragma omp parallel for schedule(static, 16) // 16 is so that if cache line is 64 bytes and float is 4 bytes // then threads do not stomp on each other for ( int i = 0; i < nI; i++ ) { // for each instance da_j[i] = ( ( 1 - out_j[i] ) / ( 1 - a_j[i] ) ) - ( out_j[i] / a_j[i] ); #ifdef COUNT num_b_flops += 5; #endif } } // 'da' for last layer has been computed BYE: return status; } //================================================================ /* For backward propagation, in_layer --> current layer (l) out_layer -> previous layer (l-1) */ int bstep( float **z, /* 'z' at in_layer */ float **a_prev, /* 'a' at out_layer */ float **W, /* 'W' at in_layer */ float **da, /* 'da' at in_layer */ float **dz, /* 'dz' at in_layer */ float **da_prev, /* 'da' at out_layer */ float **dW, /* 'dW' at in_layer */ float *db, /* 'db' at in_layer */ int32_t n_in, /* neurons in in_layer */ int32_t n_out, /* neurons in out_layer */ int32_t nI, __bak_act_fn_t afn ) { int status = 0; // I think it might make sense to compute dW and db even if we don't // use them because of the dropout // Initialize dz to zero #pragma omp parallel for schedule(static) for ( int j = 0; j < n_in; j++ ) { // for neurons in in_layer float *dz_j = dz[j]; // RAMESH: We should compare loop with memset // RAMESH: might as well do omp simd, will not hurt #pragma omp simd for ( int i = 0; i < nI; i++ ) { dz_j[i] = 0; } } // Initialize da_prev to zero if ( da_prev != NULL ) { // avoid computing da[0], which is NULL #pragma omp parallel for schedule(static) for ( int j = 0; j < n_out; j++ ) { // for neurons in out_layer float *da_prev_j = da_prev[j]; // RAMESH: Same comments as earlier, // compare with memset and simd won't hurt #pragma omp simd for ( int i = 0; i < nI; i++ ) { da_prev_j[i] = 0; } } } // ----------- START - compute dz ----------- #pragma omp parallel for schedule(static) for ( int j = 0; j < n_in; j++ ) { // for neurons in in_layer int l_status = 0; if ( status < 0 ) { continue; } float *z_j = z[j]; float *da_j = da[j]; float *dz_j = dz[j]; l_status = afn(z_j, da_j, nI, dz_j); if ( l_status < 0 ) { status = -1; continue; } } cBYE(status); // ----------- STOP - compute dz ----------- // ----------- START - compute da_prev ----------- // TODO: if I enable below pragma omp instruction, // then I observe difference for few values of updated 'W' and 'b' #pragma omp parallel for schedule(static) for ( int j = 0; j < n_in; j++ ) { // for neurons in in_layer float *dz_j = dz[j]; if ( da_prev != NULL ) { // avoid computing da[0], which is NULL for ( int jprime = 0; jprime < n_out; jprime++ ) { // for neurons in out_layer float *W_jprime = W[jprime]; float *da_prev_jprime = da_prev[jprime]; status = va_times_sb_plus_vc(dz_j, W_jprime[j], da_prev_jprime, da_prev_jprime, nI); //cBYE(status) } } } // ----------- STOP - compute da_prev ----------- // ----------- START - compute dW & db ----------- #pragma omp parallel for schedule(static) for ( int j = 0; j < n_in; j++ ) { // for neurons in in_layer float sum = 0; float *dz_j = dz[j]; for ( int jprime = 0; jprime < n_out; jprime++ ) { // for neurons in out_layer sum = 0; float *a_prev_jprime = a_prev[jprime]; status = va_dot_vb(dz_j, a_prev_jprime, &sum, nI); // TODO P1 Put this status check back //cBYE(status); sum /= nI; #ifdef COUNT num_b_flops += 1; #endif dW[jprime][j] = sum; } sum = 0; #pragma omp simd reduction(+:sum) for ( int i = 0; i < nI; i++ ) { sum += dz_j[i]; #ifdef COUNT num_b_flops += 1; #endif } sum /= nI; #ifdef COUNT num_b_flops += 1; #endif db[j] = sum; } // ----------- STOP - compute dW & db ----------- BYE: return status; }
generator_spgemm_csc_bsparse.c
/****************************************************************************** ** Copyright (c) 2015-2019, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ /** * @file * This file is part of GemmCodeGenerator. * * @author Alexander Heinecke (alexander.heinecke AT mytum.de, http://www5.in.tum.de/wiki/index.php/Alexander_Heinecke,_M.Sc.,_M.Sc._with_honors) * * @section LICENSE * Copyright (c) 2012-2014, Technische Universitaet Muenchen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * <DESCRIPTION> */ #include "generator_spgemm_csc_bsparse.h" #include "generator_common.h" #include "libxsmm_main.h" #if defined(LIBXSMM_OFFLOAD_TARGET) # pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET)) #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #if defined(LIBXSMM_OFFLOAD_TARGET) # pragma offload_attribute(pop) #endif LIBXSMM_API_INTERN void libxsmm_generator_spgemm_csc_bsparse( libxsmm_generated_code* io_generated_code, const libxsmm_gemm_descriptor* i_xgemm_desc, const char* i_arch, const unsigned int* i_row_idx, const unsigned int* i_column_idx, const double* i_values ) { unsigned int l_n; unsigned int l_z; unsigned int l_column_elements; unsigned int l_flop_count = 0; char l_new_code[512]; int l_max_code_length = 511; int l_code_length = 0; LIBXSMM_UNUSED(i_values); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " unsigned int l_m = 0;\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); /* reset C if beta is zero */ if (0 != (LIBXSMM_GEMM_FLAG_BETA_0 & i_xgemm_desc->flags)) { /* Beta=0 */ l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " unsigned int l_n = 0;\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) {\n", (unsigned int)i_xgemm_desc->n); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); if ( i_xgemm_desc->m > 1 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma vector aligned\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_m = 0; l_m < %u; l_m++) { C[(l_n*%u)+l_m] = 0.0; }\n", (unsigned int)i_xgemm_desc->m, (unsigned int)i_xgemm_desc->ldc); } else { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_m = 0; l_m < %u; l_m++) { C[(l_n*%u)+l_m] = 0.0f; }\n", (unsigned int)i_xgemm_desc->m, (unsigned int)i_xgemm_desc->ldc); } libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " }\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, "\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); /* determine the correct simd pragma for each architecture */ if ( ( strcmp( i_arch, "noarch" ) == 0 ) || ( strcmp( i_arch, "wsm" ) == 0 ) || ( strcmp( i_arch, "snb" ) == 0 ) || ( strcmp( i_arch, "hsw" ) == 0 ) ) { if ( i_xgemm_desc->m > 7 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(8)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } else if ( i_xgemm_desc->m > 3 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(4)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } else if ( i_xgemm_desc->m > 1 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(2)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } else {} if ( (i_xgemm_desc->m > 1) && ((LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0) && ((LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0) ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma vector aligned\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } } else if ( ( strcmp( i_arch, "knl" ) == 0 ) || ( strcmp( i_arch, "skx" ) == 0 ) || ( strcmp( i_arch, "clx" ) == 0 ) || ( strcmp( i_arch, "cpx" ) == 0 ) ) { if ( (i_xgemm_desc->m > 1) && ((LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0) && ((LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0) ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(32)\n #pragma vector aligned\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_ARCH ); return; } /* generate the actuel kernel */ l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_m = 0; l_m < %u; l_m++) {\n", (unsigned int)i_xgemm_desc->m); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); for ( l_n = 0; l_n < (unsigned int)i_xgemm_desc->n; l_n++ ) { l_column_elements = i_column_idx[l_n+1] - i_column_idx[l_n]; for ( l_z = 0; l_z < l_column_elements; l_z++ ) { /* check k such that we just use rows which actually need to be multiplied */ if ( i_row_idx[i_column_idx[l_n] + l_z] < (unsigned int)i_xgemm_desc->k ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " C[%u+l_m] += A[%u+l_m] * B[%u];\n", l_n * i_xgemm_desc->ldc, i_row_idx[i_column_idx[l_n] + l_z]*i_xgemm_desc->lda, i_column_idx[l_n] + l_z); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_flop_count += 2; } } } l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " }\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); /* add flop counter */ l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, "\n#ifndef NDEBUG\n#ifdef _OPENMP\n#pragma omp atomic\n#endif\nlibxsmm_num_total_flops += %u;\n#endif\n", l_flop_count * (unsigned int)i_xgemm_desc->m); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); }
3d7pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 24; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,12);t1++) { lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24)); ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(24*t2-Nz-20,24));t3<=min(min(min(floord(Nt+Ny-4,24),floord(12*t1+Ny+21,24)),floord(24*t2+Ny+20,24)),floord(24*t1-24*t2+Nz+Ny+19,24));t3++) { for (t4=max(max(max(0,ceild(3*t1-255,256)),ceild(24*t2-Nz-1020,1024)),ceild(24*t3-Ny-1020,1024));t4<=min(min(min(min(floord(Nt+Nx-4,1024),floord(12*t1+Nx+21,1024)),floord(24*t2+Nx+20,1024)),floord(24*t3+Nx+20,1024)),floord(24*t1-24*t2+Nz+Nx+19,1024));t4++) { for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),24*t3-Ny+2),1024*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),24*t3+22),1024*t4+1022),24*t1-24*t2+Nz+21);t5++) { for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(24*t3,t5+1);t7<=min(24*t3+23,t5+Ny-2);t7++) { lbv=max(1024*t4,t5+1); ubv=min(1024*t4+1023,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
grid.c
#include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <float.h> #include <fcntl.h> #include <stdint.h> #include <complex.h> #include <fftw3.h> #include "grid.h" // Assume all uvw are zero. This eliminates all coordinate // calculations and grids only into the middle. //#define ASSUME_UVW_0 static const double c = 299792458.0; inline static double uvw_lambda(struct bl_data *bl_data, int time, int freq, int uvw) { return bl_data->uvw[3*time+uvw] * bl_data->freq[freq] / c; } inline static int coord(int grid_size, double theta, struct bl_data *bl_data, int time, int freq) { #ifdef ASSUME_UVW_0 int x = 0, y = 0; #else int x = (int)floor(theta * uvw_lambda(bl_data, time, freq, 0) + .5); int y = (int)floor(theta * uvw_lambda(bl_data, time, freq, 1) + .5); #endif return (y+grid_size/2) * grid_size + (x+grid_size/2); } inline static void frac_coord(int grid_size, int kernel_size, int oversample, double theta, struct bl_data *bl_data, int time, int freq, double d_u, double d_v, int *grid_offset, int *sub_offset) { #ifdef ASSUME_UVW_0 double x = 0, y = 0; #else double x = theta * (uvw_lambda(bl_data, time, freq, 0) - d_u); double y = theta * (uvw_lambda(bl_data, time, freq, 1) - d_v); #endif int flx = (int)floor(x + .5 / oversample); int fly = (int)floor(y + .5 / oversample); int xf = (int)floor((x - (double)flx) * oversample + .5); int yf = (int)floor((y - (double)fly) * oversample + .5); *grid_offset = (fly+grid_size/2-kernel_size/2)*grid_size + (flx+grid_size/2-kernel_size/2); *sub_offset = kernel_size * kernel_size * (yf*oversample + xf); } void weight(unsigned int *wgrid, int grid_size, double theta, struct vis_data *vis) { // Simple uniform weighting int bl, time, freq; memset(wgrid, 0, grid_size * grid_size * sizeof(unsigned int)); for (bl = 0; bl < vis->bl_count; bl++) { for (time = 0; time < vis->bl[bl].time_count; time++) { for (freq = 0; freq < vis->bl[bl].freq_count; freq++) { wgrid[coord(grid_size, theta, &vis->bl[bl], time, freq)]++; } } } for (bl = 0; bl < vis->bl_count; bl++) { for (time = 0; time < vis->bl[bl].time_count; time++) { for (freq = 0; freq < vis->bl[bl].freq_count; freq++) { vis->bl[bl].vis[time*vis->bl[bl].freq_count + freq] /= wgrid[coord(grid_size, theta, &vis->bl[bl], time, freq)]; } } } } uint64_t grid_simple(double complex *uvgrid, int grid_size, double theta, struct vis_data *vis) { uint64_t flops = 0; int bl, time, freq; for (bl = 0; bl < vis->bl_count; bl++) { for (time = 0; time < vis->bl[bl].time_count; time++) { for (freq = 0; freq < vis->bl[bl].freq_count; freq++) { uvgrid[coord(grid_size, theta, &vis->bl[bl], time, freq)] += vis->bl[bl].vis[time*vis->bl[bl].freq_count + freq]; flops += 2; } } } return flops; } //If the W-Kernels vary in size. #ifdef VAR_W_KERN inline static uint64_t w_project(double complex *uvgrid, int grid_size, double theta, int time, int freq, double d_u, double d_v, double d_w, struct bl_data *bl, struct var_w_kernel_data *wkern) { // Determine w-kernel to use double w = uvw_lambda(bl, time, freq, 2) - d_w; int w_plane = (int)floor((w - wkern->w_min) / wkern->w_step + .5); double complex *wk = wkern->kern_by_w[w_plane].data; // Get visibility double complex v = bl->vis[time*bl->freq_count+freq]; // Copy kernel int x, y; // Calculate grid and sub-grid coordinates int grid_offset, sub_offset; frac_coord(grid_size, wkern->kern_by_w[w_plane].size_x, wkern->kern_by_w[w_plane].oversampling, theta, bl, time, freq, d_u, d_v, &grid_offset, &sub_offset); int wkern_size = wkern->kern_by_w[w_plane].size_x; assert(wkern->kern_by_w[w_plane].size_y == wkern_size); for (y = 0; y < wkern_size; y++) { for (x = 0; x < wkern_size; x++) { uvgrid[grid_offset + y*grid_size + x] += v * conj(wk[sub_offset + y*wkern_size + x]); } } return 8 * wkern_size * wkern_size; } uint64_t grid_wprojection(double complex *uvgrid, int grid_size, double theta, struct vis_data *vis, struct var_w_kernel_data *wkern) { uint64_t flops = 0; int bl, time, freq; for (bl = 0; bl < vis->bl_count; bl++) { for (time = 0; time < vis->bl[bl].time_count; time++) { for (freq = 0; freq < vis->bl[bl].freq_count; freq++) { flops += w_project(uvgrid, grid_size, theta, time, freq, 0, 0, 0, &vis->bl[bl], wkern); } } } return flops; } #else inline static uint64_t w_project(double complex *uvgrid, int grid_size, double theta, int time, int freq, double d_u, double d_v, double d_w, struct bl_data *bl, struct w_kernel_data *wkern) { // Calculate grid and sub-grid coordinates int grid_offset, sub_offset; frac_coord(grid_size, wkern->size_x, wkern->oversampling, theta, bl, time, freq, d_u, d_v, &grid_offset, &sub_offset); // Determine w-kernel to use double w = uvw_lambda(bl, time, freq, 2) - d_w; int w_plane = (int)floor((w - wkern->w_min) / wkern->w_step + .5); double complex *wk = wkern->kern_by_w[w_plane].data; // Get visibility double complex v = bl->vis[time*bl->freq_count+freq]; // Copy kernel int x, y; int wkern_size = wkern->size_x; assert(wkern->size_y == wkern_size); for (y = 0; y < wkern_size; y++) { for (x = 0; x < wkern_size; x++) { uvgrid[grid_offset + y*grid_size + x] += v * conj(wk[sub_offset + y*wkern_size + x]); } } return 8 * wkern->size_x * wkern->size_y; } uint64_t grid_wprojection(double complex *uvgrid, int grid_size, double theta, struct vis_data *vis, struct w_kernel_data *wkern) { uint64_t flops = 0; int bl, time, freq; for (bl = 0; bl < vis->bl_count; bl++) { for (time = 0; time < vis->bl[bl].time_count; time++) { for (freq = 0; freq < vis->bl[bl].freq_count; freq++) { flops += w_project(uvgrid, grid_size, theta, time, freq, 0, 0, 0, &vis->bl[bl], wkern); } } } return flops; } #endif static inline double lambda_min(struct bl_data *bl_data, double u) { return u * (u < 0 ? bl_data->f_max : bl_data->f_min) / c; } static inline double lambda_max(struct bl_data *bl_data, double u) { return u * (u < 0 ? bl_data->f_min : bl_data->f_max) / c; } #ifdef VAR_W_KERN static uint64_t w_project_bin(double complex *subgrid, int subgrid_size, double theta, struct bl_data **bl_bin, int bl_count, struct var_w_kernel_data *wkern, double u_min, double u_max, double u_mid, double v_min, double v_max, double v_mid, double w_min, double w_max, double w_mid) { #else static uint64_t w_project_bin(double complex *subgrid, int subgrid_size, double theta, struct bl_data **bl_bin, int bl_count, struct w_kernel_data *wkern, double u_min, double u_max, double u_mid, double v_min, double v_max, double v_mid, double w_min, double w_max, double w_mid) { #endif int bl, time, freq; uint64_t all_flops = 0; for (bl = 0; bl < bl_count; bl++) { struct bl_data *bl_data = bl_bin[bl]; // Baseline cannot possible overlap uvw bin? if (lambda_max(bl_data, bl_data->u_max) < u_min || lambda_min(bl_data, bl_data->u_min) >= u_max || lambda_max(bl_data, bl_data->v_max) < v_min || lambda_min(bl_data, bl_data->v_min) >= v_max || lambda_max(bl_data, bl_data->w_max) < w_min || lambda_min(bl_data, bl_data->w_min) >= w_max) { // Skip continue; } // Then go through individual visibilities uint64_t flops = 0; for (time = 0; time < bl_data->time_count; time++) { for (freq = 0; freq < bl_data->freq_count; freq++) { // Fine bounds check double u = uvw_lambda(bl_data, time, freq, 0); double v = uvw_lambda(bl_data, time, freq, 1); double w = uvw_lambda(bl_data, time, freq, 2); if (u < u_min || u >= u_max || v < v_min || v >= v_max || w < w_min || w >= w_max) { continue; } // w-project the last mile (TODO: special case for wp=0) flops += w_project(subgrid, subgrid_size, theta, time, freq, u_mid, v_mid, w_mid, bl_data, wkern); } } bl_data->flops += flops; all_flops += flops; } return all_flops; } // How is this not in the standard library somewhere? // (stolen from Stack Overflow) inline double complex cipow(double complex base, int exp) { double complex result = 1; if (exp < 0) return 1 / cipow(base, -exp); if (exp == 1) return base; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } uint64_t grid_wtowers(double complex *uvgrid, int grid_size, double theta, struct vis_data *vis, struct w_kernel_data *wkern, int subgrid_size, int subgrid_margin, double wincrement) { assert(subgrid_margin >= wkern->size_x); assert(wkern->size_x == wkern->size_y); assert(subgrid_size % 2 == 0 && subgrid_margin % 2 == 0); // Not sure whether it works otherwise // Make transfer Fresnel pattern int subgrid_mem_size = sizeof(double complex) * subgrid_size * subgrid_size; double complex *wtransfer = (double complex *)malloc(subgrid_mem_size); int x, y; for (y = 0; y < subgrid_size; y++) { for (x = 0; x < subgrid_size; x++) { double l = theta * (double)(x - subgrid_size / 2) / subgrid_size; double m = theta * (double)(y - subgrid_size / 2) / subgrid_size; double ph = wincrement * (1 - sqrt(1 - l*l - m*m)); wtransfer[y * subgrid_size + x] = cexp(2 * M_PI * I * ph); } } // Move zero image position to (0,0). This is going to be the // convention for subimg, it simplifies the (frequent!) FFTs. fft_shift(wtransfer, subgrid_size); // Make sub-grids in grid and image space int chunk_size = subgrid_size - subgrid_margin; int chunk_count = grid_size / chunk_size + 1; // Make FFT plan. NOT THREAD SAFE. fftw_plan fft_plan, ifft_plan; #ifdef OMP_TOWERS int cym, cxm; //If we parallelise this we need all the subgrids seperate. Not sure of effect on cache.. double complex **subgrids = (double complex **)malloc((grid_size / chunk_size + 1)*(grid_size / chunk_size + 1) * sizeof(double complex)); for(cym=0 ; cym < chunk_count; cym++){ for(cxm = 0; cxm < chunk_count; cxm++){ *(subgrids + cym * chunk_count + cxm) = (double complex *)malloc(subgrid_mem_size); } } double complex **subimgs = (double complex **)malloc((grid_size / chunk_size + 1)*(grid_size / chunk_size + 1) * sizeof(double complex)); for(cym=0 ; cym < chunk_count; cym++){ for(cxm = 0; cxm < chunk_count; cxm++){ *(subimgs + cym * chunk_count + cxm) = (double complex *)malloc(subgrid_mem_size); } } fft_plan = fftw_plan_dft_2d(subgrid_size, subgrid_size, *(subimgs), *(subimgs), -1, FFTW_MEASURE); ifft_plan = fftw_plan_dft_2d(subgrid_size, subgrid_size, *(subgrids), *(subgrids), 1, FFTW_MEASURE); #else double complex *subgrid = (double complex *)malloc(subgrid_mem_size); double complex *subimg = (double complex *)malloc(subgrid_mem_size); fft_plan = fftw_plan_dft_2d(subgrid_size, subgrid_size, subimg, subimg, -1, FFTW_MEASURE); ifft_plan = fftw_plan_dft_2d(subgrid_size, subgrid_size, subgrid, subgrid, +1, FFTW_MEASURE); #endif // Determine bounds in w double vis_w_min = 0, vis_w_max = 0; int bl; for (bl = 0; bl < vis->bl_count; bl++) { double w_min = lambda_min(&vis->bl[bl], vis->bl[bl].w_min); double w_max = lambda_max(&vis->bl[bl], vis->bl[bl].w_max); if (w_min < vis_w_min) { vis_w_min = w_min; } if (w_max > vis_w_max) { vis_w_max = w_max; } } int wp_min = (int) floor(vis_w_min / wincrement + 0.5); int wp_max = (int) floor(vis_w_max / wincrement + 0.5); // Bin in uv int bins_size = sizeof(void *) * chunk_count * chunk_count; struct bl_data ***bins = (struct bl_data ***)malloc(bins_size); memset(bins, 0, bins_size); int bins_count_size = sizeof(int) * chunk_count * chunk_count; int *bins_count = (int *)malloc(bins_count_size); memset(bins_count, 0, bins_count_size); for (bl = 0; bl < vis->bl_count; bl++) { // Determine bounds (could be more precise, future work...) struct bl_data *bl_data = &vis->bl[bl]; double u_min = lambda_min(bl_data, bl_data->u_min); double u_max = lambda_max(bl_data, bl_data->u_max); double v_min = lambda_min(bl_data, bl_data->v_min); double v_max = lambda_max(bl_data, bl_data->v_max); // Determine first/last overlapping grid chunks int cx0 = (floor(u_min * theta + 0.5) + grid_size/2) / chunk_size; int cx1 = (floor(u_max * theta + 0.5) + grid_size/2) / chunk_size; int cy0 = (floor(v_min * theta + 0.5) + grid_size/2) / chunk_size; int cy1 = (floor(v_max * theta + 0.5) + grid_size/2) / chunk_size; int cy, cx; for (cy = cy0; cy <= cy1; cy++) { for (cx = cx0; cx <= cx1; cx++) { // Lazy dynamically sized vector int bcount = ++bins_count[cy*chunk_count + cx]; bins[cy*chunk_count + cx] = (struct bl_data **)realloc(bins[cy*chunk_count + cx], sizeof(void *) * bcount); bins[cy*chunk_count + cx][bcount-1] = bl_data; } } } //Some debug information to help me parallelise.. printf("Chunks %d",grid_size/chunk_size + 1); //# pragma omp paralell for // Grid chunks uint64_t flops = 0; int chunk; int cy, cx; #ifdef OMP_TOWERS #pragma omp parallel for schedule(dynamic) private(cy,cx) #endif for (chunk = 0; chunk < (grid_size / chunk_size + 1) * (grid_size / chunk_size + 1); chunk++) { #ifdef OMP_TOWERS double complex *subgrid = *(subgrids + chunk); double complex *subimg = *(subimgs + chunk); #endif // Get our baselines bin struct bl_data **bl_bin = bins[chunk]; int bl_count = bins_count[chunk]; if (bl_count == 0) { continue; } //To get around one-dimension loop arithmetic, this step needs a bit of a fudge. int cx = chunk % chunk_count; int cy = floor(chunk / chunk_count); // Determine tower base int x_min = chunk_size*cx - grid_size/2; int y_min = chunk_size*cy - grid_size/2; double u_min = ((double)x_min - 0.5) / theta; double v_min = ((double)y_min - 0.5) / theta; double u_max = u_min + chunk_size / theta; double v_max = v_min + chunk_size / theta; // Midpoint in uvw. Important to note that for even-sized // FFTs (likely what we are using!) this is slightly // off-centre, so u_mid != (u_min + u_max) / 2. double u_mid = (double)(x_min + chunk_size / 2) / theta; double v_mid = (double)(y_min + chunk_size / 2) / theta; // Clean subgrid memset(subgrid, 0, subgrid_mem_size); memset(subimg, 0, subgrid_mem_size); // Go through w-planes int have_vis = 0; int last_wp = wp_min; for (int wp = wp_min; wp <= wp_max; wp++) { double w_mid = (double)wp * wincrement; double w_min = ((double)wp - 0.5) * wincrement; double w_max = ((double)wp + 0.5) * wincrement; // Now grid all baselines for this uvw bin uint64_t bin_flops = w_project_bin(subgrid, subgrid_size, theta, bl_bin, bl_count, wkern, u_min, u_max, u_mid, v_min, v_max, v_mid, w_min, w_max, w_mid); // Skip the rest if we found no visibilities. if (bin_flops == 0) { continue; } flops += bin_flops; have_vis = 1; fftw_execute_dft(ifft_plan, subgrid, subgrid); // Bring image sum to our w-plane and add new data, // clean subgrid for next w-plane. for (y = 0; y< subgrid_size; y++) { for(x = 0; x < subgrid_size; x++){ double complex wtrans = cipow(wtransfer[y*subgrid_size + x], wp-last_wp); subimg[y*subgrid_size + x] = wtrans * subimg[y*subgrid_size + x] + subgrid[y*subgrid_size + x]; subgrid[y*subgrid_size + x] = 0; } } last_wp = wp; } // No visibilities? Skip if (!have_vis) { continue; } // Transfer to w=0 plane if (last_wp != 0) { for (y = 0; y < subgrid_size; y++) { for (x = 0; x < subgrid_size; x++) { subimg[y * subgrid_size + x] /= cipow(wtransfer[y*subgrid_size + x], last_wp); } } } // FFT fftw_execute_dft(fft_plan, subimg, subimg); // Add to main grid, ignoring margins, which might be over // bounds (should not actually happen, but let's be safe) int x0 = x_min - subgrid_margin/2, x1 = x0 + subgrid_size; int y0 = y_min - subgrid_margin/2, y1 = y0 + subgrid_size; if (x0 < -grid_size/2) { x0 = -grid_size/2; } if (y0 < -grid_size/2) { y0 = -grid_size/2; } if (x1 > grid_size/2) { x1 = grid_size/2; } if (y1 > grid_size/2) { y1 = grid_size/2; } double complex *uvgrid_mid = uvgrid + (grid_size+1)*grid_size/2; int sg_norm = subgrid_size * subgrid_size; for (y = y0; y < y1; y++) { for (x = x0; x < x1; x++) { uvgrid_mid[x + y*grid_size] += (subimg[(x-x_min+subgrid_margin/2) + (y-y_min+subgrid_margin/2)*subgrid_size] / sg_norm); } } } #ifndef OMP_TOWERS // Check that all visibilities were actually gridded for (bl = 0; bl < vis->bl_count; bl++) { if (vis->bl[bl].flops != 8 * wkern->size_x * wkern->size_x * vis->bl[bl].time_count * vis->bl[bl].freq_count) { printf("!!! bl %d-%d: %lu flops, %d expected !!!\n", vis->bl[bl].antenna1, vis->bl[bl].antenna2, vis->bl[bl].flops, 8 * wkern->size_x * wkern->size_x * vis->bl[bl].time_count * vis->bl[bl].freq_count); } } #endif // Clean up fftw_destroy_plan(fft_plan); fftw_destroy_plan(ifft_plan); #ifdef OMP_TOWERS for (cy = 0; cy < grid_size / chunk_size +1; cy++){ for (cx = 0; cx < grid_size / chunk_size +1; cx++){ free(*(subgrids + cy*chunk_count +cx)); free(*(subimgs + cy*chunk_count + cx)); } } #else free(subgrid); free(subimg); #endif for (cy = 0; cy < grid_size / chunk_size + 1; cy++) { for (cx = 0; cx < grid_size / chunk_size + 1; cx++) { free(bins[cy*chunk_count + cx]); } } free(bins); free(bins_count); return flops; } void convolve_aw_kernels(struct bl_data *bl, struct w_kernel_data *wkern, struct a_kernel_data *akern) { assert(wkern->size_x == akern->size_x); assert(wkern->size_y == akern->size_y); int size_x = wkern->size_x, size_y = wkern->size_y; int ov = wkern->oversampling; // We assume that every time channel has their own w-kernel const int awkern_count = bl->time_count * akern->freq_count; const int awkern_size = size_x * size_y * ov * ov; bl->awkern = (double complex *)malloc(awkern_count * awkern_size * sizeof(double complex)); int time, freq; for (time = 0; time < bl->time_count; time++) { for (freq = 0; freq < akern->freq_count; freq++) { double t = bl->time[time]; int atime = (int)floor((t - akern->t_min) / akern->t_step + .5); int a1i = bl->antenna1 * akern->time_count * akern->freq_count + atime * akern->freq_count + freq; int a2i = bl->antenna2 * akern->time_count * akern->freq_count + atime * akern->freq_count + freq; struct a_kernel *a1k = &akern->kern_by_atf[a1i]; struct a_kernel *a2k = &akern->kern_by_atf[a2i]; double w = bl->uvw[time*3+2] * a1k->freq / c; int w_plane = (int)floor((w - wkern->w_min) / wkern->w_step + .5); struct w_kernel *wk = &wkern->kern_by_w[w_plane]; // Here is where we normally would convolve the kernel - // but it doesn't matter for this test, so we just copy // the w-kernel. memcpy(&bl->awkern[(time * akern->freq_count + freq) * awkern_size], wk->data, awkern_size * sizeof(double complex)); } } } uint64_t grid_awprojection(double complex *uvgrid, int grid_size, double theta, struct vis_data *vis, struct w_kernel_data *wkern, struct a_kernel_data *akern, int bl_min, int bl_max) { // Note that we require awkern to be set on all baselines // processed here! uint64_t flops = 0; int bl, time, freq; for (bl = bl_min; bl < bl_max; bl++) { const int awkern_size = akern->size_x * akern->size_y * wkern->oversampling * wkern->oversampling; const struct bl_data *pbl = &vis->bl[bl]; for (time = 0; time < pbl->time_count; time++) { for (freq = 0; freq < pbl->freq_count; freq++) { // Calculate grid and sub-grid coordinates int grid_offset, sub_offset; frac_coord(grid_size, wkern->size_x, wkern->oversampling, theta, &vis->bl[bl], time, freq, 0, 0, &grid_offset, &sub_offset); // Determine kernel frequency, get kernel int afreq = (int)floor((pbl->freq[freq] - akern->f_min) / akern->f_step + .5); double complex *awk = &pbl->awkern[ (time * akern->freq_count + afreq) * awkern_size]; // Get visibility double complex v = vis->bl[bl].vis[time*vis->bl[bl].freq_count+freq]; int x, y; for (y = 0; y < wkern->size_y; y++) { for (x = 0; x < wkern->size_x; x++) { uvgrid[grid_offset + y*grid_size + x] += v * conj(awk[sub_offset + y*wkern->size_x + x]); } } flops += 8 * wkern->size_x * wkern->size_y; } } } return flops; } void make_hermitian(double complex *uvgrid, int grid_size) { // Determine start index. For even-sized grids, the zero frequency // is at grid_size/2, so things are off by one. complex double *p0; if (grid_size % 2 == 0) { p0 = uvgrid + grid_size + 1; } else { p0 = uvgrid; } complex double *p1 = uvgrid + grid_size * grid_size - 1; // Now simply add cells from the other side of the grid while(p0 < p1) { double complex g0 = *p0; *p0++ += conj(*p1); *p1-- += conj(g0); } // Should end up exactly on the zero frequency assert( p0 == p1 && p0 == uvgrid + (grid_size+1) * (grid_size/2) ); *p0 += conj(*p0); } void fft_shift(double complex *uvgrid, int grid_size) { // Shift the FFT assert(grid_size % 2 == 0); int x, y; for (y = 0; y < grid_size; y++) { for (x = 0; x < grid_size/2; x++) { int ix0 = y * grid_size + x; int ix1 = (ix0 + (grid_size+1) * (grid_size/2)) % (grid_size*grid_size); double complex temp = uvgrid[ix0]; uvgrid[ix0] = uvgrid[ix1]; uvgrid[ix1] = temp; } } }
serialized.c
// RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s // REQUIRES: ompt // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7 #define TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN #include "callback.h" #include <omp.h> #include <math.h> int main() { omp_set_nested(0); print_frame(0); #pragma omp parallel num_threads(2) { print_frame_from_outlined_fn(1); print_ids(0); print_ids(1); print_frame(0); #pragma omp master { print_ids(0); void *creator_frame = get_frame_address(0); int t = (int)sin(0.1); #pragma omp task if (t) { void *task_frame = get_frame_address(0); if (creator_frame == task_frame) { // Assume this code was inlined which the compiler is allowed to do. print_frame(0); } else { // The exit frame must be our parent! print_frame_from_outlined_fn(1); } print_ids(0); print_ids(1); print_ids(2); } print_fuzzy_address(1); print_ids(0); } print_ids(0); } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // make sure initial data pointers are null // CHECK-NOT: 0: new_task_data initially not null // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_initial_task_begin: parallel_id={{[0-9]+}} // CHECK-SAME: task_id={{[0-9]+}}, actual_parallelism=1, index=1, flags=1 // CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address(0) // CHECK-SAME: =[[MAIN_REENTER:0x[0-f]+]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin // CHECK-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]] // CHECK-SAME: parent_task_frame.exit=[[NULL]] // CHECK-SAME: parent_task_frame.reenter=0x{{[0-f]+}} // CHECK-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=2 // CHECK-SAME: codeptr_ra=0x{{[0-f]+}}, invoker={{[0-9]+}} // nested parallel masters // CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin // CHECK-SAME: parallel_id=[[PARALLEL_ID]] // CHECK-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address // CHECK-SAME: =[[EXIT:0x[0-f]+]] // CHECK: {{^}}[[MASTER_ID]]: task level 0 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=[[NULL]] // CHECK: {{^}}[[MASTER_ID]]: task level 1 // CHECK-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]] // CHECK-SAME: task_id=[[PARENT_TASK_ID]], // CHECK-SAME: exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address(0)=[[REENTER:0x[0-f]+]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_create // CHECK-SAME: parent_task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: parent_task_frame.exit=[[EXIT]] // CHECK-SAME: parent_task_frame.reenter=0x{{[0-f]+}} // CHECK-SAME: new_task_id=[[TASK_ID:[0-9]+]] // CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_schedule: // CHECK-SAME: first_task_id=[[IMPLICIT_TASK_ID]], second_task_id=[[TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address // CHECK-SAME: =[[TASK_EXIT:0x[0-f]+]] // CHECK: {{^}}[[MASTER_ID]]: task level 0 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[TASK_ID]] // CHECK-SAME: exit_frame=[[TASK_EXIT]], reenter_frame=[[NULL]] // CHECK: {{^}}[[MASTER_ID]]: task level 1 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=0x{{[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: task level 2 // CHECK-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]] // CHECK-SAME: task_id=[[PARENT_TASK_ID]] // CHECK-SAME: exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_schedule // CHECK-SAME: first_task_id=[[TASK_ID]], second_task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_end: task_id=[[TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: task level 0 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=[[NULL]] // implicit barrier parallel // CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: task level 0 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: exit_frame=[[NULL]], reenter_frame=[[NULL]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_end // parallel_id is 0 because the region ended in the barrier! // CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end // CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin // CHECK-SAME: parallel_id=[[PARALLEL_ID]] // CHECK-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address // CHECK-SAME: =[[EXIT:0x[0-f]+]] // CHECK: {{^}}[[THREAD_ID]]: task level 0 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=[[NULL]] // CHECK: {{^}}[[THREAD_ID]]: task level 1 // CHECK-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]] // CHECK-SAME: task_id=[[PARENT_TASK_ID]] // CHECK-SAME: exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address(0)={{0x[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[THREAD_ID]]: task level 0 // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK-SAME: exit_frame=[[NULL]], reenter_frame=[[NULL]] // parallel_id is 0 because the region ended in the barrier! // CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_end // CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] return 0; }
main.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #include "omp.h" #include "functions.h" int main (int argc, char **argv) { int Nthreads = 1; omp_set_num_threads(Nthreads); //seed value for the randomizer double seed = clock(); //this will make your program run differently everytime //double seed = 0; //uncomment this and your program will behave the same everytime it's run srand(seed); //declare storage for an ElGamal cryptosytem unsigned int p, g, h, x; //begin with rank 0 getting user's input unsigned int n; printf("Enter a number of bits: "); fflush(stdout); char status = scanf("%u",&n); //make sure the input makes sense if ((n<9)||(n>31)) {//Updated bounds. 8 is no good (need to encode chars) printf("Unsupported bit size.\n"); return 0; } printf("\n"); //setup an ElGamal cryptosystem setupElGamal(n,&p,&g,&h,&x); int bufferSize = 1024; unsigned char *message = (unsigned char *) malloc(bufferSize*sizeof(unsigned char)); //populate the string with a message strcpy(message, "Hello, this is the message as a string."); printf("Message = \"%s\"\n", message); /* Q1.1 Finish this line */ unsigned int charsPerInt = (n-1)/8; padString(message, charsPerInt); printf("Padded Message = \"%s\"\n", message); unsigned int Nchars = strlen(message); unsigned int Nints = strlen(message)/charsPerInt; //storage for message as elements of Z_p unsigned int *Zmessage = (unsigned int *) malloc(Nints*sizeof(unsigned int)); //storage for extra encryption coefficient unsigned int *a = (unsigned int *) malloc(Nints*sizeof(unsigned int)); // cast the string into an unsigned int array convertStringToZ(message, Nchars, Zmessage, Nints); //Encrypt the Zmessage with the ElGamal cyrptographic system ElGamalEncrypt(Zmessage,a,Nints,p,g,h); printf("The encrypted text is: "); for (unsigned int i=0;i<Nints;i++) { printf("(%u,%u) ", Zmessage[i], a[i]); } printf("]\n"); //Decrypt the Zmessage with the ElGamal cyrptographic system ElGamalDecrypt(Zmessage,a,Nints,p,x); convertZToString(Zmessage, Nints, message, Nchars); printf("Decrypted Message = \"%s\"\n", message); printf("\n"); //Suppose we don't know the secret key. Use OpenMP threads to try and find it in parallel printf("Using %d OpenMP threads to find the secret key...\n", Nthreads); /* Q2.3 Parallelize this loop with OpenMP */ double startTime = omp_get_wtime(); unsigned int found = 0; #pragma omp parallel for shared(found) for (unsigned int i=0;i<p-1;i++) { if (found == 0 && modExp(g,i+1,p)==h) { printf("Secret key found! x = %u \n", i+1); found = 1; } } double endTime = omp_get_wtime(); double totalTime = endTime-startTime; double work = (double) p; double throughput = work/totalTime; printf("Searching all keys took %g seconds, throughput was %g values tested per second.\n", totalTime, throughput); return 0; }
frpca.c
#include "matrix_vector_functions_intel_mkl_ext.h" /*[L, ~] = lu(A) as in MATLAB*/ void LUfraction(mat *A, mat *L) { matrix_copy(L, A); int *ipiv = (int *)malloc(sizeof(int)*L->nrows); LAPACKE_dgetrf (LAPACK_COL_MAJOR, L->nrows, L->ncols, L->d, L->nrows, ipiv); int i,j; #pragma omp parallel private(i,j) { #pragma omp for for(i=0;i<L->ncols;i++) { for(j=0;j<i;j++) { L->d[i*L->nrows+j] = 0; } L->d[i*L->nrows+i] = 1; } } { for(i=L->ncols-1;i>=0;i--) { int ipi = ipiv[i]-1; for(j=0;j<L->ncols;j++) { double temp = L->d[j*L->nrows+ipi]; L->d[j*L->nrows+ipi] = L->d[j*L->nrows+i]; L->d[j*L->nrows+i] = temp; } } } free(ipiv); } /*[U, S, V] = eigSVD(A)*/ void eigSVD(mat* A, mat **U, mat **S, mat **V) { matrix_transpose_matrix_mult(A, A, *V); LAPACKE_dsyevd(LAPACK_COL_MAJOR, 'V', 'U', (*V)->ncols, (*V)->d, (*V)->ncols, (*S)->d); mat *V1 = matrix_new((*V)->ncols, (*V)->ncols); matrix_copy(V1, (*V)); int i, j; #pragma omp parallel shared(V1,S) private(i,j) { #pragma omp for for(i=0; i<V1->ncols; i++) { (*S)->d[i] = sqrt((*S)->d[i]); for(j=0; j<V1->nrows;j++) V1->d[i*V1->nrows+j] /= (*S)->d[i]; } } mat *Uc = matrix_new((*U)->nrows, (*U)->ncols); matrix_matrix_mult(A, V1, Uc); matrix_copy((*U), Uc); matrix_delete(V1); matrix_delete(Uc); } /*[U, S, V] = frSVD(A, k, p)*/ /* Parameter q should be larger than 1, and the q times pass equals to (q-2)/2 times power iteration. */ void frPCAt(mat_csr *A, mat **U, mat **S, mat **V, int k, int q) { if (q == 1) { printf("Pass parameter q should be large than 1\n!"); return; } int s = 5; mat *Q = matrix_new(A->nrows, k+s); mat *Qt = matrix_new(A->ncols, k+s); mat *SS = matrix_new(k+s, 1); mat *VV = matrix_new(k+s, k+s); if(q%2 == 0) { initialize_random_matrix(Q); csr_matrix_transpose_matrix_mult(A, Q, Qt); if(q==2) { eigSVD(Qt, &Qt, &SS, &VV); } else { LUfraction(Qt, Qt); } } else { initialize_random_matrix(Qt); } int niter = (q-1)/2, i; for(i=1;i<=niter;i++) { csr_matrix_matrix_mult(A, Qt, Q); csr_matrix_transpose_matrix_mult(A, Q, Qt); if(i==niter) { eigSVD(Qt, &Qt, &SS, &VV); } else { LUfraction(Qt, Qt); } } csr_matrix_matrix_mult(A, Qt, Q); eigSVD(Q, &Q, &SS, &VV); int inds[k]; for(i=s;i<k+s;i++) { inds[i-s] = i; } mat *VV2 = matrix_new(k+s, k); matrix_get_selected_columns(Q, inds, *U); matrix_get_selected_rows(SS, inds, *S); matrix_get_selected_columns(VV, inds, VV2); matrix_matrix_mult(Qt, VV2, (*V)); matrix_delete(Q); matrix_delete(Qt); matrix_delete(SS); matrix_delete(VV); matrix_delete(VV2); } /*[U, S, V] = frSVD(A, k, p)*/ /* Parameter q should be larger than 1, and the q times pass equals to (q-2)/2 times power iteration. */ void frPCA(mat_csr *A, mat **U, mat **S, mat **V, int k, int q) { if (q == 1) { printf("Pass parameter q should be large than 1!\n"); return; } int s = 5; mat *Q = matrix_new(A->nrows, k+s); mat *Qt = matrix_new(A->ncols, k+s); mat *UU = matrix_new(A->ncols, k+s); mat *SS = matrix_new(k+s, 1); mat *VV = matrix_new(k+s, k+s); if(q%2 == 0) { initialize_random_matrix(Qt); csr_matrix_matrix_mult(A, Qt, Q); if(q==2) { eigSVD(Q, &Q, &SS, &VV); } else { LUfraction(Q, Q); } } else { initialize_random_matrix(Q); } int niter = (q-1)/2, i; for(i=1;i<=niter;i++) { csr_matrix_transpose_matrix_mult(A, Q, Qt); csr_matrix_matrix_mult(A, Qt, Q); if(i==niter) { eigSVD(Q, &Q, &SS, &VV); } else { LUfraction(Q, Q); } } csr_matrix_transpose_matrix_mult(A, Q, Qt); eigSVD(Qt, &UU, &SS, &VV); int inds[k]; for(i=s;i<k+s;i++) { inds[i-s] = i; } mat *VV2 = matrix_new(k+s, k); matrix_get_selected_columns(UU, inds, *V); matrix_get_selected_rows(SS, inds, *S); matrix_get_selected_columns(VV, inds, VV2); matrix_matrix_mult(Q, VV2, (*U)); matrix_delete(Q); matrix_delete(Qt); matrix_delete(UU); matrix_delete(SS); matrix_delete(VV); matrix_delete(VV2); } void randQB_basic_csr(mat_csr *M, int k, int p, mat **U, mat **S, mat **V) { int m, n, i, l=k+5; m = M->nrows; n = M->ncols; mat *Q = matrix_new(m, l); mat *B = matrix_new(l, n); mat *Vt = matrix_new(l, n); mat *VV = matrix_new(n, l); mat *UU = matrix_new(l, l); mat *UUk = matrix_new(l, k); mat *SS = matrix_new(l, l); *U = matrix_new(m ,k); *V = matrix_new(n, k); *S = matrix_new(k, k); // samples mat *R, *G, *Bt; R = matrix_new(n, l); G = Q; Bt = R; initialize_random_matrix(R); csr_matrix_matrix_mult(M, R, G); QR_factorization_getQ_inplace(G); // power iteration if (p > 0) { for (i = 0; i < p; i++) { csr_matrix_transpose_matrix_mult(M, G, R); QR_factorization_getQ_inplace(R); csr_matrix_matrix_mult(M, R, G); QR_factorization_getQ_inplace(G); } } //QR_factorization_getQ_inplace(G); csr_matrix_transpose_matrix_mult(M, Q, Bt); matrix_build_transpose(B, Bt); singular_value_decomposition(B, UU, SS, Vt); matrix_build_transpose(VV, Vt); int inds[k]; for(i=0;i<k;i++) { inds[i] = i; } matrix_get_selected_columns(UU, inds, UUk); matrix_matrix_mult(Q, UUk, (*U)); matrix_get_selected_columns(VV, inds, (*V)); matrix_copy_first_k_rows_and_columns(*S, SS); matrix_delete(Q); matrix_delete(B); matrix_delete(Vt); matrix_delete(VV); matrix_delete(UU); matrix_delete(UUk); matrix_delete(SS); matrix_delete(R); }
vecAdd_deadlock.c
/****************************************************************************** * FILE: omp_bug5.c * DESCRIPTION: * Using SECTIONS, two threads initialize their own array and then add * it to the other's array, however a deadlock occurs. * AUTHOR: Blaise Barney 01/29/04 * LAST REVISED: 04/06/05 ******************************************************************************/ /** * The first thread acquires locka and then tries to get lockb before releasing * locka. Meanwhile, the second thread has acquired lockb and then tries to get * locka before releasing lockb. * Online source: * https://computing.llnl.gov/tutorials/openMP/samples/C/omp_bug5.c **/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #define N 1000000 #define PI 3.1415926535 #define DELTA .01415926535 int main (int argc, char *argv[]) { int nthreads, tid, i; float a[N], b[N]; omp_lock_t locka, lockb; /* Initialize the locks */ omp_init_lock(&locka); omp_init_lock(&lockb); /* Fork a team of threads giving them their own copies of variables */ #pragma omp parallel shared(a, b, nthreads, locka, lockb) private(tid) { /* Obtain thread number and number of threads */ tid = omp_get_thread_num(); #pragma omp master { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } printf("Thread %d starting...\n", tid); #pragma omp barrier #pragma omp sections nowait { #pragma omp section { printf("Thread %d initializing a[]\n",tid); omp_set_lock(&locka); for (i=0; i<N; i++) a[i] = i * DELTA; omp_set_lock(&lockb); printf("Thread %d adding a[] to b[]\n",tid); for (i=0; i<N; i++) b[i] += a[i]; omp_unset_lock(&lockb); omp_unset_lock(&locka); } #pragma omp section { printf("Thread %d initializing b[]\n",tid); omp_set_lock(&lockb); for (i=0; i<N; i++) b[i] = i * PI; omp_set_lock(&locka); printf("Thread %d adding b[] to a[]\n",tid); for (i=0; i<N; i++) a[i] += b[i]; omp_unset_lock(&locka); omp_unset_lock(&lockb); } } /* end of sections */ } /* end of parallel region */ }
PmlSpectralTimeStraggered.h
#pragma once #include "Grid.h" #include "FieldSolver.h" #include "Pml.h" #include "Constants.h" namespace pfc { template<GridTypes gridTypes> class PmlSpectralTimeStraggered : public PmlSpectral<gridTypes> { public: PmlSpectralTimeStraggered(SpectralFieldSolver<gridTypes>* solver, Int3 sizePML) : PmlSpectral<gridTypes>((SpectralFieldSolver<gridTypes>*)solver, sizePML), tmpFieldReal(solver->grid->numCells), tmpFieldComplex(FourierTransform::getSizeOfComplex(solver->grid->numCells)) {} virtual void updateBxSplit(); virtual void updateBySplit(); virtual void updateBzSplit(); virtual void updateExSplit(); virtual void updateEySplit(); virtual void updateEzSplit(); virtual void updateBSplit(); virtual void updateESplit(); virtual void doFirstStep(); virtual void computeTmpField(MemberOfFP3 coordK, ScalarField<complexFP>& field, double dt) {}; ScalarField<complexFP> tmpFieldComplex; ScalarField<FP> tmpFieldReal; protected: SpectralFieldSolver<gridTypes>* getFieldSolver() { return (SpectralFieldSolver<gridTypes>*)this->fieldSolver; } void updateFieldSplit(std::vector<FP>& field, double sign); }; template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateFieldSplit(std::vector<FP>& field, double sign) { #pragma omp parallel for for (int idx = 0; idx < this->numCells; ++idx) { int i = this->cellIndex[idx].x; int j = this->cellIndex[idx].y; int k = this->cellIndex[idx].z; field[idx] += sign * tmpFieldReal(i, j, k); } } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateBxSplit() { SpectralFieldSolver<gridTypes>* fs = getFieldSolver(); computeTmpField(&FP3::y, fs->complexGrid->Ez, fs->grid->dt * 0.5); updateFieldSplit(this->byx, -1); computeTmpField(&FP3::z, fs->complexGrid->Ey, fs->grid->dt * 0.5); updateFieldSplit(this->bzx, +1); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateBySplit() { SpectralFieldSolver<gridTypes>* fs = getFieldSolver(); computeTmpField(&FP3::z, fs->complexGrid->Ex, fs->grid->dt * 0.5); updateFieldSplit(this->bzy, -1); computeTmpField(&FP3::x, fs->complexGrid->Ez, fs->grid->dt * 0.5); updateFieldSplit(this->bxy, +1); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateBzSplit() { SpectralFieldSolver<gridTypes>* fs = getFieldSolver(); computeTmpField(&FP3::x, fs->complexGrid->Ey, fs->grid->dt * 0.5); updateFieldSplit(this->bxz, -1); computeTmpField(&FP3::y, fs->complexGrid->Ex, fs->grid->dt * 0.5); updateFieldSplit(this->byz, +1); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateExSplit() { SpectralFieldSolver<gridTypes>* fs = getFieldSolver(); computeTmpField(&FP3::y, fs->complexGrid->Bz, fs->grid->dt); updateFieldSplit(this->eyx, +1); computeTmpField(&FP3::z, fs->complexGrid->By, fs->grid->dt); updateFieldSplit(this->ezx, -1); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateEySplit() { SpectralFieldSolver<gridTypes>* fs = getFieldSolver(); computeTmpField(&FP3::z, fs->complexGrid->Bx, fs->grid->dt); updateFieldSplit(this->ezy, +1); computeTmpField(&FP3::x, fs->complexGrid->Bz, fs->grid->dt); updateFieldSplit(this->exy, -1); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateEzSplit() { SpectralFieldSolver<gridTypes>* fs = getFieldSolver(); computeTmpField(&FP3::x, fs->complexGrid->By, fs->grid->dt); updateFieldSplit(this->exz, +1); computeTmpField(&FP3::y, fs->complexGrid->Bx, fs->grid->dt); updateFieldSplit(this->eyz, -1); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateBSplit() { updateBxSplit(); updateBySplit(); updateBzSplit(); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::updateESplit() { updateExSplit(); updateEySplit(); updateEzSplit(); } template<GridTypes gridTypes> inline void PmlSpectralTimeStraggered<gridTypes>::doFirstStep() { updateBSplit(); updateESplit(); updateBSplit(); } }
PReLU.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/PReLU.c" #else void THNN_(PReLU_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THTensor *weight) { THTensor_(resizeAs)(output, input); int64_t nOutputPlane = THTensor_(numel)(weight); if (nOutputPlane == 1) { // handle shared parameter case real w = *THTensor_(data)(weight); TH_TENSOR_APPLY2(real, output, real, input, *output_data = (*input_data > 0) ? *input_data : w*(*input_data); ); return; } input = THTensor_(newContiguous)(input); int64_t bs = 1, ks = 1; { int64_t input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } real *output_data = THTensor_(data)(output); real *input_data = THTensor_(data)(input); real *weight_data = THTensor_(data)(weight); THIndex_t i, j, k; #pragma omp parallel for private(j,k) for (i = 0; i < bs; ++i) { real* n_input_data = input_data + i*nOutputPlane*ks; real* n_output_data = output_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { for (k = 0; k < ks; ++k) n_output_data[k] = (n_input_data[k] > 0) ? n_input_data[k] : weight_data[j] * n_input_data[k]; n_input_data += ks; n_output_data += ks; } } THTensor_(free)(input); } void THNN_(PReLU_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight) { THNN_CHECK_NELEMENT(input, gradOutput); THTensor_(resizeAs)(gradInput, input); int64_t nOutputPlane = THTensor_(numel)(weight); if (nOutputPlane == 1) { real w = THTensor_(data)(weight)[0]; TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, input, if ((*input_data) > 0) *gradInput_data = *gradOutput_data; else *gradInput_data = w * (*gradOutput_data); ); return; } input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THTensor_(newContiguous)(weight); const real *input_data = THTensor_(data)(input); const real *gradOutput_data = THTensor_(data)(gradOutput); const real *weight_data = THTensor_(data)(weight); real *gradInput_data = THTensor_(data)(gradInput); int64_t bs = 1, ks = 1; { int64_t input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } THIndex_t i, j, k; #pragma omp parallel for private(j,k) for (i = 0; i < bs; ++i) { const real *n_input_data = input_data + i*nOutputPlane*ks; const real *n_gradOutput_data = gradOutput_data + i*nOutputPlane*ks; real *n_gradInput_data = gradInput_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { real w = weight_data[j]; for (k = 0; k < ks; ++k) { if (n_input_data[k] > 0) n_gradInput_data[k] = n_gradOutput_data[k]; else n_gradInput_data[k] = n_gradOutput_data[k] * w; } n_input_data += ks; n_gradInput_data += ks; n_gradOutput_data += ks; } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } void THNN_(PReLU_accGradParameters)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THTensor *gradWeight, accreal scale_) { real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_); THNN_CHECK_NELEMENT(input, gradOutput); int64_t nOutputPlane = THTensor_(numel)(weight); if (nOutputPlane == 1) { real *gradWeight_data = THTensor_(data)(gradWeight); real sum = 0; TH_TENSOR_APPLY2(real, input, real, gradOutput, if ((*input_data) <= 0) sum += (*input_data) * (*gradOutput_data); ); gradWeight_data[0] += scale * sum; return; } THArgCheck(THTensor_(isContiguous)(gradWeight), 6, "gradWeight needs to be contiguous"); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THTensor_(newContiguous)(weight); int64_t bs = 1, ks = 1; { int64_t input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } const real *input_data = THTensor_(data)(input); const real *gradOutput_data = THTensor_(data)(gradOutput); real *gradWeight_data = THTensor_(data)(gradWeight); THIndex_t i, j, k; for (i = 0; i < bs; ++i) { const real *n_input_data = input_data + i*nOutputPlane*ks; const real *n_gradOutput_data = gradOutput_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { real sum = 0; for (k = 0; k < ks; ++k) if (n_input_data[k] <= 0) sum += n_gradOutput_data[k] * n_input_data[k]; gradWeight_data[j] += scale * sum; n_input_data += ks; n_gradOutput_data += ks; } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } #endif
GB_unop__minv_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__minv_fp64_fp64 // op(A') function: GB_unop_tran__minv_fp64_fp64 // C type: double // A type: double // cast: double cij = aij // unaryop: cij = 1./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 = 1./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] = 1./z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__minv_fp64_fp64 ( double *Cx, // Cx and Ax may be aliased const double *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = 1./z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__minv_fp64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nmt_covar_flat.c
#include "config.h" #include "utils.h" static fcomplex *product_and_transform(nmt_flatsky_info *fs,flouble *m1,flouble *m2) { flouble *m12=dftw_malloc(fs->npix*sizeof(flouble)); fs_map_product(fs,m1,m2,m12); fcomplex *cm12=dftw_malloc(fs->ny*(fs->nx/2+1)*sizeof(fcomplex)); fs_map2alm(fs,1,0,&m12,&cm12); dftw_free(m12); return cm12; } static nmt_binning_scheme_flat *nmt_bins_copy(nmt_binning_scheme_flat *b_or) { nmt_binning_scheme_flat *b=my_malloc(sizeof(nmt_binning_scheme_flat)); b->n_bands=b_or->n_bands; b->ell_0_list=my_malloc(b->n_bands*sizeof(flouble)); memcpy(b->ell_0_list,b_or->ell_0_list,b->n_bands*sizeof(flouble)); b->ell_f_list=my_malloc(b->n_bands*sizeof(flouble)); memcpy(b->ell_f_list,b_or->ell_f_list,b->n_bands*sizeof(flouble)); return b; } nmt_covar_workspace_flat *nmt_covar_workspace_flat_init(nmt_field_flat *fla1,nmt_field_flat *fla2, nmt_binning_scheme_flat *ba, nmt_field_flat *flb1,nmt_field_flat *flb2, nmt_binning_scheme_flat *bb) { int ii; if((fla1->fs->nx!=fla2->fs->nx) || (fla1->fs->ny!=fla2->fs->ny) || (fla1->fs->nx!=flb1->fs->nx) || (fla1->fs->ny!=flb1->fs->ny) || (fla1->fs->nx!=flb2->fs->nx) || (fla1->fs->ny!=flb2->fs->ny)) report_error(NMT_ERROR_COVAR,"Can't compute covariance for fields with different resolutions\n"); nmt_flatsky_info *fs=fla1->fs; if(ba->n_bands!=bb->n_bands) report_error(NMT_ERROR_COVAR,"Can't compute covariance for different binning schemes\n"); nmt_covar_workspace_flat *cw=my_malloc(sizeof(nmt_covar_workspace_flat)); cw->bin=nmt_bins_copy(ba); cw->xi00_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi00_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi02_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi02_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi22p_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi22p_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi22m_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); cw->xi22m_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); for(ii=0;ii<cw->bin->n_bands;ii++) { cw->xi00_1122[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi00_1221[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi02_1122[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi02_1221[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi22p_1122[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi22p_1221[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi22m_1122[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); cw->xi22m_1221[ii]=my_calloc(cw->bin->n_bands,sizeof(flouble)); } int *n_cells=my_calloc(cw->bin->n_bands,sizeof(int)); //Multiply masks and Fourier-transform fcomplex *cm_a1b1=product_and_transform(fs,fla1->mask,flb1->mask); fcomplex *cm_a1b2=product_and_transform(fs,fla1->mask,flb2->mask); fcomplex *cm_a2b1=product_and_transform(fs,fla2->mask,flb1->mask); fcomplex *cm_a2b2=product_and_transform(fs,fla2->mask,flb2->mask); //Compute squared-mask power spectra int *i_band,*i_band_nocut; flouble *cl_mask_1122=my_malloc(fs->npix*sizeof(double)); flouble *cl_mask_1221=my_malloc(fs->npix*sizeof(double)); flouble *cosarr=dftw_malloc(fs->npix*sizeof(double)); flouble *sinarr=dftw_malloc(fs->npix*sizeof(double)); i_band=my_malloc(fs->npix*sizeof(int)); i_band_nocut=my_malloc(fs->npix*sizeof(int)); #pragma omp parallel default(none) \ shared(cw,fs,cm_a1b1,cm_a1b2,cm_a2b1,cm_a2b2,n_cells) \ shared(i_band_nocut,i_band,cl_mask_1122,cl_mask_1221) \ shared(cosarr,sinarr) { flouble dkx=2*M_PI/fs->lx; flouble dky=2*M_PI/fs->ly; int *n_cells_thr=my_calloc(cw->bin->n_bands,sizeof(int)); int iy1,ix1; #pragma omp for for(iy1=0;iy1<fs->ny;iy1++) { flouble ky; int ik=0; if(2*iy1<=fs->ny) ky=iy1*dky; else ky=-(fs->ny-iy1)*dky; for(ix1=0;ix1<fs->nx;ix1++) { flouble kx,kmod,c,s; int ix_here,index_here,index; index=ix1+fs->nx*iy1; if(2*ix1<=fs->nx) { kx=ix1*dkx; ix_here=ix1; } else { kx=-(fs->nx-ix1)*dkx; ix_here=fs->nx-ix1; } index_here=ix_here+(fs->nx/2+1)*iy1; cl_mask_1122[index]=(creal(cm_a1b1[index_here])*creal(cm_a2b2[index_here])+ cimag(cm_a1b1[index_here])*cimag(cm_a2b2[index_here])); cl_mask_1221[index]=(creal(cm_a1b2[index_here])*creal(cm_a2b1[index_here])+ cimag(cm_a1b2[index_here])*cimag(cm_a2b1[index_here])); kmod=sqrt(kx*kx+ky*ky); ik=nmt_bins_flat_search_fast(cw->bin,kmod,ik); if(ik>=0) { i_band[index]=ik; n_cells_thr[ik]++; } else i_band[index]=-1; i_band_nocut[index]=ik; if(kmod>0) { c=kx/kmod; s=ky/kmod; } else { c=1.; s=0.; } cosarr[index]=c*c-s*s; sinarr[index]=2*s*c; } } //end omp for #pragma omp critical { for(iy1=0;iy1<cw->bin->n_bands;iy1++) n_cells[iy1]+=n_cells_thr[iy1]; } //end omp critical free(n_cells_thr); } //end omp parallel dftw_free(cm_a1b1); dftw_free(cm_a1b2); dftw_free(cm_a2b1); dftw_free(cm_a2b2); //Compute Xis #pragma omp parallel default(none) \ shared(fs,i_band,cw,cl_mask_1122,cl_mask_1221) \ shared(cosarr,sinarr) { int iy1,ix1,ix2,iy2; flouble **xi00_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi00_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi02_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi02_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi22p_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi22p_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi22m_1122=my_malloc(cw->bin->n_bands*sizeof(flouble *)); flouble **xi22m_1221=my_malloc(cw->bin->n_bands*sizeof(flouble *)); for(iy1=0;iy1<cw->bin->n_bands;iy1++) { xi00_1122[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi00_1221[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi02_1122[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi02_1221[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi22p_1122[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi22p_1221[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi22m_1122[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); xi22m_1221[iy1]=my_calloc(cw->bin->n_bands,sizeof(flouble)); } #pragma omp for for(iy1=0;iy1<fs->ny;iy1++) { for(ix1=0;ix1<fs->nx;ix1++) { int index1=ix1+fs->nx*iy1; int ik1=i_band[index1]; if(ik1>=0) { for(iy2=0;iy2<fs->ny;iy2++) { for(ix2=0;ix2<fs->nx;ix2++) { int index,index2=ix2+fs->nx*iy2; int ik2=i_band[index2]; flouble cdiff=1,sdiff=0; int iy=iy1-iy2; int ix=ix1-ix2; if(iy<0) iy+=fs->ny; if(ix<0) ix+=fs->nx; index=ix+fs->nx*iy; if(ik2>=0) { double clm1122=cl_mask_1122[index]; double clm1221=cl_mask_1221[index]; cdiff=cosarr[index1]*cosarr[index2]+sinarr[index1]*sinarr[index2]; sdiff=sinarr[index1]*cosarr[index2]-cosarr[index1]*sinarr[index2]; xi00_1122[ik1][ik2]+=clm1122; xi00_1221[ik1][ik2]+=clm1221; xi02_1122[ik1][ik2]+=clm1122*cdiff; xi02_1221[ik1][ik2]+=clm1221*cdiff; xi22p_1122[ik1][ik2]+=clm1122*cdiff*cdiff; xi22p_1221[ik1][ik2]+=clm1221*cdiff*cdiff; xi22m_1122[ik1][ik2]+=clm1122*sdiff*sdiff; xi22m_1221[ik1][ik2]+=clm1221*sdiff*sdiff; } } } } } } //end omp for #pragma omp critical { for(iy1=0;iy1<cw->bin->n_bands;iy1++) { for(iy2=0;iy2<cw->bin->n_bands;iy2++) { cw->xi00_1122[iy1][iy2]+=xi00_1122[iy1][iy2]; cw->xi00_1221[iy1][iy2]+=xi00_1221[iy1][iy2]; cw->xi02_1122[iy1][iy2]+=xi02_1122[iy1][iy2]; cw->xi02_1221[iy1][iy2]+=xi02_1221[iy1][iy2]; cw->xi22p_1122[iy1][iy2]+=xi22p_1122[iy1][iy2]; cw->xi22p_1221[iy1][iy2]+=xi22p_1221[iy1][iy2]; cw->xi22m_1122[iy1][iy2]+=xi22m_1122[iy1][iy2]; cw->xi22m_1221[iy1][iy2]+=xi22m_1221[iy1][iy2]; } } } //end omp critical for(iy1=0;iy1<cw->bin->n_bands;iy1++) { free(xi00_1122[iy1]); free(xi00_1221[iy1]); free(xi02_1122[iy1]); free(xi02_1221[iy1]); free(xi22p_1122[iy1]); free(xi22p_1221[iy1]); free(xi22m_1122[iy1]); free(xi22m_1221[iy1]); } free(xi00_1122); free(xi00_1221); free(xi02_1122); free(xi02_1221); free(xi22p_1122); free(xi22p_1221); free(xi22m_1122); free(xi22m_1221); } //end omp parallel #pragma omp parallel default(none) \ shared(fs,cw,n_cells) { int ib1; flouble fac_norm=4*M_PI*M_PI/(fs->lx*fs->lx*fs->ly*fs->ly); #pragma omp for for(ib1=0;ib1<cw->bin->n_bands;ib1++) { int ib2; for(ib2=0;ib2<cw->bin->n_bands;ib2++) { flouble norm; if(n_cells[ib1]*n_cells[ib2]>0) norm=fac_norm/(n_cells[ib1]*n_cells[ib2]); else norm=0; cw->xi00_1122[ib1][ib2]*=norm; cw->xi00_1221[ib1][ib2]*=norm; cw->xi02_1122[ib1][ib2]*=norm; cw->xi02_1221[ib1][ib2]*=norm; cw->xi22p_1122[ib1][ib2]*=norm; cw->xi22p_1221[ib1][ib2]*=norm; cw->xi22m_1122[ib1][ib2]*=norm; cw->xi22m_1221[ib1][ib2]*=norm; } } //end omp for } //end omp parallel free(i_band); free(i_band_nocut); free(cl_mask_1122); free(cl_mask_1221); dftw_free(cosarr); dftw_free(sinarr); free(n_cells); return cw; } void nmt_covar_workspace_flat_free(nmt_covar_workspace_flat *cw) { int ii; for(ii=0;ii<cw->bin->n_bands;ii++) { free(cw->xi00_1122[ii]); free(cw->xi00_1221[ii]); free(cw->xi02_1122[ii]); free(cw->xi02_1221[ii]); free(cw->xi22p_1122[ii]); free(cw->xi22p_1221[ii]); free(cw->xi22m_1122[ii]); free(cw->xi22m_1221[ii]); } free(cw->xi00_1122); free(cw->xi00_1221); free(cw->xi02_1122); free(cw->xi02_1221); free(cw->xi22p_1122); free(cw->xi22p_1221); free(cw->xi22m_1122); free(cw->xi22m_1221); nmt_bins_flat_free(cw->bin); free(cw); } void nmt_compute_gaussian_covariance_flat(nmt_covar_workspace_flat *cw, int spin_a,int spin_b,int spin_c,int spin_d, nmt_workspace_flat *wa,nmt_workspace_flat *wb, int nl,flouble *larr, flouble **clac,flouble **clad, flouble **clbc,flouble **clbd,flouble *covar_out) { if((wa->bin->n_bands!=cw->bin->n_bands) || (wb->bin->n_bands!=cw->bin->n_bands)) report_error(NMT_ERROR_COVAR,"Coupling coefficients were computed for a different binning scheme\n"); int nmaps_a=spin_a ? 2 : 1; int nmaps_b=spin_b ? 2 : 1; int nmaps_c=spin_c ? 2 : 1; int nmaps_d=spin_d ? 2 : 1; if((wa->ncls!=nmaps_a*nmaps_b) || (wb->ncls!=nmaps_c*nmaps_d)) report_error(NMT_ERROR_COVAR,"Input spins don't match input workspaces\n"); //Compute binned spectra int i_cl; flouble **cblac=my_malloc(nmaps_a*nmaps_c*sizeof(flouble *)); for(i_cl=0;i_cl<nmaps_a*nmaps_c;i_cl++) cblac[i_cl]=my_malloc(cw->bin->n_bands*sizeof(flouble)); nmt_bin_cls_flat(cw->bin,nl,larr,clac,cblac,nmaps_a*nmaps_c); flouble **cblad=my_malloc(nmaps_a*nmaps_d*sizeof(flouble *)); for(i_cl=0;i_cl<nmaps_a*nmaps_d;i_cl++) cblad[i_cl]=my_malloc(cw->bin->n_bands*sizeof(flouble)); nmt_bin_cls_flat(cw->bin,nl,larr,clad,cblad,nmaps_a*nmaps_d); flouble **cblbc=my_malloc(nmaps_b*nmaps_c*sizeof(flouble *)); for(i_cl=0;i_cl<nmaps_b*nmaps_c;i_cl++) cblbc[i_cl]=my_malloc(cw->bin->n_bands*sizeof(flouble)); nmt_bin_cls_flat(cw->bin,nl,larr,clbc,cblbc,nmaps_b*nmaps_c); flouble **cblbd=my_malloc(nmaps_b*nmaps_d*sizeof(flouble *)); for(i_cl=0;i_cl<nmaps_b*nmaps_d;i_cl++) cblbd[i_cl]=my_malloc(cw->bin->n_bands*sizeof(flouble)); nmt_bin_cls_flat(cw->bin,nl,larr,clbd,cblbd,nmaps_b*nmaps_d); //Convolve with Xi gsl_matrix *covar_binned=gsl_matrix_alloc(wa->ncls*cw->bin->n_bands,wb->ncls*cw->bin->n_bands); #pragma omp parallel default(none) \ shared(cw,spin_a,spin_b,spin_c,spin_d) \ shared(wa,wb,nl,larr,covar_binned) \ shared(nmaps_a,nmaps_b,nmaps_c,nmaps_d) \ shared(cblac,cblad,cblbc,cblbd) { int band_a; #pragma omp for for(band_a=0;band_a<cw->bin->n_bands;band_a++) { int band_b; for(band_b=0;band_b<cw->bin->n_bands;band_b++) { int ia; double xis_1122[6]={cw->xi00_1122[band_a][band_b],cw->xi02_1122[band_a][band_b], cw->xi22p_1122[band_a][band_b],cw->xi22m_1122[band_a][band_b], -cw->xi22m_1122[band_a][band_b],0}; double xis_1221[6]={cw->xi00_1221[band_a][band_b],cw->xi02_1221[band_a][band_b], cw->xi22p_1221[band_a][band_b],cw->xi22m_1221[band_a][band_b], -cw->xi22m_1221[band_a][band_b],0}; for(ia=0;ia<nmaps_a;ia++) { int ib; for(ib=0;ib<nmaps_b;ib++) { int ic; int icl_a=ib+nmaps_b*ia; int index_a=wa->ncls*band_a+icl_a; for(ic=0;ic<nmaps_c;ic++) { int id; for(id=0;id<nmaps_d;id++) { int iap; int icl_b=id+nmaps_d*ic; int index_b=wb->ncls*band_b+icl_b; double cbinned=0; for(iap=0;iap<nmaps_a;iap++) { int ibp; for(ibp=0;ibp<nmaps_b;ibp++) { int icp; for(icp=0;icp<nmaps_c;icp++) { int idp; for(idp=0;idp<nmaps_d;idp++) { double *cl_ac=cblac[icp+nmaps_c*iap]; double *cl_ad=cblad[idp+nmaps_d*iap]; double *cl_bc=cblbc[icp+nmaps_c*ibp]; double *cl_bd=cblbd[idp+nmaps_d*ibp]; double fac_1122=0.5*(cl_ac[band_a]*cl_bd[band_b]+cl_ac[band_b]*cl_bd[band_a]); double fac_1221=0.5*(cl_ad[band_a]*cl_bc[band_b]+cl_ad[band_b]*cl_bc[band_a]); int ind_1122=cov_get_coupling_pair_index(nmaps_a,nmaps_c,nmaps_b,nmaps_d, ia,iap,ic,icp,ib,ibp,id,idp); int ind_1221=cov_get_coupling_pair_index(nmaps_a,nmaps_d,nmaps_b,nmaps_c, ia,iap,id,idp,ib,ibp,ic,icp); cbinned+=xis_1122[ind_1122]*fac_1122+xis_1221[ind_1221]*fac_1221; } } } } gsl_matrix_set(covar_binned,index_a,index_b,cbinned); } } } } } } //end omp for } //end omp parallel //Sandwich with inverse MCM gsl_matrix *covar_out_g =gsl_matrix_alloc(wa->ncls*cw->bin->n_bands,wb->ncls*cw->bin->n_bands); gsl_matrix *mat_tmp =gsl_matrix_alloc(wa->ncls*cw->bin->n_bands,wb->ncls*cw->bin->n_bands); gsl_matrix *inverse_a =gsl_matrix_alloc(wa->ncls*cw->bin->n_bands,wa->ncls*cw->bin->n_bands); gsl_matrix *inverse_b =gsl_matrix_alloc(wb->ncls*cw->bin->n_bands,wb->ncls*cw->bin->n_bands); gsl_linalg_LU_invert(wb->coupling_matrix_binned_gsl,wb->coupling_matrix_perm,inverse_b); //M_b^-1 gsl_linalg_LU_invert(wa->coupling_matrix_binned_gsl,wa->coupling_matrix_perm,inverse_a); //M_a^-1 gsl_blas_dgemm(CblasNoTrans,CblasTrans ,1,covar_binned,inverse_b,0,mat_tmp ); //tmp = C * M_b^-1^T gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1,inverse_a ,mat_tmp ,0,covar_out_g); //C' = M_a^-1 * C * M_b^-1^T //Flatten int ii; long elem=0; for(ii=0;ii<wa->ncls*cw->bin->n_bands;ii++) { int jj; for(jj=0;jj<wb->ncls*cw->bin->n_bands;jj++) { covar_out[elem]=gsl_matrix_get(covar_out_g,ii,jj); elem++; } } for(i_cl=0;i_cl<nmaps_a*nmaps_c;i_cl++) free(cblac[i_cl]); free(cblac); for(i_cl=0;i_cl<nmaps_a*nmaps_d;i_cl++) free(cblad[i_cl]); free(cblad); for(i_cl=0;i_cl<nmaps_b*nmaps_c;i_cl++) free(cblbc[i_cl]); free(cblbc); for(i_cl=0;i_cl<nmaps_b*nmaps_d;i_cl++) free(cblbd[i_cl]); free(cblbd); gsl_matrix_free(mat_tmp); gsl_matrix_free(inverse_a); gsl_matrix_free(inverse_b); gsl_matrix_free(covar_out_g); gsl_matrix_free(covar_binned); }
blake2sp-ref.c
/* BLAKE2 reference source code package - reference C implementations Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at your option. The terms of these licenses can be found at: - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 - OpenSSL license : https://www.openssl.org/source/license.html - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 More information about the BLAKE2 hash function can be found at https://blake2.net. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #if defined(_OPENMP) #include <omp.h> #endif #include "blake2.h" #include "blake2-impl.h" #define PARALLELISM_DEGREE 8 BLAKE2_LOCAL_INLINE(int) blake2sp_init_leaf( blake2s_state *S, uint8_t outlen, uint8_t keylen, uint64_t offset ) { blake2s_param P[1]; P->digest_length = outlen; P->key_length = keylen; P->fanout = PARALLELISM_DEGREE; P->depth = 2; store32( &P->leaf_length, 0 ); store48( P->node_offset, offset ); P->node_depth = 0; P->inner_length = BLAKE2S_OUTBYTES; memset( P->salt, 0, sizeof( P->salt ) ); memset( P->personal, 0, sizeof( P->personal ) ); return blake2s_init_param( S, P ); } BLAKE2_LOCAL_INLINE(int) blake2sp_init_root( blake2s_state *S, uint8_t outlen, uint8_t keylen ) { blake2s_param P[1]; P->digest_length = outlen; P->key_length = keylen; P->fanout = PARALLELISM_DEGREE; P->depth = 2; store32( &P->leaf_length, 0 ); store48( P->node_offset, 0ULL ); P->node_depth = 1; P->inner_length = BLAKE2S_OUTBYTES; memset( P->salt, 0, sizeof( P->salt ) ); memset( P->personal, 0, sizeof( P->personal ) ); return blake2s_init_param( S, P ); } int blake2sp_init( blake2sp_state *S, const uint8_t outlen ) { if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; memset( S->buf, 0, sizeof( S->buf ) ); S->buflen = 0; if( blake2sp_init_root( S->R, outlen, 0 ) < 0 ) return -1; for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2sp_init_leaf( S->S[i], outlen, 0, i ) < 0 ) return -1; S->R->last_node = 1; S->S[PARALLELISM_DEGREE - 1]->last_node = 1; return 0; } int blake2sp_init_key( blake2sp_state *S, const uint8_t outlen, const void *key, const uint8_t keylen ) { if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; if( !key || !keylen || keylen > BLAKE2S_KEYBYTES ) return -1; memset( S->buf, 0, sizeof( S->buf ) ); S->buflen = 0; if( blake2sp_init_root( S->R, outlen, keylen ) < 0 ) return -1; for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2sp_init_leaf( S->S[i], outlen, keylen, i ) < 0 ) return -1; S->R->last_node = 1; S->S[PARALLELISM_DEGREE - 1]->last_node = 1; { uint8_t block[BLAKE2S_BLOCKBYTES]; memset( block, 0, BLAKE2S_BLOCKBYTES ); memcpy( block, key, keylen ); for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) blake2s_update( S->S[i], block, BLAKE2S_BLOCKBYTES ); secure_zero_memory( block, BLAKE2S_BLOCKBYTES ); /* Burn the key from stack */ } return 0; } int blake2sp_update( blake2sp_state *S, const uint8_t *in, uint64_t inlen ) { size_t left = S->buflen; size_t fill = sizeof( S->buf ) - left; if( left && inlen >= fill ) { memcpy( S->buf + left, in, fill ); for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) blake2s_update( S->S[i], S->buf + i * BLAKE2S_BLOCKBYTES, BLAKE2S_BLOCKBYTES ); in += fill; inlen -= fill; left = 0; } #if defined(_OPENMP) #pragma omp parallel shared(S), num_threads(PARALLELISM_DEGREE) #else for( size_t id__ = 0; id__ < PARALLELISM_DEGREE; ++id__ ) #endif { #if defined(_OPENMP) size_t id__ = omp_get_thread_num(); #endif uint64_t inlen__ = inlen; const uint8_t *in__ = ( const uint8_t * )in; in__ += id__ * BLAKE2S_BLOCKBYTES; while( inlen__ >= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES ) { blake2s_update( S->S[id__], in__, BLAKE2S_BLOCKBYTES ); in__ += PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; inlen__ -= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; } } in += inlen - inlen % ( PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES ); inlen %= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; if( inlen > 0 ) memcpy( S->buf + left, in, inlen ); S->buflen = left + inlen; return 0; } int blake2sp_final( blake2sp_state *S, uint8_t *out, const uint8_t outlen ) { uint8_t hash[PARALLELISM_DEGREE][BLAKE2S_OUTBYTES]; for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) { if( S->buflen > i * BLAKE2S_BLOCKBYTES ) { size_t left = S->buflen - i * BLAKE2S_BLOCKBYTES; if( left > BLAKE2S_BLOCKBYTES ) left = BLAKE2S_BLOCKBYTES; blake2s_update( S->S[i], S->buf + i * BLAKE2S_BLOCKBYTES, left ); } blake2s_final( S->S[i], hash[i], BLAKE2S_OUTBYTES ); } for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) blake2s_update( S->R, hash[i], BLAKE2S_OUTBYTES ); return blake2s_final( S->R, out, outlen ); } int blake2sp( uint8_t *out, const void *in, const void *key, uint8_t outlen, uint64_t inlen, uint8_t keylen ) { uint8_t hash[PARALLELISM_DEGREE][BLAKE2S_OUTBYTES]; blake2s_state S[PARALLELISM_DEGREE][1]; blake2s_state FS[1]; /* Verify parameters */ if ( NULL == in && inlen > 0 ) return -1; if ( NULL == out ) return -1; if ( NULL == key && keylen > 0) return -1; if( !outlen || outlen > BLAKE2S_OUTBYTES ) return -1; if( keylen > BLAKE2S_KEYBYTES ) return -1; for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2sp_init_leaf( S[i], outlen, keylen, i ) < 0 ) return -1; S[PARALLELISM_DEGREE - 1]->last_node = 1; /* mark last node */ if( keylen > 0 ) { uint8_t block[BLAKE2S_BLOCKBYTES]; memset( block, 0, BLAKE2S_BLOCKBYTES ); memcpy( block, key, keylen ); for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) blake2s_update( S[i], block, BLAKE2S_BLOCKBYTES ); secure_zero_memory( block, BLAKE2S_BLOCKBYTES ); /* Burn the key from stack */ } #if defined(_OPENMP) #pragma omp parallel shared(S,hash), num_threads(PARALLELISM_DEGREE) #else for( size_t id__ = 0; id__ < PARALLELISM_DEGREE; ++id__ ) #endif { #if defined(_OPENMP) size_t id__ = omp_get_thread_num(); #endif uint64_t inlen__ = inlen; const uint8_t *in__ = ( const uint8_t * )in; in__ += id__ * BLAKE2S_BLOCKBYTES; while( inlen__ >= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES ) { blake2s_update( S[id__], in__, BLAKE2S_BLOCKBYTES ); in__ += PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; inlen__ -= PARALLELISM_DEGREE * BLAKE2S_BLOCKBYTES; } if( inlen__ > id__ * BLAKE2S_BLOCKBYTES ) { const size_t left = inlen__ - id__ * BLAKE2S_BLOCKBYTES; const size_t len = left <= BLAKE2S_BLOCKBYTES ? left : BLAKE2S_BLOCKBYTES; blake2s_update( S[id__], in__, len ); } blake2s_final( S[id__], hash[id__], BLAKE2S_OUTBYTES ); } if( blake2sp_init_root( FS, outlen, keylen ) < 0 ) return -1; FS->last_node = 1; for( size_t i = 0; i < PARALLELISM_DEGREE; ++i ) blake2s_update( FS, hash[i], BLAKE2S_OUTBYTES ); return blake2s_final( FS, out, outlen ); } #if defined(BLAKE2SP_SELFTEST) #include <string.h> #include "blake2-kat.h" int main( int argc, char **argv ) { uint8_t key[BLAKE2S_KEYBYTES]; uint8_t buf[KAT_LENGTH]; for( size_t i = 0; i < BLAKE2S_KEYBYTES; ++i ) key[i] = ( uint8_t )i; for( size_t i = 0; i < KAT_LENGTH; ++i ) buf[i] = ( uint8_t )i; for( size_t i = 0; i < KAT_LENGTH; ++i ) { uint8_t hash[BLAKE2S_OUTBYTES]; blake2sp( hash, buf, key, BLAKE2S_OUTBYTES, i, BLAKE2S_KEYBYTES ); if( 0 != memcmp( hash, blake2sp_keyed_kat[i], BLAKE2S_OUTBYTES ) ) { puts( "error" ); return -1; } } puts( "ok" ); return 0; } #endif
IO.h
// // Created by mario on 13/11/18. // #ifndef SEVN_REVISED_IO_H #define SEVN_REVISED_IO_H #include <iostream> #include <vector> #include <set> #include <dirent.h> #include <algorithm> #include <map> #include <sevnlog.h> #include <utilities.h> #include <starparameter.h> #include <fstream> #include <numeric> //for iota function #include <set> #include <sevnlog.h> using sevnstd::SevnLogging; #include <lookup_and_phases.h> using namespace Lookup; #include <params.h> #ifdef H5OUT #include <H5out.h> using sevnstd::H5out; #else #include <fstream> #include <iomanip> #endif #include <sys/stat.h> //GI271119: moved here from region inside ifdef H5OUT class Star; /* NB: Every IO constructor needs to call set_init_variable() at the beginning to properly set the following - tablesloaded = 0; Otherwise it will never load the tables even if load is called - nthreads = 1; - ntables = _Ntables; */ class IO { public: IO(){ set_init_variables(); } IO(int argc, char **argv){ set_init_variables(); load(argc, argv); if (!get_output_folder_name().empty()) create_folder(get_output_folder_name()); svlog.debug("Output folder name is "+get_output_folder_name()); } ~IO(){ if(liststars.is_open()) liststars.close(); if(failedstars.is_open()) failedstars.close(); if(outputfile.is_open()) outputfile.close(); if(logfile.is_open()) logfile.close(); } std::string get_logstring(){ return logstring;}; template <typename T> void fill_matrix_test(std::vector< std::vector<T> > &matrix, std::ifstream &file){ std::vector<T> vline; std::string line, value; std::istringstream stream; std::cout<<" Filling matrix "<<std::endl; for(;;){ vline.erase(vline.begin(), vline.end()); getline(file, line); if(file.eof() || line.length()==0 ) break; //break if end of file or if a blank line is included. stream.clear(); stream.str(line); //If it is a comment do not read if(line[0]=='/' or line[0]=='#') continue; for(;;){ //keep reading the line till its last element if(stream >> value){ vline.push_back(utilities::s2n<T>(value, __FILE__, __LINE__)); stream.clear(); } else break; } matrix.push_back(vline); } } //tables[ID][i][j][k]: //ID = taken from enum lookup_names. It tells what kind of matrix you want to access // i = metallicity index // j = track number // k = time on the j-th track std::vector<std::vector<std::vector<std::vector<double>>>> tables,tables_HE; std::vector<double> Z, Z_HE; std::vector<std::vector<double>> allzams, allzams_HE; std::vector< std::vector<std::string> > STARS_MATRIX; std::random_device rd; //TODO Let the user select the output columns (not just what add to the default one) std::vector<std::string> printcolumns_star; /*!< List of string containing the name of the stellar properties to print in output. It *is composed by a default lit of columns (IO::list_cols_star, defined in IO::load) plus some extra columns selected at runtime by the user with the -scol flag * see IO::load*/ std::vector<std::string> printcolumns_binary; /*< As above, but for the properties of the binary system. Use -bcol flag to let the user add more columns * to the default defined in IO::list_cols_binary*/ std::vector<size_t> printIDs_star; std::vector<size_t> printIDs_binary; size_t ntables; int nthreads; std::string output_mode; /**< Handle the file output type */ std::string binput_mode; /**< Handle the formalism for the input for binaries */ std::string winds_mode; /**< Formalism for DA and DE in Winds accretion processes */ std::string RL_mode; /**< Formalism for DA and DE in RL process */ std::string tides_mode; /**< Formalism for DA and DE in tidal processes */ std::string GW_mode; /**< Formalism for DA and DE in GW rad processes */ std::string mix_mode; /**< Formalism for mixing processes options */ std::string COLL_mode; /**< Formalism for mixing processes options */ std::string SNK_mode; /**< Formalism for SN kick processes options */ std::string CE_mode; /**< Formalism for Common envelope processes options */ std::string SEVNpath; ///Parameters call //TODO Transform all the paramters to parameters call inline bool rseed_provided(){return svpar.get_bool("rseed");} SEVNpar svpar; //variable to check if look-up tables have already been loaded int tablesloaded; void print_output(std::vector<std::vector<double>> &printmatrix, const std::string &_name, const unsigned long &_rseed, const size_t &_ID, const bool binaryprint=false); inline void print_formatted_output(std::vector<std::vector<double>> &printmatrix, const std::string &_name, const unsigned long &_rseed, const size_t &_ID, const bool binaryprint=false){ //This is not needed since the print_evolved_summary is called inside the call of binstar or star //print_evolved_summary(_name, _rseed, _ID); //TODO change the way we choose among different outputs. New class structure IO --> PRINT (virtual with instances) --> -- ASCII, HDF5, CSV // here we will just call PRINT.do() OutputOption out = outputmap.at(output_mode); if(out == OutputOption::_ascii) print_ascii(printmatrix, _name, _rseed, _ID, binaryprint); else if (out == OutputOption::_csv) print_csv(printmatrix, _name, _rseed, _ID, binaryprint); else if (out == OutputOption::_binary) print_bin(printmatrix, _name, _rseed, _ID, binaryprint); #ifdef H5OUT else if (out == OutputOption::_hdf5) print_hdf5(printmatrix, _name, binaryprint); #endif else svlog.critical("Output option not recognized: [" + output_mode +"] ", __FILE__, __LINE__,sevnstd::sevnio_error()); return; } /** * Print the evolved summary in ascii format. The info are printed in the file opened as liststars in IO.h. The name of the file * is equal to evolved_<NTHREAD>.dat and it will be saved in the ouput folder chosen in input. * @param _name name assigned to the star * @param _ID ID assigen to the star */ void print_evolved_summary(const std::string &_name, const unsigned long &_rseed, const size_t &_ID); /** * Print the summary of the failed system in ascii format. The info are printed in the file opened as failedstars in IO.h. The name of the file * is equal to failed_<NTHREAD>.dat and it will be saved in the ouput folder chosen in input. * @param _name * @param _ID */ void print_failed_summary(const std::string &_name, const unsigned long &_rseed, const size_t &_ID); void print_failed_initilisation_summary(const size_t &_ID); inline void print_params(std::string filename="used_params.svpar"){ std::string fname = get_output_folder_name()+"/"+filename; std::ofstream output_file; output_file.open(fname); output_file<< svpar.print(); output_file.close(); } /** * Flush the string logstring to the logfile output and clear logstring * @param filename Name of the file where to save the log */ void print_log(std::string filename="logfile.dat"); /** * * @param loginfo */ void log_put(std::string& loginfo); #ifdef DEBUG /** * Print step by step the info on the times after a single evolution step (see evolvestar in star.h). * with respect to the normal time output it prints also the step that in evolve are rejected due to a to fast evolution in Mass (see Timestep in property.cpp) * @param s Pointer to the star object. * @return Nothing, but the info are saved in timelog_x.dat in the output folder */ void print_timelog(Star *s); #endif void create_folder(const std::string &name) { #if defined(__linux__) int results = mkdir(name.c_str(), 0777); #else //The above code seems to not work properly for certain path name on macOS int results = system(("mkdir -p "+name).c_str()); #endif if(results){ svlog.pdebug("Directory exist",__FILE__,__LINE__); DIR *theFolder = opendir(name.c_str()); struct dirent *next_file; while ( (next_file = readdir(theFolder)) != nullptr ){ std::string path = name + "/" + next_file->d_name; remove(path.c_str()); } closedir(theFolder); } } //GET inline std::string get_output_folder_name() { return output_folder_name;} inline std::string get_SEVNpath() const { return SEVNpath;} //load /** * Utilities to load auxiliary data tables. * The files needs to be all inside the folder SEVN/auxiliary_data * @param name name of the file * @return a 2D vector of double storing the given auxiliary table * @Note lines starting with # or / are skipped */ std::vector<std::vector<double>> load_auxiliary_table(std::string name) const{ std::ifstream table_file; std::vector<std::vector<double>> Matrix; #pragma omp critical { table_file.open(get_SEVNpath() + "auxiliary_data/" + name); //std::cout<<get_SEVNpath() + "auxiliary_data/" + name<<std::endl; if (table_file.is_open()) { fill_matrix(Matrix, table_file); table_file.close(); } else svlog.critical("Raised an error reading auxiliary table file " + name + ". Check if the file exist, if you specified the right path in the run script, and if you have reading permission.", __FILE__, __LINE__, sevnstd::sevnio_error()); } return Matrix; } protected: inline void set_init_variables(){ tablesloaded = 0; ntables = _Ntables; }; void load(int n, char** val); private: #ifdef H5OUT static H5out h5; //used by each thread to print the HDF5 dataset #pragma omp threadprivate(IO::h5) #endif static std::ofstream liststars; static std::ofstream failedstars; static std::ofstream failedinits; static std::ofstream outputfile; //GI 81119: File where to save the (non h5) output. static std::ofstream logfile; //File to output the log static std::string logstring; //File to store info to output in log, declared threadprivate #pragma omp threadprivate(IO::liststars) #pragma omp threadprivate(IO::failedstars) #pragma omp threadprivate(IO::failedinits) #pragma omp threadprivate(IO::outputfile) #pragma omp threadprivate(IO::logfile) #pragma omp threadprivate(IO::logstring) #ifdef DEBUG static std::ofstream timelog; #pragma omp threadprivate(IO::timelog) #endif static std::vector<std::string> labels_STARMATRIX; /*!< Vector that stores the label of the STARMATRIX column, it is set with set_STARMATRIX_labels, called by load_txt*/ std::string output_folder_name="output"; std::vector<std::vector<double>> printmatrix; SevnLogging svlog; //main std::string tables_dir, tables_dir_HE, list_file; //folder where to find all the look-up tables std::string list_cols_star; /*!< Default list of stellar properties to print in output, defined in IO::load*/ std::string list_cols_binary; /*!< Default list of binary properties to print in output, defined in IO::load*/ //auxiliaryload std::ifstream in; std::vector<std::string> zstring, zstring_HE; /** * Transfer the name from a string containing the name separated by a : to a vector of string. * It checks that each name in list cols is one of the name included in Property::PrintMap or in BinaryProperty::PrintMAP * @param list_cols A string containing the property names separated with a : * @param printcolumns Vector of sting to fill with names from list_cols. */ void columns_to_print(std::string &list_cols, std::vector<std::string> &printcolumns); void read(std::vector<std::vector<std::vector<std::vector<double>>>>& tables, const std::string& tables_dir, const std::vector<std::string>& zstring, std::vector<double>& Z); void read_tables(){ read(tables,tables_dir,zstring,Z); read(tables_HE,tables_dir_HE,zstring_HE,Z_HE); } void inspect_tables(); //It loads all the available tables, at all metallicities void load_tables(); //It loads all the available tables for pure-HE stars (if any), at all metallicities //It loads all the stars void load_stars(); template <typename T> void fill_matrix(std::vector< std::vector<T> > &matrix, std::ifstream &file) const{ std::vector<T> vline; std::string line, value; std::istringstream stream; for(;;){ vline.erase(vline.begin(), vline.end()); getline(file, line); if(file.eof() || line.length()==0 ) break; //break if end of file or if a blank line is included. stream.clear(); stream.str(line); //Skip comments if (line[0]=='#' or line[0]=='/') continue; for(;;){ //keep reading the line till its last element if(stream >> value and stream.str()[0]!='/' and stream.str()[0]!='#'){ vline.push_back(utilities::s2n<T>(value, __FILE__, __LINE__)); stream.clear(); } else break; } matrix.push_back(vline); } } void print_list_summary(std::ofstream& outstream, std::string basename, const std::string &_name, const unsigned long &_rseed, const size_t &_ID); //GI 81119: specific functions to be called by print_output depending on the output type //void print_evolved_summary(const std::string &_name, const size_t &_ID); #ifdef H5OUT void print_hdf5(std::vector<std::vector<double>> &printmatrix, const std::string &_name, const bool binaryprint); #endif /** * Formatted ascii print of values contained in the a 2D vector of doubles. * In addition to the value in printmatrix two columns are added with the name and the ID of the star. * @param filename name of the file where to write the data * @param printmatrix 2D vector of doubles to print * @param _name name of the star (it will be the second column in addition to the data in @p printmatrix) * @param _ID ID of the star (it will the first column in addition to the data in @p printmatrix) * @param binaryprint if true the system calling print is a binary, so the printmatrix contains the info of the two stars and of their orbit * @param separator field delimiter for the output file * @param _w_id field width of the id column * @param _w_name field width of the name column * @param _w_header field with of all the other columns * @param _precision decimal precision * @note The name of the columns shown in the header are taken from IO::printcolumns_star and IO::printcolumns_binary. The order of the columns name and of the columns in * printmatrix has to be the same, but it is not checked here (see IO::columns_to_print for other details on how this is managed in the class). */ void print_formatted_ascii(const std::string &filename,std::vector<std::vector<double>> &printmatrix, const std::string &_name, const unsigned long &_rseed, const size_t &_ID, const bool binaryprint, const std::string &separator, const size_t &_w_id, const size_t &_w_name, const size_t &_w_header, const size_t &_precision, const std::string &comment); void print_ascii(std::vector<std::vector<double>> &printmatrix, const std::string &_name, const unsigned long &_rseed, const size_t &_ID, const bool binaryprint); void print_csv(std::vector<std::vector<double>> &printmatrix, const std::string &_name, const unsigned long &_rseed, const size_t &_ID, const bool binaryprint); void print_bin(std::vector<std::vector<double>> &printmatrix, const std::string &_name, const unsigned long &_rseed, const size_t &_ID, const bool binaryprint); void inspect_dirs(){ inspect_dir(tables_dir,zstring,Z); inspect_dir(tables_dir_HE,zstring_HE,Z_HE); } void inspect_dir(const std::string &motherdir, std::vector<std::string>& _zstring, std::vector<double>& _Z,std::string inspectdir="") { std::string dir = motherdir + "/" + inspectdir; std::cout<<" inspectig dir = "<<dir<<std::endl; if(dir.empty()) svlog.critical("You are trying to inspect an empty directory: " + dir, __FILE__, __LINE__); dir += "/"; //safe instruction.. if the user forgets to add the / at the end of the directory string auto directory = opendir(dir.c_str()); //from dirent.h if(nullptr == directory) svlog.critical("Cannot open directory " + dir, __FILE__, __LINE__); dirent *gotobject = readdir(directory); //get the first object inside the directory while(gotobject != nullptr) { //inspect all the objects inside the current directory inspect_object(gotobject, motherdir,_zstring,_Z); gotobject = readdir(directory); } closedir(directory); } void inspect_object(dirent *object, const std::string &motherdir, std::vector<std::string>& _zstring, std::vector<double>& _Z) { if (object->d_type == DT_DIR) {//the object is a directory if (object->d_name[0] == '.') { //exclude . and .. return; } _zstring.emplace_back(object->d_name); //Vector containing the name of all the metallicity folders (GI why not directly casted from Z?) //it's a directory, so process it... it should be a metallicity dir _Z.push_back(utilities::dirname2n<double>(std::string(object->d_name), __FILE__, __LINE__)); //save the metallicity value... use the string_to_number function //_tables_file.resize(_Z.size()); inspect_dir(motherdir, _zstring, _Z, std::string(object->d_name));//process a directory (a sub_directory) return; //done inspection in the current sub-folder } //for each metallicity we fill the "tables_file vector... it contains all the tables we have for each different metallicity" if (object->d_type == DT_REG) { if (object->d_name[0] == '.') { //exclude hidden files (e.g. .DS_Store on MacOs) return; } std::string filename = motherdir + "/" + _zstring[_zstring.size()-1] + "/" + std::string(object->d_name); //GI: Do not read files that are not defined in filemap if(filemap.find(std::string(object->d_name)) == filemap.end() and filemap_optional.find(std::string(object->d_name)) == filemap_optional.end()){ svlog.warning("The unexpected file '"+std::string(object->d_name)+"' has been found in the directory "+ motherdir + "/" + _zstring[_zstring.size()-1] + ". It will be not loaded. Check if this is a misspelled table." ,__FILE__,__LINE__); return; } //if(!filename.empty()) // _tables_file[_Z.size()-1].push_back(filename); //else // svlog.critical("This filename should not be empty: " + filename, __FILE__, __LINE__); if(filename.empty()) svlog.critical("This filename should not be empty: " + filename, __FILE__, __LINE__); return; //return the name of the file } svlog.critical("This is nor a file or a directory: " + std::string(object->d_name), __FILE__, __LINE__); } protected: /** * Check if the tables Z, ZHE, allzams, allzams_HE are sorted * @return */ //TODO probably this can be made void (no need to return bool?) bool check_sorted(){ //Z if (!std::is_sorted(Z.begin(),Z.end())) svlog.critical("Z table is not sorted",__FILE__,__LINE__,sevnstd::sevnio_error()); //ZHE if (!std::is_sorted(Z_HE.begin(),Z_HE.end())) svlog.critical("Z_HE table is not sorted",__FILE__,__LINE__,sevnstd::sevnio_error()); //Mass for (auto& zams_table : allzams){ if (!std::is_sorted(zams_table.begin(),zams_table.end())) svlog.critical("zams table is not sorted",__FILE__,__LINE__,sevnstd::sevnio_error()); } //Mass HE for (auto& zams_table : allzams_HE){ if (!std::is_sorted(zams_table.begin(),zams_table.end())) svlog.critical("zams_HE table is not sorted",__FILE__,__LINE__,sevnstd::sevnio_error()); } return true; } /** * Set the labels referred to the columns of the STARMATRIX table depending on input type * NOTICE: so far we assume that a list of input system contains all binaries or all stars not a mix */ inline void set_STARMATRIX_labels(){ //TODO We should have a flag to understand if we are dealing with a binary or not. //TODO 8 is hardcoded for now; unsigned int N_expected = 8; bool is_binary = STARS_MATRIX[0].size()>N_expected; int inchoice=inputmapbin.at(binput_mode).first; if (is_binary and inchoice==InputBinaryOption::_new){ labels_STARMATRIX={"Mass_0","Z_0","spin_0", "SN_0", "Tstart_0", "Mass_1","Z_1","spin_1", "SN_1", "Tstart_1", "a","e","Tend", "Dtout"}; } else if (is_binary and inchoice==InputBinaryOption::_legacy) labels_STARMATRIX={"Mass_0","Mass_1","Z_0","Z_1","spin_0","spin_1", "a","e","Tend", "Tstart", "dt","SN_0","SN_1","Dtout"}; else if (!is_binary){ labels_STARMATRIX={"Mass","Z","spin", "SN", "Tstart", "Tend", "Dtout"}; } else svlog.critical("Option unkown",__FILE__,__LINE__,sevnstd::sevnio_error()); } //TODO Put a safe get starmatrix table? It check if is has been initialised (i.e. is not empty) or not }; #endif //SEVN_REVISED_IO_H
special_ops.h
#pragma once #include <ops/ops.h> #include <loops/reduce.h> #include <loops/scalar.h> #include <loops/indexreduce.h> #include <loops/broadcasting.h> namespace functions { namespace broadcast { template <typename T> class Broadcast; } namespace transform { template <typename T> class Transform; } namespace scalar { } namespace reduce { template <typename T> class ReduceFunction; } } namespace simdOps { template<typename T> class Pooling2D { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ inline __host__ __device__ #elif defined(__GNUC__) #endif static int outSize(int size, int k, int s, int p, bool coverAll) { if (coverAll) return (size + p * 2 - k + s - 1) / s + 1; else return (size + p * 2 - k) / s + 1; } #ifdef __CUDACC__ /** * Based on: https://github.com/pjreddie/darknet/blob/master/src/im2col_kernels.cu */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { __shared__ int kH; __shared__ int kW; __shared__ int sH; __shared__ int sW; __shared__ int pH; __shared__ int pW; __shared__ int dH; __shared__ int dW; __shared__ int poolingMode; __shared__ T extraParam0; __shared__ int batchSize; __shared__ int inChannels; __shared__ int outH; __shared__ int outW; __shared__ int inH; __shared__ int inW; //__shared__ int *strideIn; //__shared__ int *strideOut; __shared__ int strideB; __shared__ int strideC; __shared__ int strideY; __shared__ int strideX; __shared__ int strideOB; __shared__ int strideOC; __shared__ int strideOY; __shared__ int strideOX; __shared__ int length; __shared__ int kHEff; __shared__ int kWEff; __shared__ bool fOrder; if (threadIdx.x == 0) { kH = (int)extraParams[0]; kW = (int)extraParams[1]; sH = (int)extraParams[2]; sW = (int)extraParams[3]; pH = (int)extraParams[4]; pW = (int)extraParams[5]; dH = (int)extraParams[6]; //Dilation, height dimension dW = (int)extraParams[7]; //Dilation, width dimension poolingMode = (int)extraParams[9]; extraParam0 = extraParams[10]; batchSize = shape::sizeAt(xShapeBuffer, 0); inChannels = shape::sizeAt(xShapeBuffer, 1); outH = shape::sizeAt(resultShapeBuffer, 2); outW = shape::sizeAt(resultShapeBuffer, 3); inH = shape::sizeAt(xShapeBuffer, 2); inW = shape::sizeAt(xShapeBuffer, 3); strideB = shape::stride(xShapeBuffer)[0]; strideC = shape::stride(xShapeBuffer)[1]; strideY = shape::stride(xShapeBuffer)[2]; strideX = shape::stride(xShapeBuffer)[3]; strideOB = shape::stride(resultShapeBuffer)[0]; strideOC = shape::stride(resultShapeBuffer)[1]; strideOY = shape::stride(resultShapeBuffer)[2]; strideOX = shape::stride(resultShapeBuffer)[3]; length = shape::length(resultShapeBuffer); //Replace kernel H/W with *effective* kernel H/W accounting for dilatyon kHEff = kH + (kH-1)*(dH-1); kWEff = kW + (kW-1)*(dW-1); fOrder = shape::order(resultShapeBuffer) == 'f'; /* if (blockIdx.x == 0) { printf("kH: %i; kW: %i; sH: %i; sW: %i; pH: %i; pW: %i; dH: %i; dW: %i; poolingMode: %i; extraParam0: %f;\n", kH, kW, sH, sW, pH, pW, dH, dW, poolingMode, (float) extraParam0); printf("batchSize: %i; inChannels: %i; outH: %i; outW: %i; inH: %i; inW: %i; strideB: %i; strideC: %i; strideY: %i; strideX: %i;\n", batchSize, inChannels, outH, outW, inH, inW, strideB, strideC, strideY, strideX); } */ } __syncthreads(); int tid = blockIdx.x * gridDim.x + threadIdx.x; for (int index = tid; index < length; index += blockDim.x * gridDim.x) { const int pw = index % outW; const int ph = (index / outW) % outH; const int c = (index / outW / outH) % inChannels; const int n = index / outW / outH / inChannels; int hstart = sH * ph - pH; int wstart = sW * pw - pW; int hend = hstart + kHEff; int wend = wstart + kWEff; // const int hSO = hstart; // const int hEO = hend; if(hstart < 0){ int f = (int)nd4j::math::nd4j_ceil<T>((T) -hstart / (T)dH); hstart += f * dH; } if(wstart < 0){ int f = (int)nd4j::math::nd4j_ceil<T>((T) -wstart / (T) dW); wstart += f * dW; } if(hend > inH){ int f = (int)nd4j::math::nd4j_ceil<T>((T) (hend-inH) / (T) dH); hend -= f * dH; } if(wend > inW){ int f = (int)nd4j::math::nd4j_ceil<T>((T) (wend-inW) / (T) dW); wend -= f * dW; } int pool_size = (int)(nd4j::math::nd4j_ceil<T>((T) (hend-hstart) / (T) dH) * (int) nd4j::math::nd4j_ceil<T>((T) (wend-wstart) / (T) dW)); //Accounts for dilation T sum = poolingMode == 0 ? -nd4j::DataTypeUtils::max<T>() : static_cast<T>(0.f); T *input_slice = dx + (n * strideB + c * strideC); if (poolingMode == 0) { for (int h = hstart; h < hend; h += dH) { for (int w = wstart; w < wend; w += dW) { T v = input_slice[h * strideY + w * strideX]; if (v > sum) sum = v; } } } else if (poolingMode == 1) { for (int h = hstart; h < hend; h += dH) { for (int w = wstart; w < wend; w += dW) { sum += input_slice[h * strideY + w * strideX]; } } } else if (poolingMode == 2) { for (int h = hstart; h < hend; h += dH) { for (int w = wstart; w < wend; w += dW) { sum += nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(input_slice[h * strideY + w * strideX]), extraParam0); } } } T res; if (poolingMode == 0) { res = sum; } else if (poolingMode == 1) { int divide_factor = pool_size; //Case 0: exclude padding if ((int) extraParam0 == 1) //Case 1: include padding divide_factor = kH * kW; res = sum / divide_factor; } else if (poolingMode == 2) { res = nd4j::math::nd4j_pow<T>(sum, (T) 1.0f / extraParam0); } if (!fOrder) { result[index] = res; } else { result[n * strideOB + c * strideOC + pw * strideOX + ph * strideOY] = res; } /* if (index >= 0 && index < 400000) { printf("index: %i; hstart: %i; hend: %i; wstart: %i; wend: %i; ph: %i; pw: %i; hstart_orig: %i; hend_orig: %i;\n", index, hstart, hend, wstart, wend, ph, pw, hSO, hEO); } */ } } #endif static void execSpecial(T *in, Nd4jLong *inShapeBuffer, T *out, Nd4jLong *outShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { // input is [bS, iC, iH, iW] // output is [bS, iC, oH, oW] const Nd4jLong kH = (int)extraParams[0]; const Nd4jLong kW = (int)extraParams[1]; const Nd4jLong sH = (int)extraParams[2]; const Nd4jLong sW = (int)extraParams[3]; const Nd4jLong pH = (int)extraParams[4]; const Nd4jLong pW = (int)extraParams[5]; const Nd4jLong dH = (int)extraParams[6]; const Nd4jLong dW = (int)extraParams[7]; Nd4jLong poolingMode = (int)extraParams[9]; T extraParam0 = extraParams[10]; if(dH == 0 || dW == 0) { printf("Special_ops pooling2d:: dilation must not be zero, but got instead {%lld, %lld} \n", dH, dW); throw ""; } const Nd4jLong kHEff = kH + (kH-1)*(dH-1); const Nd4jLong kWEff = kW + (kW-1)*(dW-1); const int bS = shape::sizeAt(inShapeBuffer, 0); const int iC = shape::sizeAt(inShapeBuffer, 1); const int iH = shape::sizeAt(inShapeBuffer, 2); const int iW = shape::sizeAt(inShapeBuffer, 3); const int oH = shape::sizeAt(outShapeBuffer, 2); const int oW = shape::sizeAt(outShapeBuffer, 3); const Nd4jLong iStride0 = shape::stride(inShapeBuffer)[0]; const Nd4jLong iStride1 = shape::stride(inShapeBuffer)[1]; const Nd4jLong iStride2 = shape::stride(inShapeBuffer)[2]; const Nd4jLong iStride3 = shape::stride(inShapeBuffer)[3]; const Nd4jLong oStride0 = shape::stride(outShapeBuffer)[0]; const Nd4jLong oStride1 = shape::stride(outShapeBuffer)[1]; const Nd4jLong oStride2 = shape::stride(outShapeBuffer)[2]; const Nd4jLong oStride3 = shape::stride(outShapeBuffer)[3]; const Nd4jLong iStep2 = dH*iStride2; const Nd4jLong iStep3 = dW*iStride3; const int kProd = kH*kW; const T iStep2Inv = 1./iStep2; const T iStep3Inv = 1./iStep3; Nd4jLong hstart, wstart, hend, wend; T sum, *pIn; if(poolingMode == 0) { // max #pragma omp parallel for schedule(guided) private(pIn, sum, hstart, wstart, hend, wend) for(int b = 0; b < bS; ++b) { for(int c = 0; c < iC; ++c) { for(int oh = 0; oh < oH; ++oh) { for(int ow = 0; ow < oW; ++ow) { pIn = in + b * iStride0 + c * iStride1; hstart = oh * sH - pH; wstart = ow * sW - pW; hend = hstart + kHEff; wend = wstart + kWEff; if(hstart < 0) hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(-hstart) / static_cast<T>(dH)); if(wstart < 0) wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(-wstart) / static_cast<T>(dW)); if(hend > iH) hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(hend-iH) / static_cast<T>(dH)); if(wend > iW) wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(wend-iW) / static_cast<T>(dW)); hstart *= iStride2; hend *= iStride2; wstart *= iStride3; wend *= iStride3; sum = -MAX_FLOAT; for (Nd4jLong kh = hstart; kh < hend; kh += iStep2) for (Nd4jLong kw = wstart; kw < wend; kw += iStep3) { T val = pIn[kh + kw]; if (val > sum) sum = val; } out[b * oStride0 + c * oStride1 + oh * oStride2 + ow * oStride3] = sum; } } } } } /*************************************************************************/ else if(poolingMode == 1) { // avg #pragma omp parallel for schedule(guided) private(pIn, sum, hstart, wstart, hend, wend) for(int b = 0; b < bS; ++b) { for(int c = 0; c < iC; ++c) { for(int oh = 0; oh < oH; ++oh) { for(int ow = 0; ow < oW; ++ow) { pIn = in + b * iStride0 + c * iStride1; hstart = oh * sH - pH; wstart = ow * sW - pW; hend = hstart + kHEff; wend = wstart + kWEff; if(hstart < 0) hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(-hstart) / static_cast<T>(dH)); if(wstart < 0) wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(-wstart) / static_cast<T>(dW)); if(hend > iH) hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(hend-iH) / static_cast<T>(dH)); if(wend > iW) wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(wend-iW) / static_cast<T>(dW)); hstart *= iStride2; hend *= iStride2; wstart *= iStride3; wend *= iStride3; sum = static_cast<T>(0.); for (Nd4jLong kh = hstart; kh < hend; kh += iStep2) for (Nd4jLong kw = wstart; kw < wend; kw += iStep3) sum += pIn[kh + kw]; if ((int) extraParam0 == 0) //Exclude padding sum /= static_cast<T>(nd4j::math::nd4j_ceil<double>(static_cast<double>(hend-hstart) / static_cast<double>(iStep2))) * static_cast<T>(nd4j::math::nd4j_ceil<double>(static_cast<double>(wend-wstart) / static_cast<double>(iStep3))); //Accounts for dilation else if ((int) extraParam0 == 1) //Include padding sum /= kProd; out[b * oStride0 + c * oStride1 + oh * oStride2 + ow * oStride3] = sum; } } } } } /*************************************************************************/ else if(poolingMode == 2) { // pnorm #pragma omp parallel for schedule(guided) private(pIn, sum, hstart, wstart, hend, wend) for(int b = 0; b < bS; ++b) { for(int c = 0; c < iC; ++c) { for(int oh = 0; oh < oH; ++oh) { for(int ow = 0; ow < oW; ++ow) { pIn = in + b * iStride0 + c * iStride1; hstart = oh * sH - pH; wstart = ow * sW - pW; hend = hstart + kHEff; wend = wstart + kWEff; if(hstart < 0) hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(-hstart) / static_cast<T>(dH)); if(wstart < 0) wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(-wstart) / static_cast<T>(dW)); if(hend > iH) hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(hend-iH) / static_cast<T>(dH)); if(wend > iW) wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>(static_cast<T>(wend-iW) / static_cast<T>(dW)); hstart *= iStride2; hend *= iStride2; wstart *= iStride3; wend *= iStride3; sum = static_cast<T>(0.); for (Nd4jLong kh = hstart; kh < hend; kh += iStep2) for (Nd4jLong kw = wstart; kw < wend; kw += iStep3) sum += nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kh + kw]), extraParam0); sum = nd4j::math::nd4j_pow<T>(sum, (T) 1. / extraParam0); out[b * oStride0 + c * oStride1 + oh * oStride2 + ow * oStride3] = sum; } } } } } else { nd4j_printf("Special_ops::pooling2d: pooling mode argument can take three values only: 0, 1, 2, but got %i instead !\n", poolingMode); throw ""; } } op_def static T op(T d1, T *params) { return d1; } /** Calculate buffer offset (like Shape.getOffset) without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 4 */ static _CUDA_HD int getOffsetUnsafe4(int baseOffset, int *shape, int *stride, int *indices) { int offset = baseOffset; if (shape[0] != 1) offset += indices[0] * stride[0]; if (shape[1] != 1) offset += indices[1] * stride[1]; if (shape[2] != 1) offset += indices[2] * stride[2]; if (shape[3] != 1) offset += indices[3] * stride[3]; return offset; } /** * A version of Shape.getOffset without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 6, where indices[2] and indices[3] are zero (always are here) */ static _CUDA_HD int getOffsetUnsafe6(int baseOffset, int *shape, int *stride, int *indices) { int offset = baseOffset; if (shape[0] != 1) offset += indices[0] * stride[0]; if (shape[1] != 1) offset += indices[1] * stride[1]; if (shape[4] != 1) offset += indices[4] * stride[4]; if (shape[5] != 1) offset += indices[5] * stride[5]; return offset; } }; FORCEINLINE bool is_a_ge_zero_and_a_lt_b(int a, int b) { return static_cast<unsigned>(a) < static_cast<unsigned>(b); } template<typename T> class Im2col { public: static const bool requiresSpecial = true; static _CUDA_HD int outSize(int size, int k, int s, int p, bool coverAll) { if (coverAll) return (size + p * 2 - k + s - 1) / s + 1; else return (size + p * 2 - k) / s + 1; } #ifdef __CUDACC__ /** * Based on: https://github.com/pjreddie/darknet/blob/master/src/im2col_kernels.cu */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { /*kernel[0], kernel[1], stride[0], stride[1], padding[0], padding[1], 0, false*/ int kernelHeight = (int)extraParams[0]; int kernelWidth = (int)extraParams[1]; int strideY = (int)extraParams[2]; int strideX = (int)extraParams[3]; int padHeight = (int)extraParams[4]; int padWidth = (int)extraParams[5]; int dY = (int)extraParams[6]; //Dilation, height/y dimension int dX = (int)extraParams[7]; //Dilation, width/x dimension int kSize = kernelWidth * kernelHeight; T zeroPadVal = (T)extraParams[9]; //Value to use when value is padding. Usually 0 but not always auto outShape = shape::shapeOf(resultShapeBuffer); auto resultOrder = shape::order(resultShapeBuffer); auto outStride = shape::stride(resultShapeBuffer); auto inShape = shape::shapeOf(xShapeBuffer); auto inStride = shape::stride(xShapeBuffer); int samples = inShape[0]; int depth = inShape[1]; int height = inShape[2]; int width = inShape[3]; int strideex = inStride[0]; int stridech = inStride[1]; int strideh = inStride[2]; int stridew = inStride[3]; // (height + 2 * padHeight - kernelHeight) / strideX + 1; // // (width + 2 * padWidth - kernelWidth) / strideY + 1; // int height_col = outShape[4]; int width_col = outShape[5]; int n = samples * depth * height_col * width_col; /* if (threadIdx.x == 0) printf("Kernel h: [%i], w: [%i]; Col h: [%i], w: [%i]; Stride x: [%i], y: [%i]; Height: [%i], Width: [%i], Depth: [%i], N: [%i], Samples: [%i]\n", kernelHeight, kernelWidth, height_col, width_col, strideX, strideY, height, width, depth, n, samples); */ int index = blockIdx.x * blockDim.x + threadIdx.x; for (; index < n; index += blockDim.x*gridDim.x) { int h_index = index / width_col; int h_col = h_index % height_col; int w_col = index % width_col; int c_im = h_index / height_col; int c_col = c_im * kSize; int depth_im = c_im % depth; int num_im = c_im / depth; int h_offset = h_col * strideY - padHeight; int w_offset = w_col * strideX - padWidth; T* data_col_ptr = result; int i_c = (c_col * height_col + h_col) * width_col + w_col; data_col_ptr += (c_col * height_col + h_col) * width_col + w_col; T* data_im_ptr = dx; data_im_ptr += num_im * strideex + depth_im * stridech + h_offset * strideh + w_offset*stridew; for (int i = 0; i < kernelHeight; ++i) { for (int j = 0; j < kernelWidth; ++j) { int h_im = h_offset + i * dY; int w_im = w_offset + j * dX; int i_f = 0; int i_c_temp = i_c; for (int dim = 5; dim >= 0; dim--) { i_f += (i_c_temp % outShape[dim]) * outStride[dim]; i_c_temp = i_c_temp / outShape[dim]; } if (h_im >= 0 && w_im >= 0 && h_im < height && w_im < width){ result[i_f] = data_im_ptr[i * dY * strideh + j * dX * stridew]; } else result[i_f] = zeroPadVal; //result[i_f] = (h_im >= 0 && w_im >= 0 && h_im < height && w_im < width) ? data_im_ptr[i * strideh + j*stridew] : 0; data_col_ptr += height_col * width_col; i_c += height_col * width_col; } } } } #endif static void execSpecial( T *imBuff, Nd4jLong *imShapeBuffer, T *colBuff, Nd4jLong *colShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { /*kernel[0], kernel[1], stride[0], stride[1], padding[0], padding[1], 0, false*/ // [bS, iC, iH, iW] is convoluted to [bS, iC, kH, kW, oH, oW] int kH = (int)extraParams[0]; int kW = (int)extraParams[1]; int sH = (int)extraParams[2]; int sW = (int)extraParams[3]; int pH = (int)extraParams[4]; int pW = (int)extraParams[5]; int dH = (int)extraParams[6]; //Dilation, height/y dimension int dW = (int)extraParams[7]; //Dilation, width/x dimension T zeroPadVal = extraParams[9]; auto colShape = shape::shapeOf(colShapeBuffer); auto colStride = shape::stride(colShapeBuffer); auto imShape = shape::shapeOf(imShapeBuffer); auto imStride = shape::stride(imShapeBuffer); const int bS = imShape[0]; const int iC = imShape[1]; const int iH = imShape[2]; const int iW = imShape[3]; const int oH = colShape[4]; const int oW = colShape[5]; const Nd4jLong colStride0 = colStride[0]; const Nd4jLong colStride1 = colStride[1]; const Nd4jLong colStride2 = colStride[2]; const Nd4jLong colStride3 = colStride[3]; const Nd4jLong colStride4 = colStride[4]; const Nd4jLong colStride5 = colStride[5]; const Nd4jLong imStride0 = imStride[0]; const Nd4jLong imStride1 = imStride[1]; const Nd4jLong imStride2 = imStride[2]; const Nd4jLong imStride3 = imStride[3]; T *col, *im; int imRow, imCol; if (shape::order(imShapeBuffer) == 'c' && shape::order(colShapeBuffer) == 'c' && shape::strideDescendingCAscendingF(imShapeBuffer) && shape::strideDescendingCAscendingF(colShapeBuffer)) { #pragma omp parallel for schedule(static) proc_bind(close) private(col, im, imRow, imCol) for (int b = 0; b < bS; b++) { for (int c = 0; c < iC; ++c) { for (int kRow = 0; kRow < kH; ++kRow) { for (int kCol = 0; kCol < kW; ++kCol) { for (int colH = 0; colH < oH; ++colH) { for (int colW = 0; colW < oW; ++colW) { imRow = (-pH + kRow * dH) + colH*sH; imCol = (-pW + kCol * dW) + colW*sW; col = colBuff + b*colStride0 + c*colStride1 + kRow*colStride2 + kCol*colStride3 + colH*colStride4 + colW*colStride5; im = imBuff + b*imStride0 + c*imStride1 + imRow*imStride2 + imCol*imStride3; if (static_cast<unsigned>(imRow) >= static_cast<unsigned>(iH) || static_cast<unsigned>(imCol) >= static_cast<unsigned>(iW)) *col = zeroPadVal; else *col = *im; } } } } } } } else { #pragma omp parallel for schedule(static) proc_bind(close) private(im, col, imRow, imCol) for (int b = 0; b < bS; b++) { for (int colH = 0; colH < oH; ++colH) { for (int colW = 0; colW < oW; ++colW) { for (int c = 0; c < iC; ++c) { for (int kRow = 0; kRow < kH; ++kRow) { for (int kCol = 0; kCol < kW; ++kCol) { imRow = (-pH + kRow * dH) + colH*sH; imCol = (-pW + kCol * dW) + colW*sW; col = colBuff + b*colStride0 + c*colStride1 + kRow*colStride2 + kCol*colStride3 + colH*colStride4 + colW*colStride5; im = imBuff + b*imStride0 + c*imStride1 + imRow*imStride2 + imCol*imStride3; if (static_cast<unsigned>(imRow) >= static_cast<unsigned>(iH) || static_cast<unsigned>(imCol) >= static_cast<unsigned>(iW)) *col = zeroPadVal; else *col = *im; } } } } } } } } op_def static T op(T d1, T *params) { return d1; } /** Calculate buffer offset (like Shape.getOffset) without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 4 */ static _CUDA_HD int getOffsetUnsafe4(int baseOffset, int *shape, int *stride, int *indices) { int offset = baseOffset; if (shape[0] != 1) offset += indices[0] * stride[0]; if (shape[1] != 1) offset += indices[1] * stride[1]; if (shape[2] != 1) offset += indices[2] * stride[2]; if (shape[3] != 1) offset += indices[3] * stride[3]; return offset; } /** * A version of Shape.getOffset without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 6, where indices[2] and indices[3] are zero (always are here) */ static _CUDA_HD int getOffsetUnsafe6(int baseOffset, int *shape, int *stride, int *indices) { int offset = baseOffset; if (shape[0] != 1) offset += indices[0] * stride[0]; if (shape[1] != 1) offset += indices[1] * stride[1]; if (shape[4] != 1) offset += indices[4] * stride[4]; if (shape[5] != 1) offset += indices[5] * stride[5]; return offset; } }; template<typename T> class Histogram { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { int numBins = (int) extraParams[0]; T min_val = extraParams[1]; T max_val = extraParams[2]; int tid = blockIdx.x * blockDim.x + threadIdx.x; __shared__ T *bins; __shared__ int length; __shared__ T *reductor; if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; bins = (T *) shmem; reductor = ((T *) allocationPointer) + (numBins * blockIdx.x); length = shape::length(xShapeBuffer); } __syncthreads(); T binSize = (max_val - min_val) / (numBins); for (int e = threadIdx.x; e < numBins; e += blockDim.x) { bins[e] = (T) 0.0f; } __syncthreads(); for (int e = tid; e < length; e+= blockDim.x * gridDim.x) { int idx = (int) ((dx[e] - min_val) / binSize); if (idx < 0) idx = 0; else if (idx >= numBins) idx = numBins - 1; nd4j::math::atomics::nd4j_atomicAdd(&bins[idx], (T) 1.0f); } __syncthreads(); // transfer shared memory to reduction memory if (gridDim.x > 1) { unsigned int *tc = (unsigned int *)reductionPointer; __shared__ bool amLast; for (int e = threadIdx.x; e < numBins; e += blockDim.x) { reductor[e] = bins[e]; } __threadfence(); __syncthreads(); if (threadIdx.x == 0) { unsigned int ticket = atomicInc(&tc[16384], gridDim.x); amLast = (ticket == gridDim.x - 1); } __syncthreads(); if (amLast) { tc[16384] = 0; // nullify shared memory for future accumulation for (int e = threadIdx.x; e < numBins; e += blockDim.x) { bins[e] = (T) 0.0f; } // accumulate reduced bins for (int r = 0; r < gridDim.x; r++) { T *ptrBuf = ((T *)allocationPointer) + (r * numBins); for (int e = threadIdx.x; e < numBins; e += blockDim.x) { bins[e] += ptrBuf[e]; } } __syncthreads(); // write them out to Z for (int e = threadIdx.x; e < numBins; e += blockDim.x) { result[e] = bins[e]; } } } else { // if there's only 1 block - just write away data for (int e = threadIdx.x; e < numBins; e += blockDim.x) { result[e] = bins[e]; } } }; #endif static void execSpecial( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { int length = shape::length(xShapeBuffer); int _threads = 2; int numBins = (int) extraParams[0]; int span = (length / _threads) + 8; // get min over input T min_val = extraParams[1]; T max_val = extraParams[2]; /* #pragma omp parallel for simd num_threads(_threads) if (_threads > 1) reduction(min:min_val) proc_bind(close) for (int x = 0; x < length; x++) { if (min_val > dx[x]) min_val = dx[x]; } // get max over input T max_val = (T) MIN_FLOAT; #pragma omp parallel for simd num_threads(_threads) if (_threads > 1) reduction(max:max_val) proc_bind(close) for (int x = 0; x < length; x++) { if (max_val < dx[x]) max_val = dx[x]; } */ T binSize = (max_val - min_val) / (numBins); #pragma omp parallel num_threads(_threads) if (_threads > 1) proc_bind(close) default(shared) { int tid, start, end; int *bins = new int[numBins]; std::memset(bins, 0, sizeof(int) * numBins); tid = omp_get_thread_num(); start = span * tid; end = span * (tid + 1); if (end > length) end = length; #pragma omp simd for (int x = start; x < end; x++) { int idx = (int) ((dx[x] - min_val) / binSize); if (idx < 0) idx = 0; else if (idx >= numBins) idx = numBins - 1; bins[idx]++; } #pragma omp critical { #pragma omp simd for (int x = 0; x < numBins; x++) { result[x] += bins[x]; } } delete[] bins; } } op_def static T op(T d1, T *params) { return d1; } }; template<typename T> class Col2Im { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ /** * https://github.com/pjreddie/darknet/blob/master/src/col2im_kernels.cu */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto inShape = shape::shapeOf(xShapeBuffer); auto inStride = shape::stride(xShapeBuffer); int strideex = inStride[0]; int stridech = inStride[1]; int stridekrow = inStride[2]; int stridekcol = inStride[3]; int striderow = inStride[4]; int stridecol = inStride[5]; int kernelHeight = inShape[2]; int kernelWidth = inShape[3]; // C int strideY = (int)extraParams[0]; int strideX = (int)extraParams[1]; int padHeight = (int)extraParams[2]; int padWidth = (int)extraParams[3]; int imgHeight = (int)extraParams[4]; int imgWidth = (int)extraParams[5]; int dY = (int)extraParams[6]; //Dilation in height/y dimension int dX = (int)extraParams[7]; //Dilation in width/x dimension auto outShape = shape::shapeOf(resultShapeBuffer); auto resultOrder = shape::order(resultShapeBuffer); auto outStride = shape::stride(resultShapeBuffer); int samples = outShape[0]; int depth = outShape[1]; int imgH = outShape[2]; int imgW = outShape[3]; int height_col = inShape[4];//(imgHeight + 2 * padHeight - kernelHeight) / strideX + 1; int width_col = inShape[5];//(imgWidth + 2 * padWidth - kernelWidth) / strideY + 1; int n = samples * depth * imgHeight * imgWidth; /*if (threadIdx.x == 0) printf("Kernel h: [%i], w: [%i]; Col h: [%i], w: [%i]; Stride x: [%i], y: [%i]; Height: [%i], Width: [%i], Depth: [%i], N: [%i], Samples: [%i]\n", kernelHeight, kernelWidth, height_col, width_col, strideX, strideY, imgHeight, imgWidth, depth, n, samples);*/ //Effective kernel size, accounting for dilation int kEffectiveW = kernelWidth + (kernelWidth - 1) * (dX - 1); int kEffectiveH = kernelHeight + (kernelHeight - 1) * (dY - 1); for (int i = (blockDim.x * blockIdx.x) + threadIdx.x; i < n; i += blockDim.x * gridDim.x) { T val = 0; int w_im = i % imgWidth + padWidth; int h_im = (i / imgWidth) % imgHeight + padHeight; int c_im = i / (imgWidth * imgHeight); int num_im = c_im / depth; int depth_im = c_im % depth; // compute the start and end of the output // These are the indexes for dimensions ??? in the 6d col matrix int w_col_start = (w_im < kEffectiveW) ? 0 : (w_im - kEffectiveW) / strideX + 1; int w_col_end = nd4j::math::nd4j_min<int>(w_im / strideX + 1, width_col); int h_col_start = (h_im < kEffectiveH) ? 0 : (h_im - kEffectiveH) / strideY + 1; int h_col_end = nd4j::math::nd4j_min<int>(h_im / strideY + 1, height_col); //Iterate over col entries in the 6d array... these are added up for (int h_col = h_col_start; h_col < h_col_end; h_col += 1) { for (int w_col = w_col_start; w_col < w_col_end; w_col += 1) { int h_k = (h_im - h_col * strideY); int w_k = (w_im - w_col * strideX); if(h_k % dY == 0 && w_k % dX == 0){ h_k /= dY; w_k /= dX; int data_col_index = num_im * strideex + depth_im * stridech + h_k * stridekrow + w_k * stridekcol + h_col * striderow + w_col * stridecol; val += dx[data_col_index]; } } } int i_f = 0; int i_c = i; for (int dim = 3; dim >= 0; dim--) { i_f += (i_c % outShape[dim]) * outStride[dim]; i_c = i_c / outShape[dim]; } result[i_f] = val; } } #endif static void execSpecial( T *colBuff, Nd4jLong *colShapeBuffer, T *imBuff, Nd4jLong *imShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { // [bS, iC, kH, kW, oH, oW] is de-convoluted to [bS, iC, iH, iW] auto colShape = shape::shapeOf(colShapeBuffer); auto colStride = shape::stride(colShapeBuffer); auto imShape = shape::shapeOf(imShapeBuffer); auto imStride = shape::stride(imShapeBuffer); const int sH = (int)extraParams[0]; const int sW = (int)extraParams[1]; const int pH = (int)extraParams[2]; const int pW = (int)extraParams[3]; const int iH = (int)extraParams[4]; const int iW = (int)extraParams[5]; const int dH = (int)extraParams[6]; const int dW = (int)extraParams[7]; const int bS = imShape[0]; const int iC = imShape[1]; const int kH = colShape[2]; const int kW = colShape[3]; const int oH = colShape[4]; const int oW = colShape[5]; const Nd4jLong colStride0 = colStride[0]; const Nd4jLong colStride1 = colStride[1]; const Nd4jLong colStride2 = colStride[2]; const Nd4jLong colStride3 = colStride[3]; const Nd4jLong colStride4 = colStride[4]; const Nd4jLong colStride5 = colStride[5]; const Nd4jLong imStride0 = imStride[0]; const Nd4jLong imStride1 = imStride[1]; const Nd4jLong imStride2 = imStride[2]; const Nd4jLong imStride3 = imStride[3]; // initial zeroing of image content const Nd4jLong imEWS = nd4j::math::nd4j_abs<Nd4jLong>(shape::elementWiseStride(imShapeBuffer)); if(imEWS == 1) memset(imBuff, 0, shape::length(imShapeBuffer) * sizeof(T)); else #pragma omp parallel for schedule(static) proc_bind(close) for (int i = 0; i < shape::length(imShapeBuffer) * imEWS; i += imEWS) imBuff[i] = 0.f; T *col, *im; int imRow, imCol; if (shape::order(colShapeBuffer) == 'c' && shape::order(imShapeBuffer) == 'c' && shape::strideDescendingCAscendingF(colShapeBuffer) && shape::strideDescendingCAscendingF(imShapeBuffer)) { #pragma omp parallel for schedule(static) proc_bind(close) private(col, im, imRow, imCol) for (int b = 0; b < bS; b++) { for (int c = 0; c < iC; ++c) { for (int kRow = 0; kRow < kH; ++kRow) { for (int kCol = 0; kCol < kW; ++kCol) { for (int colH = 0; colH < oH; ++colH) { for (int colW = 0; colW < oW; ++colW) { imRow = (-pH + kRow * dH) + colH*sH; imCol = (-pW + kCol * dW) + colW*sW; col = colBuff + b*colStride0 + c*colStride1 + kRow*colStride2 + kCol*colStride3 + colH*colStride4 + colW*colStride5; im = imBuff + b*imStride0 + c*imStride1 + imRow*imStride2 + imCol*imStride3; if (static_cast<unsigned>(imRow) < static_cast<unsigned>(iH) && static_cast<unsigned>(imCol) < static_cast<unsigned>(iW)) *im += *col; } } } } } } } else { #pragma omp parallel for schedule(static) proc_bind(close) private(im, col, imRow, imCol) for (int b = 0; b < bS; b++) { for (int colH = 0; colH < oH; ++colH) { for (int colW = 0; colW < oW; ++colW) { for (int c = 0; c < iC; ++c) { for (int kRow = 0; kRow < kH; ++kRow) { for (int kCol = 0; kCol < kW; ++kCol) { imRow = (-pH + kRow * dH) + colH*sH; imCol = (-pW + kCol * dW) + colW*sW; col = colBuff + b*colStride0 + c*colStride1 + kRow*colStride2 + kCol*colStride3 + colH*colStride4 + colW*colStride5; im = imBuff + b*imStride0 + c*imStride1 + imRow*imStride2 + imCol*imStride3; if (static_cast<unsigned>(imRow) < static_cast<unsigned>(iH) && static_cast<unsigned>(imCol) < static_cast<unsigned>(iW)) *im += *col; } } } } } } } } op_def static T op(T d1, T *params) { return d1; } /** Calculate buffer offset (like Shape.getOffset) without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 4 */ static _CUDA_HD int getOffsetUnsafe4(int baseOffset, int *shape, int *stride, int *indices) { int offset = baseOffset; if (shape[0] != 1) offset += indices[0] * stride[0]; if (shape[1] != 1) offset += indices[1] * stride[1]; if (shape[2] != 1) offset += indices[2] * stride[2]; if (shape[3] != 1) offset += indices[3] * stride[3]; return offset; } /** A version of Shape.getOffset without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 6, where indices[2] and indices[3] are zero (always are here) */ static _CUDA_HD int getOffsetUnsafe6(int baseOffset, int *shape, int *stride, int *indices) { int offset = baseOffset; if (shape[0] != 1) offset += indices[0] * stride[0]; if (shape[1] != 1) offset += indices[1] * stride[1]; if (shape[4] != 1) offset += indices[4] * stride[4]; if (shape[5] != 1) offset += indices[5] * stride[5]; return offset; } }; template<typename T> class Reverse { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ static inline __device__ void execSpecialCuda(T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *zShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { __shared__ Nd4jLong xLength; __shared__ int xEWS; __shared__ char xOrder; __shared__ Nd4jLong sLength; __shared__ T *shmem; int tid = threadIdx.x + blockIdx.x * blockDim.x; if (threadIdx.x == 0) { xLength = shape::length(xShapeBuffer); xEWS = shape::elementWiseStride(xShapeBuffer); xOrder = shape::order(xShapeBuffer); sLength = xLength - 1; extern __shared__ unsigned char shrd[]; shmem = (T *) shrd; } __syncthreads(); if (dx == result) { if (xEWS == 1) { for (int e = tid; e < xLength / 2; e += blockDim.x * gridDim.x) { Nd4jLong idx = sLength - e; T tmp = dx[e]; dx[e] = dx[idx]; dx[idx] = tmp; } } else if (xEWS >= 1) { for (int e = tid; e < xLength / 2; e += blockDim.x * gridDim.x) { Nd4jLong idx1 = (sLength - e) * xEWS; Nd4jLong idx2 = e * xEWS; T tmp = dx[idx2]; dx[idx2] = dx[idx1]; dx[idx1] = tmp; } } else { __shared__ int xRank; __shared__ Nd4jLong *xShape; __shared__ Nd4jLong *xStride; if (threadIdx.x == 0) { xRank = shape::rank(xShapeBuffer); xShape = shape::shapeOf(xShapeBuffer); xStride = shape::stride(xShapeBuffer); } __syncthreads(); Nd4jLong xCoord[MAX_RANK]; Nd4jLong zCoord[MAX_RANK]; for (int e = tid; e < xLength / 2; e += blockDim.x * gridDim.x) { if (xOrder == 'c') { shape::ind2subC(xRank, xShape, e, xCoord); shape::ind2subC(xRank, xShape, sLength - e, zCoord); } else { shape::ind2sub(xRank, xShape, e, xCoord); shape::ind2sub(xRank, xShape, sLength - e, zCoord); } auto xOffset = shape::getOffset(0, xShape, xStride, xCoord, xRank); auto zOffset = shape::getOffset(0, xShape, xStride, zCoord, xRank); result[zOffset] = dx[xOffset]; } } } else { __shared__ int zEWS; __shared__ char zOrder; if (threadIdx.x == 0) { zEWS = shape::elementWiseStride(zShapeBuffer); zOrder = shape::order(zShapeBuffer); } __syncthreads(); if (xEWS == 1 && zEWS == 1 && xOrder == zOrder) { // loop for whole array for (int e = tid; e < xLength; e += blockDim.x * gridDim.x) { result[sLength - e] = dx[e]; } } else if (xEWS >= 1 && zEWS >= 1 && xOrder == zOrder) { for (int e = tid; e < xLength; e += blockDim.x * gridDim.x) { result[(sLength - e) * zEWS] = dx[e * xEWS]; } } else { __shared__ int xRank; __shared__ Nd4jLong *xShape; __shared__ Nd4jLong *xStride; __shared__ int zRank; __shared__ Nd4jLong *zShape; __shared__ Nd4jLong *zStride; if (threadIdx.x == 0) { xRank = shape::rank(xShapeBuffer); xShape = shape::shapeOf(xShapeBuffer); xStride = shape::stride(xShapeBuffer); zRank = shape::rank(zShapeBuffer); zShape = shape::shapeOf(zShapeBuffer); zStride = shape::stride(zShapeBuffer); } __syncthreads(); Nd4jLong xCoord[MAX_RANK]; Nd4jLong zCoord[MAX_RANK]; for (int e = tid; e < xLength; e += blockDim.x * gridDim.x) { if (xOrder == 'c') { shape::ind2subC(xRank, xShape, e, xCoord); shape::ind2subC(xRank, xShape, sLength - e, zCoord); } else { shape::ind2sub(xRank, xShape, e, xCoord); shape::ind2sub(xRank, xShape, sLength - e, zCoord); } auto xOffset = shape::getOffset(0, xShape, xStride, xCoord, xRank); auto zOffset = shape::getOffset(0, xShape, xStride, zCoord, xRank); result[zOffset] = dx[xOffset]; } } } } #endif static void execSpecial(T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *zShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { Nd4jLong xLength = shape::length(xShapeBuffer); int xEWS = shape::elementWiseStride(xShapeBuffer); char xOrder = shape::order(xShapeBuffer); Nd4jLong sLength = xLength - 1; // two step phase here if (dx == result) { if (xEWS == 1) { #pragma omp parallel for schedule(guided) for (Nd4jLong e = 0; e < xLength / 2; e++) { Nd4jLong idx = sLength - e; T tmp = dx[e]; dx[e] = dx[idx]; dx[idx] = tmp; } } else if (xEWS > 1) { #pragma omp parallel for schedule(guided) for (Nd4jLong e = 0; e < xLength / 2; e++) { Nd4jLong idx1 = (sLength - e) * xEWS; Nd4jLong idx2 = e * xEWS; T tmp = dx[idx2]; dx[idx2] = dx[idx1]; dx[idx1] = tmp; } } else { int xRank = shape::rank(xShapeBuffer); auto xShape = shape::shapeOf(xShapeBuffer); auto xStride = shape::stride(xShapeBuffer); Nd4jLong xCoord[MAX_RANK]; Nd4jLong zCoord[MAX_RANK]; #pragma omp parallel for private(xCoord, zCoord) schedule(guided) for (Nd4jLong e = 0; e < xLength / 2; e++) { if (xOrder == 'c') { shape::ind2subC(xRank, xShape, e, xCoord); shape::ind2subC(xRank, xShape, sLength - e, zCoord); } else { shape::ind2sub(xRank, xShape, e, xCoord); shape::ind2sub(xRank, xShape, sLength - e, zCoord); } auto xOffset = shape::getOffset(0, xShape, xStride, xCoord, xRank); auto zOffset = shape::getOffset(0, xShape, xStride, zCoord, xRank); result[zOffset] = dx[xOffset]; } } } else { // single step phase here auto zEWS = shape::elementWiseStride(zShapeBuffer); auto zOrder = shape::order(zShapeBuffer); if (xEWS == 1 && zEWS == 1 && xOrder == zOrder) { #pragma omp parallel for schedule(guided) for (Nd4jLong e = 0; e < xLength; e++) { result[sLength - e] = dx[e]; } } else if (xEWS >= 1 && zEWS >= 1 && xOrder == zOrder) { #pragma omp parallel for schedule(guided) for (Nd4jLong e = 0; e < xLength; e++) { result[(sLength - e) * zEWS] = dx[e * xEWS]; } } else { auto xRank = shape::rank(xShapeBuffer); auto xShape = shape::shapeOf(xShapeBuffer); auto xStride = shape::stride(xShapeBuffer); auto zRank = shape::rank(zShapeBuffer); auto zShape = shape::shapeOf(zShapeBuffer); auto zStride = shape::stride(zShapeBuffer); Nd4jLong xCoord[MAX_RANK]; Nd4jLong zCoord[MAX_RANK]; #pragma omp parallel for private(xCoord, zCoord) schedule(guided) for (Nd4jLong e = 0; e < xLength; e++) { if (xOrder == 'c') shape::ind2subC(xRank, xShape, e, xCoord); else shape::ind2sub(xRank, xShape, e, xCoord); if (zOrder == 'c') shape::ind2subC(zRank, zShape, (sLength - e), zCoord); else shape::ind2sub(zRank, zShape, (sLength - e), zCoord); auto xOffset = shape::getOffset(0, xShape, xStride, xCoord, xRank); auto zOffset = shape::getOffset(0, zShape, zStride, zCoord, zRank); result[zOffset] = dx[xOffset]; } } } } op_def static T op(T d1, T *params) { return d1; } }; template<typename T> class SoftMax { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ /** * */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto shape = shape::shapeOf(xShapeBuffer); __shared__ T maxResult; __shared__ Nd4jLong *maxResultShapeBuffer; auto length = shape::length(xShapeBuffer); auto stride = shape::stride(xShapeBuffer); //compute the row wise maxes __shared__ Nd4jLong maxShape[2]; // it's always 2d here __shared__ Nd4jLong tempBuffer[8]; if (threadIdx.x == 0) { maxResult = (T) 0.0; maxShape[0] = shape[0]; maxShape[1] = 1; maxResultShapeBuffer = shape::shapeBuffer(2, maxShape, tempBuffer); } __syncthreads(); functions::reduce::ReduceFunction<T>::template execScalarCuda<simdOps::Max<T>>(dx, xShapeBuffer, extraParams, &maxResult, maxResultShapeBuffer, reductionPointer, manager, nullptr); __syncthreads(); //subtract max of each row functions::scalar::ScalarTransform<T>::template transformCuda<simdOps::Subtract<T>>(maxResult, dx, xShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, manager); __syncthreads(); //after subtracting the row wise maxes take the exp functions::transform::Transform<T>::template transformCuda<simdOps::Exp<T>>(result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, reductionPointer, manager, tadShapeInfo, tadOffsets); __syncthreads(); //take the sum for the exponential functions::reduce::ReduceFunction<T>::template execScalarCuda<simdOps::Sum<T>>(result, resultShapeBuffer, extraParams, &maxResult, maxResultShapeBuffer, reductionPointer, manager, nullptr); __syncthreads(); //divide by the sum functions::scalar::ScalarTransform<T>::template transformCuda<simdOps::Divide<T>>(maxResult, result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, manager); } #endif static void execSpecial( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { if (shape::isMatrix(xShapeBuffer)) { auto shape = shape::shapeOf(xShapeBuffer); //iterate along rows int dimension[1] = { 0 }; int maxDimension[1] = { 1 }; //compute the row wise maxes std::vector<T> maxResult(shape[0]); for (int i = 0; i < shape[0]; i++) maxResult[i] = 0.0; Nd4jLong maxShape[2] = { shape[0], 1 }; auto maxResultShapeBuffer = shape::shapeBuffer(2, maxShape); functions::reduce::ReduceFunction<T>::template exec<simdOps::Max<T>>(dx, xShapeBuffer, extraParams, maxResult.data(), maxResultShapeBuffer, maxDimension, 1, nullptr, nullptr); //subtract max of each row functions::broadcast::Broadcast<T>::template exec<simdOps::Subtract<T>>(dx, xShapeBuffer, maxResult.data(), maxResultShapeBuffer, result, resultShapeBuffer, dimension, 1, nullptr, nullptr, nullptr, nullptr); //after subtracting the row wise maxes take the exp functions::transform::Transform<T>::template exec<simdOps::Exp<T>>(result, resultShapeBuffer, result, resultShapeBuffer, extraParams, tadShapeInfo, tadOffsets); //take the sum for the exponential functions::reduce::ReduceFunction<T>::template exec<simdOps::Sum<T>>(result, resultShapeBuffer, extraParams, maxResult.data(), maxResultShapeBuffer, maxDimension, 1, nullptr, nullptr); //divide by the sum functions::broadcast::Broadcast<T>::template exec<simdOps::Divide<T>>(result, resultShapeBuffer, maxResult.data(), maxResultShapeBuffer, result, resultShapeBuffer, dimension, 1, nullptr, nullptr, nullptr, nullptr); delete[] maxResultShapeBuffer; } else if (shape::isVector(xShapeBuffer)) { T max = -FLOAT_MAX_VALUE; T sum = 0; int elementWiseStride = shape::elementWiseStride(xShapeBuffer); int resultElementWiseStride = shape::elementWiseStride(resultShapeBuffer); int length = shape::length(xShapeBuffer); if (elementWiseStride >= 1 && resultElementWiseStride >= 1) { if (elementWiseStride == 1 && resultElementWiseStride == 1) { #pragma omp simd reduction(maxT:max) for (int i = 0; i < length; i++) { max = nd4j::math::nd4j_max<T>(max, dx[i]); } #pragma omp parallel for simd reduction(sumT:sum) for (int i = 0; i < length; i++) { result[i] = nd4j::math::nd4j_exp<T>(dx[i] - max); sum += result[i]; } #pragma omp simd for (int i = 0; i < length; i++) { result[i] /= sum; } } else { #pragma omp simd reduction(maxT:max) for (int i = 0; i < length; i++) { max = nd4j::math::nd4j_max<T>(max, dx[i * elementWiseStride]); } #pragma omp parallel for simd reduction(sumT:sum) for (int i = 0; i < length; i++) { T r = nd4j::math::nd4j_exp<T>(dx[i * elementWiseStride] - max); result[i * resultElementWiseStride] = r; sum += r; } #pragma omp simd for (int i = 0; i < length; i++) { result[i * resultElementWiseStride] /= sum; } } } } } op_def static T op(T d1, T *params) { return nd4j::math::softplus<T>(d1); } }; template<typename T> class LogSoftMax { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ /** * */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto shape = shape::shapeOf(xShapeBuffer); auto stride = shape::stride(xShapeBuffer); //iterate along rows __shared__ T maxResult; __shared__ Nd4jLong *maxResultShapeBuffer; if (threadIdx.x == 0) { maxResult = (T) 0.0; } __syncthreads(); //compute the row wise maxes Nd4jLong maxShape[2] = { shape[0], 1 }; __shared__ Nd4jLong tempBuffer[8]; if (threadIdx.x == 0) maxResultShapeBuffer = shape::shapeBuffer(2, maxShape, tempBuffer); __syncthreads(); functions::reduce::ReduceFunction<T>::template execScalarCuda<simdOps::Max<T>>(dx, xShapeBuffer, extraParams, &maxResult, maxResultShapeBuffer, reductionPointer, manager, nullptr); __syncthreads(); //subtract max of each row functions::scalar::ScalarTransform<T>::template transformCuda<simdOps::Subtract<T>>(maxResult, dx, xShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, manager); __syncthreads(); //after subtracting the row wise maxes take the exp functions::transform::Transform<T>::template transformCuda<simdOps::Exp<T>>(result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, reductionPointer, manager, tadShapeInfo, tadOffsets); __syncthreads(); //take the sum for the exponential functions::reduce::ReduceFunction<T>::template execScalarCuda<simdOps::Sum<T>>(result, resultShapeBuffer, extraParams, &maxResult, maxResultShapeBuffer, reductionPointer, manager, nullptr); __syncthreads(); //divide by the sum functions::scalar::ScalarTransform<T>::template transformCuda<simdOps::Divide<T>>(maxResult, result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, manager); __syncthreads(); functions::transform::Transform<T>::template transformCuda<simdOps::Log<T>>(result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, reductionPointer, manager, tadShapeInfo, tadOffsets); } #endif static void execSpecial( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { if (shape::isMatrix(xShapeBuffer, 2)) { auto shape = shape::shapeOf(xShapeBuffer); //iterate along rows int dimension[1] = { 0 }; int maxDimension[1] = { 1 }; //compute the row wise maxes std::vector <T> maxResult(shape[0]); #pragma omp simd for (int i = 0; i < shape[0]; i++) maxResult[i] = 0.0; Nd4jLong maxShape[2] = { shape[0], 1 }; auto maxResultShapeBuffer = shape::shapeBuffer(2, maxShape); functions::reduce::ReduceFunction<T>::template exec<simdOps::Max<T>>(dx, xShapeBuffer, extraParams, maxResult.data(), maxResultShapeBuffer, maxDimension, 1, nullptr, nullptr); //subtract max of each row functions::broadcast::Broadcast<T>::template exec<simdOps::Subtract<T>>(dx, xShapeBuffer, maxResult.data(), maxResultShapeBuffer, result, resultShapeBuffer, dimension, 1, nullptr, nullptr, nullptr, nullptr); //after subtracting the row wise maxes take the exp functions::transform::Transform<T>::template exec<simdOps::Exp<T>>(result, resultShapeBuffer, result, resultShapeBuffer, extraParams, tadShapeInfo, tadOffsets); //take the sum for the exponential functions::reduce::ReduceFunction<T>::template exec<simdOps::Sum<T>>(result, resultShapeBuffer, extraParams, maxResult.data(), maxResultShapeBuffer, maxDimension, 1, nullptr, nullptr); //divide by the sum functions::broadcast::Broadcast<T>::template exec<simdOps::Divide<T>>(result, resultShapeBuffer, maxResult.data(), maxResultShapeBuffer, result, resultShapeBuffer, dimension, 1, nullptr, nullptr, nullptr, nullptr); functions::transform::Transform<T>::template exec<simdOps::Log<T>>(result, resultShapeBuffer, result, resultShapeBuffer, extraParams, tadShapeInfo, tadOffsets); delete[] maxResultShapeBuffer; } else if (shape::isVector(xShapeBuffer, 2)) { T max = -FLOAT_MAX_VALUE; T sum = 0; auto elementWiseStride = shape::elementWiseStride(xShapeBuffer); auto length = shape::length(xShapeBuffer); if (elementWiseStride == 1) { #pragma omp simd reduction(maxT:max) for (int i = 0; i < length; i++) { max = nd4j::math::nd4j_max<T>(max, result[i]); } #pragma omp simd reduction(sumT:sum) for (int i = 0; i < length; i++) { result[i] = nd4j::math::nd4j_exp<T>(dx[i] - max); sum += result[i]; } #pragma omp simd for (int i = 0; i < length; i++) { result[i] /= sum; result[i] = nd4j::math::nd4j_log<T>(result[i]); } } else if (elementWiseStride > 1) { #pragma omp simd reduction(maxT:max) for (int i = 0; i < length; i++) { max = nd4j::math::nd4j_max<T>(max, result[i * elementWiseStride]); } #pragma omp simd reduction(sumT:sum) for (int i = 0; i < length; i++) { result[i * elementWiseStride] = nd4j::math::nd4j_exp<T>(dx[i * elementWiseStride] - max); sum += result[i * elementWiseStride]; } #pragma omp simd for (int i = 0; i < length; i++) { result[i * elementWiseStride] /= sum; result[i * elementWiseStride] = nd4j::math::nd4j_log<T>(result[i * elementWiseStride]); } } } } op_def static T op(T d1, T *params) { return nd4j::math::softplus<T>(d1); } }; /** * softmax(x) */ template<typename T> class SoftMaxDerivative { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ /** * */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto shape = shape::shapeOf(xShapeBuffer); __shared__ T maxResult; __shared__ Nd4jLong *maxResultShapeBuffer; __shared__ Nd4jLong resultEWS; auto length = shape::length(xShapeBuffer); if (threadIdx.x == 0) { resultEWS = shape::elementWiseStride(resultShapeBuffer); maxResult = (T) 0.0; } __syncthreads(); auto tride = shape::stride(xShapeBuffer); Nd4jLong maxShape[2] = { shape[0], 1 }; __shared__ Nd4jLong tempBuffer[8]; if (threadIdx.x == 0) maxResultShapeBuffer = shape::shapeBuffer(2, maxShape, tempBuffer); __syncthreads(); functions::reduce::ReduceFunction<T>::template execScalarCuda<simdOps::Max<T>>(dx, xShapeBuffer, extraParams, &maxResult, maxResultShapeBuffer, reductionPointer, manager, nullptr); __syncthreads(); //subtract max of each row functions::scalar::ScalarTransform<T>::template transformCuda<simdOps::Subtract<T>>(maxResult, dx, xShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, manager); __syncthreads(); //after subtracting the row wise maxes take the exp functions::transform::Transform<T>::template transformCuda<simdOps::Exp<T>>(result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, reductionPointer, manager, tadShapeInfo, tadOffsets); __syncthreads(); //take the sum for the exponential functions::reduce::ReduceFunction<T>::template execScalarCuda<simdOps::Sum<T>>(result, resultShapeBuffer, extraParams, &maxResult, maxResultShapeBuffer, reductionPointer, manager, nullptr); __syncthreads(); //divide by the sum functions::scalar::ScalarTransform<T>::template transformCuda<simdOps::Divide<T>>(maxResult, result, resultShapeBuffer, extraParams, result, resultShapeBuffer, allocationPointer, manager); __syncthreads(); if (resultEWS >= 1) { for (int i = threadIdx.x; i < length; i += blockDim.x) { result[i * resultEWS] = result[i * resultEWS] * ((T) 1.0 - result[i * resultEWS]); } } else { printf("Non element wise stride not supported right now\n"); } } #endif static void execSpecial( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { if (shape::isMatrix(xShapeBuffer, 2)) { auto shape = shape::shapeOf(xShapeBuffer); auto resultEleStide = shape::elementWiseStride(resultShapeBuffer); //iterate along rows int dimension[1] = { 0 }; int maxDimension[1] = { 1 }; auto len = shape::length(xShapeBuffer); //compute the row wise maxes std::vector <T> maxResult(shape[0]); #pragma omp simd for (int i = 0; i < shape[0]; i++) maxResult[i] = 0.0; Nd4jLong maxShape[2] = { shape[0], 1 }; auto maxResultShapeBuffer = shape::shapeBuffer(2, maxShape); functions::reduce::ReduceFunction<T>::template exec<simdOps::Max<T>>(dx, xShapeBuffer, extraParams, maxResult.data(), maxResultShapeBuffer, maxDimension, 1, nullptr, nullptr); //subtract max of each row functions::broadcast::Broadcast<T>::template exec<simdOps::Subtract<T>>(result, resultShapeBuffer, maxResult.data(), maxResultShapeBuffer, result, resultShapeBuffer, dimension, 1, nullptr, nullptr, nullptr, nullptr); //after subtracting the row wise maxes take the exp functions::transform::Transform<T>::template exec<simdOps::Exp<T>>(result, resultShapeBuffer, result, resultShapeBuffer, extraParams, tadShapeInfo, tadOffsets); //take the sum for the exponential functions::reduce::ReduceFunction<T>::template exec<simdOps::Sum<T>>(result, resultShapeBuffer, extraParams, maxResult.data(), maxResultShapeBuffer, maxDimension, 1, nullptr, nullptr); //divide by the sum functions::broadcast::Broadcast<T>::template exec<simdOps::Divide<T>>(result, resultShapeBuffer, maxResult.data(), maxResultShapeBuffer, result, resultShapeBuffer, dimension, 1, nullptr, nullptr, nullptr, nullptr); if (resultEleStide >= 1) { if (resultEleStide == 1) { #pragma omp simd for (int i = 0; i < len; i++) { result[i] = result[i] * ((T) 1.0f - result[i]); } } else { #pragma omp simd for (int i = 0; i < len; i++) { result[i * resultEleStide] = result[i * resultEleStide] * ((T) 1.0f - result[i * resultEleStide]); } } } else { auto zShape = shape::shapeOf(resultShapeBuffer); auto zStride = shape::stride(resultShapeBuffer); auto zRank = shape::rank(resultShapeBuffer); Nd4jLong zCoord[MAX_RANK]; for (int i = 0; i < len; i++) { shape::ind2subC(zRank,zShape, i, zCoord); Nd4jLong zOffset = shape::getOffset(0, zShape, zStride, zCoord, zRank); result[zOffset] = result[zOffset] * ((T) 1.0f - result[zOffset]); } } delete[] maxResultShapeBuffer; } else if (shape::isVector(xShapeBuffer, 2)) { T max = -FLOAT_MAX_VALUE; T sum = 0; auto elementWiseStride = shape::elementWiseStride(xShapeBuffer); auto length = shape::length(xShapeBuffer); if (elementWiseStride == 1) { #pragma omp simd reduction(maxT:max) for (int i = 0; i < length; i++) { max = nd4j::math::nd4j_max<T>(max, result[i]); } #pragma omp simd reduction(sumT:sum) for (int i = 0; i < length; i++) { result[i] -= max; result[i] = nd4j::math::nd4j_exp<T>(result[i]); sum += result[i]; } #pragma omp simd for (int i = 0; i < length; i++) { result[i] /= sum; } #pragma omp simd for (int i = 0; i < length; i++) { result[i] = result[i] * ((T) 1.0f - result[i]); } } else if (elementWiseStride >= 1) { #pragma omp simd reduction(maxT:max) for (int i = 0; i < length; i++) { max = nd4j::math::nd4j_max<T>(max, result[i * elementWiseStride]); } #pragma omp simd reduction(sumT:sum) for (int i = 0; i < length; i++) { result[i * elementWiseStride] -= max; result[i * elementWiseStride] = nd4j::math::nd4j_exp<T>(result[i * elementWiseStride]); sum += result[i * elementWiseStride]; } #pragma omp simd for (int i = 0; i < length; i++) { result[i * elementWiseStride] /= sum; } #pragma omp simd for (int i = 0; i < length; i++) { result[i * elementWiseStride] = result[i * elementWiseStride] * ((T) 1.0f - result[i * elementWiseStride]); } } else { printf("non-ews access on row not implemented yet"); } } } op_def static T op(T d1, T *params) { return nd4j::math::softplus<T>(d1); } }; template<typename T> class IsMax { public: static const bool requiresSpecial = true; #ifdef __CUDACC__ static inline __device__ void doAllCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager) { // this code is safe to delete, it's never used /* __shared__ int maxIdx; __shared__ int length; if (threadIdx.x == 0) { length = shape::length(resultShapeBuffer); } __syncthreads(); functions::indexreduce::IndexReduce<T>::template transform<simdOps::IndexMax<T>>( dx, xShapeBuffer, extraParams, result, resultShapeBuffer, nullptr, 1, 1, allocationPointer, reductionPointer, manager, nullptr, nullptr); __syncthreads(); if (threadIdx.x == 0) maxIdx = (int)result[0]; __syncthreads(); for (int i = threadIdx.x; i < length; i += blockDim.x) result[i] = 0; __syncthreads(); if (threadIdx.x == 0) { result[maxIdx] = 1.0; } */ } #endif #ifdef __CUDACC__ inline __host__ #elif defined(__GNUC__) #endif static void doAll( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams) { auto length = shape::length(xShapeBuffer); auto eleStride = shape::elementWiseStride(xShapeBuffer); auto resultEleStride = shape::elementWiseStride(resultShapeBuffer); auto xOrder = shape::order(xShapeBuffer); auto resultOrder = shape::order(resultShapeBuffer); /* int tadsPerThread = tads / TAD_THRESHOLD; int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread); num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads()); */ if (xOrder == resultOrder && xOrder == 'c') { if (eleStride == 1 && resultEleStride == 1) { if (length < ELEMENT_THRESHOLD) { int maxIdx = 0; T currMax = dx[0]; //#pragma omp simd reduction (max:maxIdx,currMax) for (int i = 0; i < length; i++) { if (currMax < dx[i]) { currMax = dx[i]; maxIdx = i; } result[i] = 0.0; } result[maxIdx] = 1.0; } else { int maxIdx = 0; T currMax = dx[0]; #pragma omp parallel proc_bind(AFFINITY) { int maxIdxLocal = maxIdx; T currMaxLocal = currMax; //#pragma omp simd reduction(max:maxIdxLocal,currMaxLocal) for (int i = 0; i < length; i++) { if (currMaxLocal < dx[i]) { currMaxLocal = dx[i]; maxIdxLocal = i; } result[i] = 0.0; } #pragma omp critical { if (currMax < currMaxLocal) { currMax = currMaxLocal; maxIdx = maxIdxLocal; } } } result[maxIdx] = 1.0; } } else { if (length < ELEMENT_THRESHOLD) { int maxIdx = 0; T currMax = dx[0]; //#pragma omp simd reduction(max:maxIdx,currMax) for (int i = 0; i < length; i++) { result[i * resultEleStride] = 0.0; if (currMax < dx[i * eleStride]) { currMax = dx[i * eleStride]; maxIdx = i; } } result[maxIdx * resultEleStride] = 1.0; } else { int maxIdx = 0; T currMax = dx[0]; #pragma omp parallel proc_bind(AFFINITY) default(shared) { int maxIdxLocal = maxIdx; T currMaxLocal = currMax; //#pragma omp simd reduction(max:maxIdxLocal,currMaxLocal) for (int i = 0; i < length; i++) { result[i * resultEleStride] = 0.0; if (currMaxLocal < dx[i * eleStride]) { currMaxLocal = dx[i * eleStride]; maxIdxLocal = i; } } #pragma omp critical { if (currMax < currMaxLocal) { currMax = currMaxLocal; maxIdx = maxIdxLocal; } } } result[maxIdx * resultEleStride] = 1.0; } } } else { Nd4jLong shapeIter[MAX_RANK]; Nd4jLong coord[MAX_RANK]; int dim; Nd4jLong xStridesIter[MAX_RANK]; Nd4jLong resultStridesIter[MAX_RANK]; auto xShape = shape::shapeOf(xShapeBuffer); auto xStride = shape::stride(xShapeBuffer); auto resultStride = shape::stride(resultShapeBuffer); auto rank = shape::rank(xShapeBuffer); T *originalResult = result; if (PrepareTwoRawArrayIter<T>(rank, xShape, dx, xStride, result, resultStride, &rank, shapeIter, &dx, xStridesIter, &result, resultStridesIter) >= 0) { T value = dx[0]; int idx = 0; int maxIdx = 0; ND4J_RAW_ITER_START(dim, rank, coord, shapeIter); { if (dx[0] > value) { value = dx[0]; maxIdx = idx; } idx++; result[0] = 0.0; } ND4J_RAW_ITER_TWO_NEXT( dim, rank, coord, shapeIter, dx, xStridesIter, result, resultStridesIter); //pointer to where max value would be if (shape::order(resultShapeBuffer) == 'c' || (shape::order(resultShapeBuffer) == 'f' && maxIdx * shape::stride(resultShapeBuffer)[shape::rank(resultShapeBuffer) - 1] >= shape::length(resultShapeBuffer))) originalResult[maxIdx] = 1.0; else originalResult[maxIdx * shape::stride(resultShapeBuffer)[shape::rank(resultShapeBuffer) - 1]] = 1.0; } } } public: #ifdef __CUDACC__ /** * */ static inline __device__ void execSpecialCuda( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { // FIXME: MAX_DIMENSION is lower then FP16 frame if (extraParams == nullptr || (int) extraParams[0] == MAX_DIMENSION) { doAllCuda(dx, xShapeBuffer, result, resultShapeBuffer, extraParams, allocationPointer, reductionPointer, manager); } } #endif static void execSpecial( T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { //FIXME: this op should be moved to CustomOps if (extraParams == nullptr || (int)extraParams[0] == 0 || ((int)extraParams[0] == 1 && (int)extraParams[1] == MAX_DIMENSION)) { doAll(dx, xShapeBuffer, result, resultShapeBuffer, extraParams); } else if (shape::isVector(xShapeBuffer)) { auto dimensionLength = (int)extraParams[0]; auto dimension = new int[dimensionLength]; auto length = shape::length(xShapeBuffer); for (int i = 0; i < dimensionLength; i++) { dimension[i] = (int)extraParams[i + 1]; } if (shape::shapeOf(xShapeBuffer)[dimension[0]] == 1) { for (int i = 0; i < length; i++) { result[i] = 1.0; } } else { auto eleStride = shape::elementWiseStride(xShapeBuffer); if (eleStride == 1) { int maxIdx = 0; T currMax = dx[0]; if (length < ELEMENT_THRESHOLD) { //#pragma omp simd reduction(max:maxIdx,currMax) for (int i = 0; i < length; i++) { if (currMax < dx[i]) { currMax = dx[i]; maxIdx = i; } result[i] = 0.0; } } else { #pragma omp parallel proc_bind(AFFINITY) default(shared) { int maxIdxLocal = maxIdx; T currMaxLocal = currMax; //#pragma omp simd reduction(max:maxIdxLocal,currMaxLocal) for (int i = 0; i < length; i++) { if (currMaxLocal < dx[i]) { currMaxLocal = dx[i]; maxIdxLocal = i; } result[i] = 0.0; } #pragma omp critical { if (currMax < currMaxLocal) { currMax = currMaxLocal; maxIdx = maxIdxLocal; } } } } result[maxIdx] = 1.0; } else { int maxIdx = 0; T currMax = dx[0]; if (length < ELEMENT_THRESHOLD) { //#pragma omp parallel for reduction(max:maxIdx,currMax) proc_bind(AFFINITY) for (int i = 0; i < length; i++) { if (currMax < dx[i * eleStride]) { currMax = dx[i * eleStride]; maxIdx = i; } result[i] = 0.0; } } else { #pragma omp parallel proc_bind(AFFINITY) default(shared) { int maxIdxLocal = maxIdx; T currMaxLocal = currMax; //#pragma omp parallel for reduction(max:maxIdx,currMax) proc_bind(AFFINITY) for (int i = 0; i < length; i++) { if (currMaxLocal < dx[i * eleStride]) { currMaxLocal = dx[i * eleStride]; maxIdxLocal = i; } result[i] = 0.0; } #pragma omp critical { if (currMax < currMaxLocal) { currMax = currMaxLocal; maxIdx = maxIdxLocal; } } } } result[maxIdx] = 1.0; } } } else { auto dimensionLength = (int) extraParams[0]; auto dimension = new int[dimensionLength]; #pragma omp simd for (int i = 0; i < dimensionLength; i++) { dimension[i] = (int) extraParams[i + 1]; } //decompose in to several sub tads after //moving all dimensions (in sorted order) //to the back. //permuted version of the x shape info for setting up the tad problem auto tadShapeShapeInfo = tadShapeInfo; shape::TAD tad (xShapeBuffer, dimension, dimensionLength); if(tadShapeInfo==nullptr) { tad.createTadOnlyShapeInfo(); tad.createOffsets(); tadShapeShapeInfo = tad.tadOnlyShapeInfo; tadOffsets = tad.tadOffsets; } auto tadLength = shape::tadLength(xShapeBuffer, dimension, dimensionLength); auto tads = shape::length(xShapeBuffer) / tadLength; int tadsPerThread = tads / TAD_THRESHOLD; int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread); num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads()); auto tadEWS = shape::elementWiseStride(tadShapeShapeInfo); auto zEWS = tadEWS; int span = (tads / num_threads) + 8; #pragma omp parallel num_threads(num_threads) if (num_threads>1) proc_bind(AFFINITY) { int tid = omp_get_thread_num(); int start = span * tid; int end = span * (tid + 1); if (end > tads) end = tads; for (int r = start; r < end; r++) { if (tadEWS > 0 && zEWS > 0 && dimensionLength == 1) { T *rX = dx + tadOffsets[r]; T *rZ = result + tadOffsets[r]; T maxValue = rX[0]; int maxIdx = 0; if (tadEWS == 1 && zEWS == 1) { //#pragma omp simd reduction(max:maxValue,maxIdx) for (int i = 0; i < tadLength; i++) { if (rX[i] > maxValue) { maxIdx = i; maxValue = rX[i]; } } #pragma omp simd for (int i = 0; i < tadLength; i++) { rZ[i] = maxIdx == i ? (T) 1.0 : (T) 0.0; } } else { //#pragma omp parallel for reduction(max:maxValue,maxIdx) default(shared) for (int i = 0; i < tadLength; i++) { if (rX[i * tadEWS] > maxValue) { maxIdx = i; maxValue = rX[i * tadEWS]; } } #pragma omp simd for (int i = 0; i < tadLength; i++) { rZ[i * zEWS] = maxIdx == i ? (T) 1.0 : (T) 0.0; } } } else { int tadsPerThread = tads / TAD_THRESHOLD; int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread); num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads()); auto offset = tadOffsets[r]; Nd4jLong shapeIter[MAX_RANK]; Nd4jLong coord[MAX_RANK]; int dim; Nd4jLong xStridesIter[MAX_RANK]; Nd4jLong resultStridesIter[MAX_RANK]; auto xShape = shape::shapeOf(tadShapeShapeInfo); auto xStride = shape::stride(tadShapeShapeInfo); auto resultStride = shape::stride(tadShapeShapeInfo); int rank = shape::rank(tadShapeShapeInfo); T *xPointer = dx + offset; T *resultPointer = result + offset; T maxValue = xPointer[0]; T *maxCursor = resultPointer; Nd4jPointer maxCursorLong = reinterpret_cast<Nd4jPointer>(maxCursor); if (PrepareTwoRawArrayIter<T>(rank, xShape, xPointer, xStride, resultPointer, resultStride, &rank, shapeIter, &xPointer, xStridesIter, &resultPointer, resultStridesIter) >= 0) { ND4J_RAW_ITER_START(dim, rank, coord, shapeIter); { if (maxValue < xPointer[0]) { maxCursor = resultPointer; maxCursorLong = reinterpret_cast<Nd4jPointer>(resultPointer); maxValue = xPointer[0]; } resultPointer[0] = 0.0; } ND4J_RAW_ITER_TWO_NEXT(dim, rank, coord, shapeIter, xPointer, xStridesIter, resultPointer, resultStridesIter); maxCursor = reinterpret_cast<T *>(maxCursorLong); maxCursor[0] = 1.0; } } } } delete[] dimension; } } op_def static T op(T d1, T *params) { return nd4j::math::softplus<T>(d1); } }; }
convolution_1x1_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // author:BUG1989 (https://github.com/BUG1989/) Long-term support. // author:FuGuangping (https://github.com/fu1899) Implemented the first version of INT8 quantization on ARMv7. // // 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 inline signed char float2int8(float v) { int int32 = round(v); if (int32 > 127) return 127; if (int32 < -127) return -127; return (signed char)int32; } #if __aarch64__ #if 1 #include "gemm_symm_int8.h" static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(outch, inch, (size_t)1u); const int8_t* a = _kernel; int8_t* sa = kernel_tm; reorder_a((int8_t*)a, sa, outch, inch, inch); } static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { const size_t n = bottom_blob.w * bottom_blob.h; const size_t k = bottom_blob.c; const size_t m = top_blob.c; ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t* pData = bottom_blob; int8_t* pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, bottom_blob.cstep); } // GEMM int32_t* pc = top_blob; const int8_t* pa = kernel; const int8_t* pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, 0, 0, opt); } static void conv1x1s1_sgemm_int8_requant_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, std::vector<float> scales_requant, const Option& opt) { const size_t n = bottom_blob.w * bottom_blob.h; const size_t k = bottom_blob.c; const size_t m = top_blob.c; ncnn::Mat scales_tm(m); ncnn::Mat bias_tm(m); float* scales = scales_tm; const float* bias = _bias; // outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); // the equation could convert to: // out = float2int8( (float)sum * (scale_requant_in * scale_requant_out) + (bias * scale_requant_out) ) // prebuild the list of (scales_requant_in*scale_requant_out) for (size_t i = 0; i < m; ++i) { scales_tm[i] = scales_requant[2 * i] * scales_requant[2 * i + 1]; } if (!_bias.empty()) { for (size_t i = 0; i < m; ++i) { bias_tm[i] = bias[i] * scales_requant[2 * i + 1]; } bias = bias_tm; } ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t* pData = bottom_blob; int8_t* pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, bottom_blob.cstep); } // GEMM int8_t* pc = top_blob; const int8_t* pa = kernel; const int8_t* pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, scales, (float*)bias, opt); } #else static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const signed char* kernel = _kernel; // kernel memory packed 4 x 4 kernel_tm.create(4 * 4, inch / 4 + inch % 4, outch / 4 + outch % 4, (size_t)1u); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; const signed char* k0 = kernel + (p + 0) * inch; const signed char* k1 = kernel + (p + 1) * inch; const signed char* k2 = kernel + (p + 2) * inch; const signed char* k3 = kernel + (p + 3) * inch; signed char* ktmp = kernel_tm.channel(p / 4); int q = 0; for (; q + 1 < inch; q += 2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp[2] = k1[0]; ktmp[3] = k1[1]; ktmp[4] = k2[0]; ktmp[5] = k2[1]; ktmp[6] = k3[0]; ktmp[7] = k3[1]; ktmp += 8; k0 += 2; k1 += 2; k2 += 2; k3 += 2; } for (; q < inch; 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; } } for (int p = remain_outch_start; p < outch; p++) { const signed char* k0 = kernel + (p + 0) * inch; signed char* ktmp = kernel_tm.channel(p / 4 + p % 4); int q = 0; for (; q + 1 < inch; q = q + 2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp += 2; k0 += 2; } for (; q < inch; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; // bottom_tm memory packed 4 x 4 ncnn::Mat bottom_tm(4, inch, size / 4 + size % 4, (size_t)1u, opt.workspace_allocator); { int nn_size = size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_blob.channel(0); const signed char* img1 = bottom_blob.channel(1); img0 += i; img1 += i; signed char* tmpptr = bottom_tm.channel(i / 4); int q = 0; for (; q + 1 < inch; q = q + 2) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img0[1]; tmpptr[3] = img1[1]; tmpptr[4] = img0[2]; tmpptr[5] = img1[2]; tmpptr[6] = img0[3]; tmpptr[7] = img1[3]; tmpptr += 8; img0 += bottom_blob.cstep; img0 += bottom_blob.cstep; img1 += bottom_blob.cstep; img1 += bottom_blob.cstep; } for (; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i / 4 + i % 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p + 1); int* outptr2 = top_blob.channel(p + 2); int* outptr3 = top_blob.channel(p + 3); int i = 0; for (; i + 3 < size; i += 4) { signed char* tmpptr = bottom_tm.channel(i / 4); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \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 "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) "ld1 {v0.16b}, [%4] \n" // i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n" // k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n" // i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n" // i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n" // i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #1024] \n" "prfm pldl1keep, [%5, #1024] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n" // i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n" // i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n" // i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n" // i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n" // w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n" // r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n" // for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n" // i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n" // k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n" // i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n" // i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n" // i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" // realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n" // w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n" // k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n" // i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n" // i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n" // i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n" // i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" "st1 {v20.4s}, [%0] \n" "st1 {v21.4s}, [%1] \n" "st1 {v22.4s}, [%2] \n" "st1 {v23.4s}, [%3] \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int q = 0; for (; q + 1 < inch; q = q + 2) { sum0_0 += tmpptr[0] * kptr[0]; sum0_0 += tmpptr[1] * kptr[1]; sum0_1 += tmpptr[2] * kptr[0]; sum0_1 += tmpptr[3] * kptr[1]; sum0_2 += tmpptr[4] * kptr[0]; sum0_2 += tmpptr[5] * kptr[1]; sum0_3 += tmpptr[6] * kptr[0]; sum0_3 += tmpptr[7] * kptr[1]; sum1_0 += tmpptr[0] * kptr[2]; sum1_0 += tmpptr[1] * kptr[3]; sum1_1 += tmpptr[2] * kptr[2]; sum1_1 += tmpptr[3] * kptr[3]; sum1_2 += tmpptr[4] * kptr[2]; sum1_2 += tmpptr[5] * kptr[3]; sum1_3 += tmpptr[6] * kptr[2]; sum1_3 += tmpptr[7] * kptr[3]; sum2_0 += tmpptr[0] * kptr[4]; sum2_0 += tmpptr[1] * kptr[5]; sum2_1 += tmpptr[2] * kptr[4]; sum2_1 += tmpptr[3] * kptr[5]; sum2_2 += tmpptr[4] * kptr[4]; sum2_2 += tmpptr[5] * kptr[5]; sum2_3 += tmpptr[6] * kptr[4]; sum2_3 += tmpptr[7] * kptr[5]; sum3_0 += tmpptr[0] * kptr[6]; sum3_0 += tmpptr[1] * kptr[7]; sum3_1 += tmpptr[2] * kptr[6]; sum3_1 += tmpptr[3] * kptr[7]; sum3_2 += tmpptr[4] * kptr[6]; sum3_2 += tmpptr[5] * kptr[7]; sum3_3 += tmpptr[6] * kptr[6]; sum3_3 += tmpptr[7] * kptr[7]; tmpptr += 8; kptr += 8; } for (; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; #endif outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } for (; i < size; i++) { signed char* tmpptr = bottom_tm.channel(i / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4); #if 0 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+3<inch; q=q+4) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8x2_t _k = vld2_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] tmpptr += 4; kptr += 16; } for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 2; kptr += 8; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); tmpptr += 1; kptr += 4; } vst1q_lane_s32(outptr0, _sum, 0); vst1q_lane_s32(outptr1, _sum, 1); vst1q_lane_s32(outptr2, _sum, 2); vst1q_lane_s32(outptr3, _sum, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q = 0; for (; q + 1 < inch; q = q + 2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[0] * kptr[2]; sum1 += tmpptr[1] * kptr[3]; sum2 += tmpptr[0] * kptr[4]; sum2 += tmpptr[1] * kptr[5]; sum3 += tmpptr[0] * kptr[6]; sum3 += tmpptr[1] * kptr[7]; tmpptr += 2; kptr += 8; } for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr += 1; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; #endif outptr0++; outptr1++; outptr2++; outptr3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); int* outptr0 = out0; int i = 0; for (; i + 3 < size; i += 4) { signed char* tmpptr = bottom_tm.channel(i / 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); #if __ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q = 0; for (; q + 1 < inch; q = q + 2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(kptr); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 8; kptr += 2; } for (; q < inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(kptr); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 tmpptr += 4; kptr += 1; } vst1q_s32(outptr0, _sum); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q = 0; for (; q + 1 < inch; q = q + 2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[2] * kptr[0]; sum1 += tmpptr[3] * kptr[1]; sum2 += tmpptr[4] * kptr[0]; sum2 += tmpptr[5] * kptr[1]; sum3 += tmpptr[6] * kptr[0]; sum3 += tmpptr[7] * kptr[1]; tmpptr += 8; kptr += 2; } for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; #endif outptr0 += 4; } for (; i < size; i++) { signed char* tmpptr = bottom_tm.channel(i / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); int q = 0; int sum0 = 0; for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } } static void conv1x1s1_sgemm_int8_requant_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // bottom_tm memory packed 4 x 4 ncnn::Mat bottom_tm(4, inch, size / 4 + size % 4, (size_t)1u, opt.workspace_allocator); { int nn_size = size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_blob.channel(0); const signed char* img1 = bottom_blob.channel(1); img0 += i; img1 += i; signed char* tmpptr = bottom_tm.channel(i / 4); int q = 0; for (; q + 1 < inch; q = q + 2) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img0[1]; tmpptr[3] = img1[1]; tmpptr[4] = img0[2]; tmpptr[5] = img1[2]; tmpptr[6] = img0[3]; tmpptr[7] = img1[3]; tmpptr += 8; img0 += bottom_blob.cstep; img0 += bottom_blob.cstep; img1 += bottom_blob.cstep; img1 += bottom_blob.cstep; } for (; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i / 4 + i % 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; signed char* outptr0 = top_blob.channel(p); signed char* outptr1 = top_blob.channel(p + 1); signed char* outptr2 = top_blob.channel(p + 2); signed char* outptr3 = top_blob.channel(p + 3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float scale_requant_in0 = scales_requant[2 * p]; const float scale_requant_out0 = scales_requant[2 * p + 1]; const float scale_requant_in1 = scales_requant[2 * (p + 1)]; const float scale_requant_out1 = scales_requant[2 * (p + 1) + 1]; const float scale_requant_in2 = scales_requant[2 * (p + 2)]; const float scale_requant_out2 = scales_requant[2 * (p + 2) + 1]; const float scale_requant_in3 = scales_requant[2 * (p + 3)]; const float scale_requant_out3 = scales_requant[2 * (p + 3) + 1]; float32x4_t _bias03, _scale_in03, _scale_out03; float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _bias1 = vdupq_n_f32(bias1); float32x4_t _bias2 = vdupq_n_f32(bias2); float32x4_t _bias3 = vdupq_n_f32(bias3); _bias03[0] = bias0; _bias03[1] = bias1; _bias03[2] = bias2; _bias03[3] = bias3; _scale_in03[0] = scale_requant_in0; _scale_in03[1] = scale_requant_in1; _scale_in03[2] = scale_requant_in2; _scale_in03[3] = scale_requant_in3; _scale_out03[0] = scale_requant_out0; _scale_out03[1] = scale_requant_out1; _scale_out03[2] = scale_requant_out2; _scale_out03[3] = scale_requant_out3; int i = 0; for (; i + 3 < size; i += 4) { signed char* tmpptr = bottom_tm.channel(i / 4); const signed char* kptr = kernel.channel(p / 4); #if 1 //__ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \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 "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) "ld1 {v0.16b}, [%4] \n" // i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n" // k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n" // i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n" // i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n" // i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #1024] \n" "prfm pldl1keep, [%5, #1024] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n" // i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n" // i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n" // i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n" // i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n" // w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n" // r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n" // for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n" // i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n" // k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n" // i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n" // i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n" // i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" // realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n" // w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n" // k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n" // i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n" // i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n" // i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n" // i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" // top_s32 -> top_f32 "scvtf v20.4s, v20.4s \n" "scvtf v21.4s, v21.4s \n" "scvtf v22.4s, v22.4s \n" "scvtf v23.4s, v23.4s \n" // top_f32 = top_f32 * scale_in "fmul v20.4s, v20.4s, %17.s[0] \n" "fmul v21.4s, v21.4s, %17.s[1] \n" "fmul v22.4s, v22.4s, %17.s[2] \n" "fmul v23.4s, v23.4s, %17.s[3] \n" // top_f32 = top_f32 + bias "fadd v20.4s, v20.4s, %13.4s \n" "fadd v21.4s, v21.4s, %14.4s \n" "fadd v22.4s, v22.4s, %15.4s \n" "fadd v23.4s, v23.4s, %16.4s \n" // top_f32 = top_f32 * scale_out "fmul v20.4s, v20.4s, %18.s[0] \n" "fmul v21.4s, v21.4s, %18.s[1] \n" "fmul v22.4s, v22.4s, %18.s[2] \n" "fmul v23.4s, v23.4s, %18.s[3] \n" // top_f32 -> top_s32 "fcvtas v20.4s, v20.4s \n" "fcvtas v21.4s, v21.4s \n" "fcvtas v22.4s, v22.4s \n" "fcvtas v23.4s, v23.4s \n" // top_s32 -> top_s16 "sqxtn v7.4h, v20.4s \n" "sqxtn2 v7.8h, v21.4s \n" "sqxtn v8.4h, v22.4s \n" "sqxtn2 v8.8h, v23.4s \n" // top_s16 -> top_s8 "sqxtn v0.8b, v7.8h \n" "sqxtn v1.8b, v8.8h \n" // save top_s8 "st1 {v0.s}[0], [%0] \n" "st1 {v0.s}[1], [%1] \n" "st1 {v1.s}[0], [%2] \n" "st1 {v1.s}[1], [%3] \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "w"(_bias0), // %13 "w"(_bias1), // %14 "w"(_bias2), // %15 "w"(_bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "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 int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int q = 0; for (; q + 1 < inch; q = q + 2) { sum0_0 += tmpptr[0] * kptr[0]; sum0_0 += tmpptr[1] * kptr[1]; sum0_1 += tmpptr[2] * kptr[0]; sum0_1 += tmpptr[3] * kptr[1]; sum0_2 += tmpptr[4] * kptr[0]; sum0_2 += tmpptr[5] * kptr[1]; sum0_3 += tmpptr[6] * kptr[0]; sum0_3 += tmpptr[7] * kptr[1]; sum1_0 += tmpptr[0] * kptr[2]; sum1_0 += tmpptr[1] * kptr[3]; sum1_1 += tmpptr[2] * kptr[2]; sum1_1 += tmpptr[3] * kptr[3]; sum1_2 += tmpptr[4] * kptr[2]; sum1_2 += tmpptr[5] * kptr[3]; sum1_3 += tmpptr[6] * kptr[2]; sum1_3 += tmpptr[7] * kptr[3]; sum2_0 += tmpptr[0] * kptr[4]; sum2_0 += tmpptr[1] * kptr[5]; sum2_1 += tmpptr[2] * kptr[4]; sum2_1 += tmpptr[3] * kptr[5]; sum2_2 += tmpptr[4] * kptr[4]; sum2_2 += tmpptr[5] * kptr[5]; sum2_3 += tmpptr[6] * kptr[4]; sum2_3 += tmpptr[7] * kptr[5]; sum3_0 += tmpptr[0] * kptr[6]; sum3_0 += tmpptr[1] * kptr[7]; sum3_1 += tmpptr[2] * kptr[6]; sum3_1 += tmpptr[3] * kptr[7]; sum3_2 += tmpptr[4] * kptr[6]; sum3_2 += tmpptr[5] * kptr[7]; sum3_3 += tmpptr[6] * kptr[6]; sum3_3 += tmpptr[7] * kptr[7]; tmpptr += 8; kptr += 8; } for (; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = float2int8(((float)sum0_0 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[1] = float2int8(((float)sum0_1 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[2] = float2int8(((float)sum0_2 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[3] = float2int8(((float)sum0_3 * scale_requant_in0 + bias0) * scale_requant_out0); outptr1[0] = float2int8(((float)sum1_0 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[1] = float2int8(((float)sum1_1 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[2] = float2int8(((float)sum1_2 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[3] = float2int8(((float)sum1_3 * scale_requant_in1 + bias1) * scale_requant_out1); outptr2[0] = float2int8(((float)sum2_0 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[1] = float2int8(((float)sum2_1 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[2] = float2int8(((float)sum2_2 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[3] = float2int8(((float)sum2_3 * scale_requant_in2 + bias2) * scale_requant_out2); outptr3[0] = float2int8(((float)sum3_0 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[1] = float2int8(((float)sum3_1 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[2] = float2int8(((float)sum3_2 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[3] = float2int8(((float)sum3_3 * scale_requant_in3 + bias3) * scale_requant_out3); #endif outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } for (; i < size; i++) { signed char* tmpptr = bottom_tm.channel(i / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4); #if 1 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q = 0; for (; q + 3 < inch; q = q + 4) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8x2_t _k = vld2_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] tmpptr += 4; kptr += 16; } for (; q + 1 < inch; q = q + 2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 2; kptr += 8; } for (; q < inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); tmpptr += 1; kptr += 4; } // top_s32 -> top_f32 float32x4_t _sum_f32 = vcvtq_f32_s32(_sum); // top_f32 = top_f32 * scale_in _sum_f32 = vmulq_f32(_sum_f32, _scale_in03); // top_f32 = top_f32 + bias _sum_f32 = vaddq_f32(_sum_f32, _bias03); // top_f32 = top_f32 * scale_out _sum_f32 = vmulq_f32(_sum_f32, _scale_out03); // top_f32 -> top_s32 _sum = vcvtaq_s32_f32(_sum_f32); // top_s32 -> top_s16 int16x4_t _sum_s16 = vqmovn_s32(_sum); int16x8_t _sum_s16_tp = vcombine_s16(_sum_s16, _sum_s16); // top_s16 -> top_s8 int8x8_t _sum_s8 = vqmovn_s16(_sum_s16_tp); // save top_s8 vst1_lane_s8(outptr0, _sum_s8, 0); vst1_lane_s8(outptr1, _sum_s8, 1); vst1_lane_s8(outptr2, _sum_s8, 2); vst1_lane_s8(outptr3, _sum_s8, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q = 0; for (; q + 1 < inch; q = q + 2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[0] * kptr[2]; sum1 += tmpptr[1] * kptr[3]; sum2 += tmpptr[0] * kptr[4]; sum2 += tmpptr[1] * kptr[5]; sum3 += tmpptr[0] * kptr[6]; sum3 += tmpptr[1] * kptr[7]; tmpptr += 2; kptr += 8; } for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr += 1; kptr += 4; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in0 + bias0) * scale_requant_out0); outptr1[0] = float2int8(((float)sum1 * scale_requant_in1 + bias1) * scale_requant_out1); outptr2[0] = float2int8(((float)sum2 * scale_requant_in2 + bias2) * scale_requant_out2); outptr3[0] = float2int8(((float)sum3 * scale_requant_in3 + bias3) * scale_requant_out3); #endif outptr0++; outptr1++; outptr2++; outptr3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); signed char* outptr0 = out0; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2 * p]; const float scale_requant_out = scales_requant[2 * p + 1]; float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _scale_in = vdupq_n_f32(scale_requant_in); float32x4_t _scale_out = vdupq_n_f32(scale_requant_out); int i = 0; for (; i + 3 < size; i += 4) { signed char* tmpptr = bottom_tm.channel(i / 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); #if 1 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q = 0; for (; q + 1 < inch; q = q + 2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(kptr); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 8; kptr += 2; } for (; q < inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(kptr); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 tmpptr += 4; kptr += 1; } // top_s32 -> top_f32 float32x4_t _sum_f32 = vcvtq_f32_s32(_sum); // top_f32 = top_f32 * scale_in _sum_f32 = vmulq_f32(_sum_f32, _scale_in); // top_f32 = top_f32 + bias _sum_f32 = vaddq_f32(_sum_f32, _bias0); // top_f32 = top_f32 * scale_out _sum_f32 = vmulq_f32(_sum_f32, _scale_out); // top_f32 -> top_s32 _sum = vcvtaq_s32_f32(_sum_f32); // top_s32 -> top_s16 int16x4_t _sum_s16 = vqmovn_s32(_sum); int16x8_t _sum_s16_tp = vcombine_s16(_sum_s16, _sum_s16); // top_s16 -> top_s8 int8x8_t _sum_s8 = vqmovn_s16(_sum_s16_tp); // save top_s8 vst1_s8(outptr0, _sum_s8); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q = 0; for (; q + 1 < inch; q = q + 2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[2] * kptr[0]; sum1 += tmpptr[3] * kptr[1]; sum2 += tmpptr[4] * kptr[0]; sum2 += tmpptr[5] * kptr[1]; sum3 += tmpptr[6] * kptr[0]; sum3 += tmpptr[7] * kptr[1]; tmpptr += 8; kptr += 2; } for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); outptr0[1] = float2int8(((float)sum1 * scale_requant_in + bias0) * scale_requant_out); outptr0[2] = float2int8(((float)sum2 * scale_requant_in + bias0) * scale_requant_out); outptr0[3] = float2int8(((float)sum3 * scale_requant_in + bias0) * scale_requant_out); #endif outptr0 += 4; } for (; i < size; i++) { signed char* tmpptr = bottom_tm.channel(i / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); int q = 0; int sum0 = 0; for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); outptr0++; } } } #endif #else static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const signed char* kernel = _kernel; kernel_tm.create(4 * 4, inch / 4 + inch % 4, outch / 4 + outch % 4, (size_t)1u); int p = 0; for (; p + 3 < outch; p += 4) { const signed char* kernel0 = kernel + (p + 0) * inch; const signed char* kernel1 = kernel + (p + 1) * inch; const signed char* kernel2 = kernel + (p + 2) * inch; const signed char* kernel3 = kernel + (p + 3) * inch; signed char* ktmp = kernel_tm.channel(p / 4); for (int q = 0; q < inch; q++) { // kernel0...3 0 ktmp[0] = kernel0[0]; ktmp[1] = kernel1[0]; ktmp[2] = kernel2[0]; ktmp[3] = kernel3[0]; ktmp += 4; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; } } for (; p < outch; p++) { const signed char* kernel0 = kernel + p * inch; signed char* ktmp = kernel_tm.channel(p / 4 + p % 4); for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[0]; ktmp++; kernel0++; } } } /* * Convolution 1x1 quantized with sgemm int8 */ static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; // interleave Mat tmp(8 * 4, inch / 4 + inch % 4, size / 8 + (size % 8) / 4 + size % 4, 1u, opt.workspace_allocator); { int nn_size = 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 signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { #if __ARM_NEON asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "d0"); img0 += bottom_blob.cstep; #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]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } 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; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p + 1); int* outptr2 = top_blob.channel(p + 2); int* outptr3 = top_blob.channel(p + 3); int i = 0; for (; i + 7 < size; i += 8) { const signed char* tmpptr = tmp.channel(i / 8); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4-d7}, [%4]! \n" // tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n" // a30-a37 "vmovl.s8 q4, d6 \n" // a20-a27 "vmovl.s8 q3, d5 \n" // a10-a17 "vmovl.s8 q2, d4 \n" // a00-a07 "vld1.s8 {d0-d1}, [%5]! \n" // kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n" // k02-k32,k03-k33 "vmovl.s8 q0, d0 \n" // k00-k30,k01-k31 "vmlal.s16 q6, d4, d0[0] \n" // sum0 = (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q8, d4, d0[1] \n" // sum1 = (a00-a07) * k10 "vmlal.s16 q9, d5, d0[1] \n" "vmlal.s16 q10, d4, d0[2] \n" // sum2 = (a00-a07) * k20 "vmlal.s16 q11, d5, d0[2] \n" "vmlal.s16 q12, d4, d0[3] \n" // sum3 = (a00-a07) * k30 "vmlal.s16 q13, d5, d0[3] \n" "vmlal.s16 q6, d6, d1[0] \n" // sum0 += (a10-a17) * k01 "vmlal.s16 q7, d7, d1[0] \n" "vmlal.s16 q8, d6, d1[1] \n" // sum1 += (a10-a17) * k11 "vmlal.s16 q9, d7, d1[1] \n" "vmlal.s16 q10, d6, d1[2] \n" // sum2 += (a10-a17) * k21 "vmlal.s16 q11, d7, d1[2] \n" "vmlal.s16 q12, d6, d1[3] \n" // sum3 += (a10-a17) * k31 "vmlal.s16 q13, d7, d1[3] \n" "vmlal.s16 q6, d8, d2[0] \n" // sum0 += (a20-a27) * k02 "vmlal.s16 q7, d9, d2[0] \n" "vmlal.s16 q8, d8, d2[1] \n" // sum1 += (a20-a27) * k12 "vmlal.s16 q9, d9, d2[1] \n" "vmlal.s16 q10, d8, d2[2] \n" // sum2 += (a20-a27) * k22 "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d2[3] \n" // sum3 += (a20-a27) * k32 "vmlal.s16 q13, d9, d2[3] \n" "vmlal.s16 q6, d10, d3[0] \n" // sum0 += (a30-a37) * k03 "vmlal.s16 q7, d11, d3[0] \n" "vmlal.s16 q8, d10, d3[1] \n" // sum1 += (a30-a37) * k13 "vmlal.s16 q9, d11, d3[1] \n" "vmlal.s16 q10, d10, d3[2] \n" // sum2 += (a30-a37) * k23 "vmlal.s16 q11, d11, d3[2] \n" "vmlal.s16 q12, d10, d3[3] \n" // sum3 += (a30-a37) * k33 "vmlal.s16 q13, d11, d3[3] \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--) "vld1.s8 {d2}, [%4]! \n" // tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%5] \n" // kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n" // sum0 += (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "vmlal.s16 q8, d2, d0[1] \n" // sum1 += (a00-a07) * k10 "vmlal.s16 q9, d3, d0[1] \n" "vmlal.s16 q10, d2, d0[2] \n" // sum2 += (a00-a07) * k20 "vmlal.s16 q11, d3, d0[2] \n" "vmlal.s16 q12, d2, d0[3] \n" // sum3 += (a00-a07) * k30 "vmlal.s16 q13, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vst1.s32 {d12-d15}, [%0]! \n" "vst1.s32 {d16-d19}, [%1]! \n" "vst1.s32 {d20-d23}, [%2]! \n" "vst1.s32 {d24-d27}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum0_4 = 0; int sum0_5 = 0; int sum0_6 = 0; int sum0_7 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum1_4 = 0; int sum1_5 = 0; int sum1_6 = 0; int sum1_7 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum2_4 = 0; int sum2_5 = 0; int sum2_6 = 0; int sum2_7 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int sum3_4 = 0; int sum3_5 = 0; int sum3_6 = 0; int sum3_7 = 0; for (int q = 0; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i + 3 < size; i += 4) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4-d5}, [%4]! \n" // tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n" // a20-a23,a30-a33 "vmovl.s8 q2, d4 \n" // a00-a04,a10-a14 "vld1.s8 {d0-d1}, [%5]! \n" // kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n" // k02-k32,k03-k33 "vmovl.s8 q0, d0 \n" // k00-k30,k01-k31 "vmlal.s16 q6, d4, d0[0] \n" // sum0 = (a00-a03) * k00 "vmlal.s16 q7, d4, d0[1] \n" // sum1 = (a00-a03) * k10 "vmlal.s16 q8, d4, d0[2] \n" // sum2 = (a00-a03) * k20 "vmlal.s16 q9, d4, d0[3] \n" // sum3 = (a00-a03) * k30 "vmlal.s16 q6, d5, d1[0] \n" // sum0 += (a10-a13) * k01 "vmlal.s16 q7, d5, d1[1] \n" // sum1 += (a10-a13) * k11 "vmlal.s16 q8, d5, d1[2] \n" // sum2 += (a10-a13) * k21 "vmlal.s16 q9, d5, d1[3] \n" // sum3 += (a10-a13) * k31 "vmlal.s16 q6, d6, d2[0] \n" // sum0 += (a20-a23) * k02 "vmlal.s16 q7, d6, d2[1] \n" // sum1 += (a20-a23) * k12 "vmlal.s16 q8, d6, d2[2] \n" // sum2 += (a20-a23) * k22 "vmlal.s16 q9, d6, d2[3] \n" // sum3 += (a20-a23) * k32 "vmlal.s16 q6, d7, d3[0] \n" // sum0 += (a30-a33) * k03 "vmlal.s16 q7, d7, d3[1] \n" // sum1 += (a30-a33) * k13 "vmlal.s16 q8, d7, d3[2] \n" // sum2 += (a30-a33) * k23 "vmlal.s16 q9, d7, d3[3] \n" // sum3 += (a30-a33) * k33 "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--) "vld1.s8 {d2}, [%4] \n" // tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%5] \n" // kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #4 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n" // sum0 += (a00-a03) * k00 "vmlal.s16 q7, d2, d0[1] \n" // sum1 += (a00-a03) * k10 "vmlal.s16 q8, d2, d0[2] \n" // sum2 += (a00-a03) * k20 "vmlal.s16 q9, d2, d0[3] \n" // sum3 += (a00-a03) * k30 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vst1.s32 {d12-d13}, [%0]! \n" "vst1.s32 {d14-d15}, [%1]! \n" "vst1.s32 {d16-d17}, [%2]! \n" "vst1.s32 {d18-d19}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; for (int q = 0; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "vmov.s32 q10, #0 \n" "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4}, [%4] \n" // tmpr a00,a10,a20,a30 a(inch)(data) "add %4, #4 \n" "vmovl.s8 q2, d4 \n" // a00,a10,a20,a30 "vld1.s8 {d0-d1}, [%5]! \n" // kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n" // k02-k32,k03-k33 "vmovl.s8 q0, d0 \n" // k00-k30,k01-k31 "vmlal.s16 q6, d0, d4[0] \n" // (k00-k30) * a00 "vmlal.s16 q7, d1, d4[1] \n" // (k01-k31) * a10 "vmlal.s16 q8, d2, d4[2] \n" // (k02-k32) * a20 "vmlal.s16 q9, d3, d4[3] \n" // (k03-k33) * a30 "subs r4, r4, #1 \n" "bne 0b \n" // end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q10, q6, q9 \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--) "vld1.s8 {d2}, [%4] \n" // tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n" // kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q10, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vst1.s32 {d20[0]}, [%0]! \n" "vst1.s32 {d20[1]}, [%1]! \n" "vst1.s32 {d21[0]}, [%2]! \n" "vst1.s32 {d21[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); int* outptr0 = out0; int i = 0; for (; i + 7 < size; i += 8) { const signed char* tmpptr = tmp.channel(i / 8); const signed char* kptr = kernel.channel(p / 4 + p % 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n" // tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n" // a30-a37 "vmovl.s8 q4, d6 \n" // a20-a27 "vmovl.s8 q3, d5 \n" // a10-a17 "vmovl.s8 q2, d4 \n" // a00-a07 "vld1.s8 {d0}, [%2] \n" // kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n" // k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n" // (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n" // (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n" // (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n" // (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "subs r4, r4, #1 \n" "bne 0b \n" // end for "1: \n" // remain loop "and r4, %6, #3 \n" // r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" // for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n" // tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n" // kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n" // (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vst1.s32 {d12-d15}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7"); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i + 3 < size; i += 4) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "lsr r4, %6, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%2, #128] \n" "vld1.s8 {d4-d5}, [%1]! \n" // tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n" // a20-a23,a30-a33 "vmovl.s8 q2, d4 \n" // a00-a03,a10-a13 "vld1.s8 {d0}, [%2] \n" // kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n" // k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n" // (a00-a03) * k00 "vmlal.s16 q6, d5, d0[1] \n" // (a10-a13) * k01 "vmlal.s16 q6, d6, d0[2] \n" // (a20-a23) * k02 "vmlal.s16 q6, d7, d0[3] \n" // (a30-a33) * k03 "subs r4, r4, #1 \n" "bne 0b \n" // end for "1: \n" // remain loop "and r4, %6, #3 \n" // r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" // for(; remain != 0; remain--) "vld1.s8 {d2}, [%1] \n" // tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%2] \n" // kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %1, #4 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n" // (a00-a03) * k00 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vst1.s32 {d12-d13}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6"); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); int q = 0; int sum0 = 0; for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } // // NOTE sgemm int8 // for (; p<outch; p++) // { // Mat out0 = top_blob.channel(p); // // int* outptr0 = out0; // // for (int i=0; i<size; i++) // { // int sum = 0; // // const signed char* kptr = _kernel.channel(p/8 + p%8); // // for (int q=0; q<inch; q++) // { // const signed char* img0 = bottom_blob.channel(q); // // sum += img0[i] * kptr[0]; // kptr ++; // } // // outptr0[i] = sum; // } // } } static void conv1x1s1_sgemm_int8_requant_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // interleave Mat tmp(8 * 4, inch / 4 + inch % 4, size / 8 + (size % 8) / 4 + size % 4, 1u, opt.workspace_allocator); { int nn_size = 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 signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { #if __ARM_NEON asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "d0"); img0 += bottom_blob.cstep; #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]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } 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; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; signed char* outptr0 = top_blob.channel(p); signed char* outptr1 = top_blob.channel(p + 1); signed char* outptr2 = top_blob.channel(p + 2); signed char* outptr3 = top_blob.channel(p + 3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float scale_requant_in0 = scales_requant[2 * p]; const float scale_requant_out0 = scales_requant[2 * p + 1]; const float scale_requant_in1 = scales_requant[2 * (p + 1)]; const float scale_requant_out1 = scales_requant[2 * (p + 1) + 1]; const float scale_requant_in2 = scales_requant[2 * (p + 2)]; const float scale_requant_out2 = scales_requant[2 * (p + 2) + 1]; const float scale_requant_in3 = scales_requant[2 * (p + 3)]; const float scale_requant_out3 = scales_requant[2 * (p + 3) + 1]; #if __ARM_NEON float32x4_t _bias03, _scale_in03, _scale_out03; _bias03[0] = bias0; _bias03[1] = bias1; _bias03[2] = bias2; _bias03[3] = bias3; _scale_in03[0] = scale_requant_in0; _scale_in03[1] = scale_requant_in1; _scale_in03[2] = scale_requant_in2; _scale_in03[3] = scale_requant_in3; _scale_out03[0] = scale_requant_out0; _scale_out03[1] = scale_requant_out1; _scale_out03[2] = scale_requant_out2; _scale_out03[3] = scale_requant_out3; #endif // __ARM_NEON int i = 0; for (; i + 7 < size; i += 8) { const signed char* tmpptr = tmp.channel(i / 8); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d28-d31}, [%4]! \n" // tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d31 \n" // a30-a37 "vmovl.s8 q4, d30 \n" // a20-a27 "vmovl.s8 q15, d29 \n" // a10-a17 "vmovl.s8 q14, d28 \n" // a00-a07 "vld1.s8 {d0-d1}, [%5]! \n" // kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n" // k02-k32,k03-k33 "vmovl.s8 q0, d0 \n" // k00-k30,k01-k31 "vmlal.s16 q6, d28, d0[0] \n" // sum0 = (a00-a07) * k00 "vmlal.s16 q7, d29, d0[0] \n" "vmlal.s16 q8, d28, d0[1] \n" // sum1 = (a00-a07) * k10 "vmlal.s16 q9, d29, d0[1] \n" "vmlal.s16 q10, d28, d0[2] \n" // sum2 = (a00-a07) * k20 "vmlal.s16 q11, d29, d0[2] \n" "vmlal.s16 q12, d28, d0[3] \n" // sum3 = (a00-a07) * k30 "vmlal.s16 q13, d29, d0[3] \n" "vmlal.s16 q6, d30, d1[0] \n" // sum0 += (a10-a17) * k01 "vmlal.s16 q7, d31, d1[0] \n" "vmlal.s16 q8, d30, d1[1] \n" // sum1 += (a10-a17) * k11 "vmlal.s16 q9, d31, d1[1] \n" "vmlal.s16 q10, d30, d1[2] \n" // sum2 += (a10-a17) * k21 "vmlal.s16 q11, d31, d1[2] \n" "vmlal.s16 q12, d30, d1[3] \n" // sum3 += (a10-a17) * k31 "vmlal.s16 q13, d31, d1[3] \n" "vmlal.s16 q6, d8, d2[0] \n" // sum0 += (a20-a27) * k02 "vmlal.s16 q7, d9, d2[0] \n" "vmlal.s16 q8, d8, d2[1] \n" // sum1 += (a20-a27) * k12 "vmlal.s16 q9, d9, d2[1] \n" "vmlal.s16 q10, d8, d2[2] \n" // sum2 += (a20-a27) * k22 "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d2[3] \n" // sum3 += (a20-a27) * k32 "vmlal.s16 q13, d9, d2[3] \n" "vmlal.s16 q6, d10, d3[0] \n" // sum0 += (a30-a37) * k03 "vmlal.s16 q7, d11, d3[0] \n" "vmlal.s16 q8, d10, d3[1] \n" // sum1 += (a30-a37) * k13 "vmlal.s16 q9, d11, d3[1] \n" "vmlal.s16 q10, d10, d3[2] \n" // sum2 += (a30-a37) * k23 "vmlal.s16 q11, d11, d3[2] \n" "vmlal.s16 q12, d10, d3[3] \n" // sum3 += (a30-a37) * k33 "vmlal.s16 q13, d11, d3[3] \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--) "vld1.s8 {d2}, [%4]! \n" // tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%5] \n" // kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n" // sum0 += (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "vmlal.s16 q8, d2, d0[1] \n" // sum1 += (a00-a07) * k10 "vmlal.s16 q9, d3, d0[1] \n" "vmlal.s16 q10, d2, d0[2] \n" // sum2 += (a00-a07) * k20 "vmlal.s16 q11, d3, d0[2] \n" "vmlal.s16 q12, d2, d0[3] \n" // sum3 += (a00-a07) * k30 "vmlal.s16 q13, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vdup.f32 q14, %13 \n" // bias "vdup.f32 q15, %14 \n" // bias "vdup.f32 q4, %15 \n" // bias "vdup.f32 q5, %16 \n" // bias // sum0 // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" "vcvt.f32.s32 q9, q9 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q6, q6, %e17[0] \n" "vmul.f32 q7, q7, %e17[0] \n" "vmul.f32 q8, q8, %e17[1] \n" "vmul.f32 q9, q9, %e17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q14 \n" "vadd.f32 q8, q8, q15 \n" "vadd.f32 q9, q9, q15 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %e18[0] \n" "vmul.f32 q1, q7, %e18[0] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12}, [%0]! \n" // sum1 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q8, %e18[1] \n" "vmul.f32 q1, q9, %e18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d16, q0 \n" "vqmovn.s32 d17, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d16, q8 \n" // save top_s8 "vst1.8 {d16}, [%1]! \n" // sum2 // top_s32 -> top_f32 "vcvt.f32.s32 q10, q10 \n" "vcvt.f32.s32 q11, q11 \n" "vcvt.f32.s32 q12, q12 \n" "vcvt.f32.s32 q13, q13 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q10, q10, %f17[0] \n" "vmul.f32 q11, q11, %f17[0] \n" "vmul.f32 q12, q12, %f17[1] \n" "vmul.f32 q13, q13, %f17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q10, q10, q4 \n" "vadd.f32 q11, q11, q4 \n" "vadd.f32 q12, q12, q5 \n" "vadd.f32 q13, q13, q5 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q10, %f18[0] \n" "vmul.f32 q1, q11, %f18[0] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d20, q0 \n" "vqmovn.s32 d21, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d20, q10 \n" // save top_s8 "vst1.8 {d20}, [%2]! \n" // sum3 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q12, %f18[1] \n" "vmul.f32 q1, q13, %f18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d24, q0 \n" "vqmovn.s32 d25, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d24, q12 \n" // save top_s8 "vst1.8 {d24}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "r"(bias0), // %13 "r"(bias1), // %14 "r"(bias2), // %15 "r"(bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "r4", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum0_4 = 0; int sum0_5 = 0; int sum0_6 = 0; int sum0_7 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum1_4 = 0; int sum1_5 = 0; int sum1_6 = 0; int sum1_7 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum2_4 = 0; int sum2_5 = 0; int sum2_6 = 0; int sum2_7 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int sum3_4 = 0; int sum3_5 = 0; int sum3_6 = 0; int sum3_7 = 0; for (int q = 0; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i + 3 < size; i += 4) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d28-d29}, [%4]! \n" // tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q15, d29 \n" // a20-a23,a30-a33 "vmovl.s8 q14, d28 \n" // a00-a04,a10-a14 "vld1.s8 {d0-d1}, [%5]! \n" // kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n" // k02-k32,k03-k33 "vmovl.s8 q0, d0 \n" // k00-k30,k01-k31 "vmlal.s16 q6, d28, d0[0] \n" // sum0 = (a00-a03) * k00 "vmlal.s16 q7, d28, d0[1] \n" // sum1 = (a00-a03) * k10 "vmlal.s16 q8, d28, d0[2] \n" // sum2 = (a00-a03) * k20 "vmlal.s16 q9, d28, d0[3] \n" // sum3 = (a00-a03) * k30 "vmlal.s16 q6, d29, d1[0] \n" // sum0 += (a10-a13) * k01 "vmlal.s16 q7, d29, d1[1] \n" // sum1 += (a10-a13) * k11 "vmlal.s16 q8, d29, d1[2] \n" // sum2 += (a10-a13) * k21 "vmlal.s16 q9, d29, d1[3] \n" // sum3 += (a10-a13) * k31 "vmlal.s16 q6, d30, d2[0] \n" // sum0 += (a20-a23) * k02 "vmlal.s16 q7, d30, d2[1] \n" // sum1 += (a20-a23) * k12 "vmlal.s16 q8, d30, d2[2] \n" // sum2 += (a20-a23) * k22 "vmlal.s16 q9, d30, d2[3] \n" // sum3 += (a20-a23) * k32 "vmlal.s16 q6, d31, d3[0] \n" // sum0 += (a30-a33) * k03 "vmlal.s16 q7, d31, d3[1] \n" // sum1 += (a30-a33) * k13 "vmlal.s16 q8, d31, d3[2] \n" // sum2 += (a30-a33) * k23 "vmlal.s16 q9, d31, d3[3] \n" // sum3 += (a30-a33) * k33 "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--) "vld1.s8 {d2}, [%4] \n" // tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%5] \n" // kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #4 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n" // sum0 += (a00-a03) * k00 "vmlal.s16 q7, d2, d0[1] \n" // sum1 += (a00-a03) * k10 "vmlal.s16 q8, d2, d0[2] \n" // sum2 += (a00-a03) * k20 "vmlal.s16 q9, d2, d0[3] \n" // sum3 += (a00-a03) * k30 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory "vdup.f32 q14, %13 \n" // bias "vdup.f32 q15, %14 \n" // bias "vdup.f32 q4, %15 \n" // bias "vdup.f32 q5, %16 \n" // bias // sum0-1 // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" "vcvt.f32.s32 q9, q9 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q6, q6, %e17[0] \n" "vmul.f32 q7, q7, %e17[1] \n" "vmul.f32 q8, q8, %f17[0] \n" "vmul.f32 q9, q9, %f17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q15 \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %e18[0] \n" "vmul.f32 q1, q7, %e18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.s32 {d12[0]}, [%0]! \n" "vst1.s32 {d12[1]}, [%1]! \n" // sum1-2 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q8, %f18[0] \n" "vmul.f32 q1, q9, %f18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d16, q0 \n" "vqmovn.s32 d17, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d16, q8 \n" // save top_s8 "vst1.s32 {d16[0]}, [%2]! \n" "vst1.s32 {d16[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "r"(bias0), // %13 "r"(bias1), // %14 "r"(bias2), // %15 "r"(bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "r4", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; for (int q = 0; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4); #if __ARM_NEON asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "vmov.s32 q10, #0 \n" "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4}, [%4] \n" // tmpr a00,a10,a20,a30 a(inch)(data) "add %4, #4 \n" "vmovl.s8 q2, d4 \n" // a00,a10,a20,a30 "vld1.s8 {d0-d1}, [%5]! \n" // kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n" // k02-k32,k03-k33 "vmovl.s8 q0, d0 \n" // k00-k30,k01-k31 "vmlal.s16 q6, d0, d4[0] \n" // (k00-k30) * a00 "vmlal.s16 q7, d1, d4[1] \n" // (k01-k31) * a10 "vmlal.s16 q8, d2, d4[2] \n" // (k02-k32) * a20 "vmlal.s16 q9, d3, d4[3] \n" // (k03-k33) * a30 "subs r4, r4, #1 \n" "bne 0b \n" // end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q10, q6, q9 \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--) "vld1.s8 {d2}, [%4] \n" // tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n" // kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q10, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q10, q10 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q10, q10, %q14 \n" // top_f32 = top_f32 + bias "vadd.f32 q10, q10, %q13 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q10, %q15 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12[0]}, [%0]! \n" "vst1.8 {d12[1]}, [%1]! \n" "vst1.8 {d12[2]}, [%2]! \n" "vst1.8 {d12[3]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "w"(_bias03), // %13 "w"(_scale_in03), // %14 "w"(_scale_out03) // %15 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12"); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); signed char* outptr0 = out0; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2 * p]; const float scale_requant_out = scales_requant[2 * p + 1]; #if __ARM_NEON float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _scale_in = vdupq_n_f32(scale_requant_in); float32x4_t _scale_out = vdupq_n_f32(scale_requant_out); #endif // __ARM_NEON int i = 0; for (; i + 7 < size; i += 8) { const signed char* tmpptr = tmp.channel(i / 8); const signed char* kptr = kernel.channel(p / 4 + p % 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n" // tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n" // a30-a37 "vmovl.s8 q4, d6 \n" // a20-a27 "vmovl.s8 q3, d5 \n" // a10-a17 "vmovl.s8 q2, d4 \n" // a00-a07 "vld1.s8 {d0}, [%2] \n" // kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n" // k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n" // (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n" // (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n" // (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n" // (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "subs r4, r4, #1 \n" "bne 0b \n" // end for "1: \n" // remain loop "and r4, %6, #3 \n" // r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" // for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n" // tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n" // kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n" // (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" // top_f32 = top_f32 * scale_in "vmul.f32 q6, q6, %q8 \n" "vmul.f32 q7, q7, %q8 \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, %q7 \n" "vadd.f32 q7, q7, %q7 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %q9 \n" "vmul.f32 q1, q7, %q9 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch), // %6 "w"(_bias0), // %7 "w"(_scale_in), // %8 "w"(_scale_out) // %9 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7"); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i + 3 < size; i += 4) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "lsr r4, %6, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" // for(; nn != 0; nn--) "pld [%2, #128] \n" "vld1.s8 {d4-d5}, [%1]! \n" // tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n" // a20-a23,a30-a33 "vmovl.s8 q2, d4 \n" // a00-a03,a10-a13 "vld1.s8 {d0}, [%2] \n" // kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n" // k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n" // (a00-a03) * k00 "vmlal.s16 q6, d5, d0[1] \n" // (a10-a13) * k01 "vmlal.s16 q6, d6, d0[2] \n" // (a20-a23) * k02 "vmlal.s16 q6, d7, d0[3] \n" // (a30-a33) * k03 "subs r4, r4, #1 \n" "bne 0b \n" // end for "1: \n" // remain loop "and r4, %6, #3 \n" // r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" // for(; remain != 0; remain--) "vld1.s8 {d2}, [%1] \n" // tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%2] \n" // kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %1, #4 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n" // (a00-a03) * k00 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n" // store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" // top_f32 = top_f32 * scale_in "vmul.f32 q6, q6, %q8 \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, %q7 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %q9 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" "vst1.s32 {d12[0]}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch), // %6 "w"(_bias0), // %7 "w"(_scale_in), // %8 "w"(_scale_out) // %9 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6"); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const signed char* kptr = kernel.channel(p / 4 + p % 4); int q = 0; int sum0 = 0; for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } } #endif
test5.c
int main () { int i; int j = 10; #pragma omp parallel for ordered default(shared) private(i) for(i = 0; i < j; i++) { #pragma omp atomic update i = i + 1; } }
profile.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO FFFFF IIIII L EEEEE % % P P R R O O F I L E % % PPPP RRRR O O FFF I L EEE % % P R R O O F I L E % % P R R OOO F IIIII LLLLL EEEEE % % % % % % MagickCore Image Profile Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/linked-list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/option-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H) #include <wchar.h> #include <lcms/lcms2.h> #else #include <wchar.h> #include "lcms2.h" #endif #endif #if defined(MAGICKCORE_XML_DELEGATE) # if defined(MAGICKCORE_WINDOWS_SUPPORT) # if !defined(__MINGW32__) # include <win32config.h> # endif # endif # include <libxml/parser.h> # include <libxml/tree.h> #endif /* Forward declarations */ static MagickBooleanType SetImageProfileInternal(Image *,const char *,const StringInfo *, const MagickBooleanType,ExceptionInfo *); static void WriteTo8BimProfile(Image *,const char*,const StringInfo *); /* Typedef declarations */ struct _ProfileInfo { char *name; size_t length; unsigned char *info; size_t signature; }; typedef struct _CMSExceptionInfo { Image *image; ExceptionInfo *exception; } CMSExceptionInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProfiles() clones one or more image profiles. % % The format of the CloneImageProfiles method is: % % MagickBooleanType CloneImageProfiles(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProfile() deletes a profile from the image by its name. % % The format of the DeleteImageProfile method is: % % MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); WriteTo8BimProfile(image,name,(StringInfo *) NULL); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProfiles() releases memory associated with an image profile map. % % The format of the DestroyProfiles method is: % % void DestroyImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProfiles(Image *image) { if (image->profiles != (SplayTreeInfo *) NULL) image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProfile() gets a profile associated with an image by name. % % The format of the GetImageProfile method is: % % const StringInfo *GetImageProfile(const Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport const StringInfo *GetImageProfile(const Image *image, const char *name) { const StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProfile() gets the next profile name for an image. % % The format of the GetNextImageProfile method is: % % char *GetNextImageProfile(const Image *image) % % A description of each parameter follows: % % o hash_info: the hash info. % */ MagickExport char *GetNextImageProfile(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((char *) NULL); return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProfileImage() associates, applies, or removes an ICM, IPTC, or generic % profile with / to / from an image. If the profile is NULL, it is removed % from the image otherwise added or applied. Use a name of '*' and a profile % of NULL to remove all profiles from the image. % % ICC and ICM profiles are handled as follows: If the image does not have % an associated color profile, the one you provide is associated with the % image and the image pixels are not transformed. Otherwise, the colorspace % transform defined by the existing and new profile are applied to the image % pixels and the new profile is associated with the image. % % The format of the ProfileImage method is: % % MagickBooleanType ProfileImage(Image *image,const char *name, % const void *datum,const size_t length,const MagickBooleanType clone) % % A description of each parameter follows: % % o image: the image. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o datum: the profile data. % % o length: the length of the profile. % % o clone: should be MagickFalse. % */ #if defined(MAGICKCORE_LCMS_DELEGATE) typedef struct _LCMSInfo { ColorspaceType colorspace; cmsUInt32Number type; size_t channels; cmsHPROFILE profile; int intent; double scale, translate; void **magick_restrict pixels; } LCMSInfo; #if LCMS_VERSION < 2060 static void* cmsGetContextUserData(cmsContext ContextID) { return(ContextID); } static cmsContext cmsCreateContext(void *magick_unused(Plugin),void *UserData) { magick_unreferenced(Plugin); return((cmsContext) UserData); } static void cmsSetLogErrorHandlerTHR(cmsContext magick_unused(ContextID), cmsLogErrorHandlerFunction Fn) { magick_unreferenced(ContextID); cmsSetLogErrorHandler(Fn); } static void cmsDeleteContext(cmsContext magick_unused(ContextID)) { magick_unreferenced(ContextID); } #endif static void **DestroyPixelThreadSet(void **pixels) { ssize_t i; if (pixels == (void **) NULL) return((void **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (void *) NULL) pixels[i]=RelinquishMagickMemory(pixels[i]); pixels=(void **) RelinquishMagickMemory(pixels); return(pixels); } static void **AcquirePixelThreadSet(const size_t columns, const size_t channels,MagickBooleanType highres) { ssize_t i; size_t number_threads; size_t size; void **pixels; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(void **) AcquireQuantumMemory(number_threads,sizeof(*pixels)); if (pixels == (void **) NULL) return((void **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); size=sizeof(double); if (highres == MagickFalse) size=sizeof(Quantum); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=AcquireQuantumMemory(columns,channels*size); if (pixels[i] == (void *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform) { ssize_t i; assert(transform != (cmsHTRANSFORM *) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (transform[i] != (cmsHTRANSFORM) NULL) cmsDeleteTransform(transform[i]); transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform); return(transform); } static cmsHTRANSFORM *AcquireTransformThreadSet(const LCMSInfo *source_info, const LCMSInfo *target_info,const cmsUInt32Number flags, cmsContext cms_context) { cmsHTRANSFORM *transform; ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads, sizeof(*transform)); if (transform == (cmsHTRANSFORM *) NULL) return((cmsHTRANSFORM *) NULL); (void) memset(transform,0,number_threads*sizeof(*transform)); for (i=0; i < (ssize_t) number_threads; i++) { transform[i]=cmsCreateTransformTHR(cms_context,source_info->profile, source_info->type,target_info->profile,target_info->type, target_info->intent,flags); if (transform[i] == (cmsHTRANSFORM) NULL) return(DestroyTransformThreadSet(transform)); } return(transform); } static void CMSExceptionHandler(cmsContext context,cmsUInt32Number severity, const char *message) { CMSExceptionInfo *cms_exception; ExceptionInfo *exception; Image *image; cms_exception=(CMSExceptionInfo *) cmsGetContextUserData(context); if (cms_exception == (CMSExceptionInfo *) NULL) return; exception=cms_exception->exception; if (exception == (ExceptionInfo *) NULL) return; image=cms_exception->image; if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s'","unknown context"); return; } if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s", severity,message != (char *) NULL ? message : "no message"); (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s', %s (#%u)",image->filename, message != (char *) NULL ? message : "no message",severity); } static void TransformDoublePixels(const int id,const Image* image, const LCMSInfo *source_info,const LCMSInfo *target_info, const cmsHTRANSFORM *transform,Quantum *q) { #define GetLCMSPixel(source_info,pixel) \ (source_info->scale*QuantumScale*(pixel)+source_info->translate) #define SetLCMSPixel(target_info,pixel) \ ClampToQuantum(target_info->scale*QuantumRange*(pixel)+target_info->translate) double *p; ssize_t x; p=(double *) source_info->pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetLCMSPixel(source_info,GetPixelRed(image,q)); if (source_info->channels > 1) { *p++=GetLCMSPixel(source_info,GetPixelGreen(image,q)); *p++=GetLCMSPixel(source_info,GetPixelBlue(image,q)); } if (source_info->channels > 3) *p++=GetLCMSPixel(source_info,GetPixelBlack(image,q)); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_info->pixels[id], target_info->pixels[id],(unsigned int) image->columns); p=(double *) target_info->pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_info->channels == 1) SetPixelGray(image,SetLCMSPixel(target_info,*p),q); else SetPixelRed(image,SetLCMSPixel(target_info,*p),q); p++; if (target_info->channels > 1) { SetPixelGreen(image,SetLCMSPixel(target_info,*p),q); p++; SetPixelBlue(image,SetLCMSPixel(target_info,*p),q); p++; } if (target_info->channels > 3) { SetPixelBlack(image,SetLCMSPixel(target_info,*p),q); p++; } q+=GetPixelChannels(image); } } static void TransformQuantumPixels(const int id,const Image* image, const LCMSInfo *source_info,const LCMSInfo *target_info, const cmsHTRANSFORM *transform,Quantum *q) { Quantum *p; ssize_t x; p=(Quantum *) source_info->pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetPixelRed(image,q); if (source_info->channels > 1) { *p++=GetPixelGreen(image,q); *p++=GetPixelBlue(image,q); } if (source_info->channels > 3) *p++=GetPixelBlack(image,q); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_info->pixels[id], target_info->pixels[id],(unsigned int) image->columns); p=(Quantum *) target_info->pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_info->channels == 1) SetPixelGray(image,*p++,q); else SetPixelRed(image,*p++,q); if (target_info->channels > 1) { SetPixelGreen(image,*p++,q); SetPixelBlue(image,*p++,q); } if (target_info->channels > 3) SetPixelBlack(image,*p++,q); q+=GetPixelChannels(image); } } #endif static MagickBooleanType SetsRGBImageProfile(Image *image, ExceptionInfo *exception) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (GetImageProfile(image,"icc") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); return(status); } MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, const void *datum,const size_t length,ExceptionInfo *exception) { #define ProfileImageTag "Profile/Image" #ifndef TYPE_XYZ_8 #define TYPE_XYZ_8 (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(1)) #endif #define ThrowProfileException(severity,tag,context) \ { \ if (profile != (StringInfo *) NULL) \ profile=DestroyStringInfo(profile); \ if (cms_context != (cmsContext) NULL) \ cmsDeleteContext(cms_context); \ if (source_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(source_info.profile); \ if (target_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(target_info.profile); \ ThrowBinaryException(severity,tag,context); \ } MagickBooleanType status; StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(name != (const char *) NULL); if ((datum == (const void *) NULL) || (length == 0)) { char *next; /* Delete image profile(s). */ ResetImageProfileIterator(image); for (next=GetNextImageProfile(image); next != (const char *) NULL; ) { if (IsOptionMember(next,name) != MagickFalse) { (void) DeleteImageProfile(image,next); ResetImageProfileIterator(image); } next=GetNextImageProfile(image); } return(MagickTrue); } /* Add a ICC, IPTC, or generic profile to the image. */ status=MagickTrue; profile=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile,(unsigned char *) datum); if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) status=SetImageProfile(image,name,profile,exception); else { const StringInfo *icc_profile; icc_profile=GetImageProfile(image,"icc"); if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { const char *value; value=GetImageProperty(image,"exif:ColorSpace",exception); (void) value; if (LocaleCompare(value,"1") != 0) (void) SetsRGBImageProfile(image,exception); value=GetImageProperty(image,"exif:InteroperabilityIndex",exception); if (LocaleCompare(value,"R98.") != 0) (void) SetsRGBImageProfile(image,exception); icc_profile=GetImageProfile(image,"icc"); } if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { profile=DestroyStringInfo(profile); return(MagickTrue); } #if !defined(MAGICKCORE_LCMS_DELEGATE) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (LCMS)",image->filename); #else { cmsContext cms_context; CMSExceptionInfo cms_exception; LCMSInfo source_info, target_info; /* Transform pixel colors as defined by the color profiles. */ cms_exception.image=image; cms_exception.exception=exception; cms_context=cmsCreateContext(NULL,&cms_exception); if (cms_context == (cmsContext) NULL) ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); cmsSetLogErrorHandlerTHR(cms_context,CMSExceptionHandler); source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(profile),(cmsUInt32Number) GetStringInfoLength(profile)); if (source_info.profile == (cmsHPROFILE) NULL) { cmsDeleteContext(cms_context); ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } if ((cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass) && (icc_profile == (StringInfo *) NULL)) status=SetImageProfile(image,name,profile,exception); else { CacheView *image_view; cmsColorSpaceSignature signature; cmsHTRANSFORM *magick_restrict transform; cmsUInt32Number flags; #if !defined(MAGICKCORE_HDRI_SUPPORT) const char *artifact; #endif MagickBooleanType highres; MagickOffsetType progress; ssize_t y; target_info.profile=(cmsHPROFILE) NULL; if (icc_profile != (StringInfo *) NULL) { target_info.profile=source_info.profile; source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(icc_profile), (cmsUInt32Number) GetStringInfoLength(icc_profile)); if (source_info.profile == (cmsHPROFILE) NULL) ThrowProfileException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } highres=MagickTrue; #if !defined(MAGICKCORE_HDRI_SUPPORT) artifact=GetImageArtifact(image,"profile:highres-transform"); if (IsStringFalse(artifact) != MagickFalse) highres=MagickFalse; #endif source_info.scale=1.0; source_info.translate=0.0; source_info.colorspace=sRGBColorspace; source_info.channels=3; switch (cmsGetColorSpace(source_info.profile)) { case cmsSigCmykData: { source_info.colorspace=CMYKColorspace; source_info.channels=4; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_CMYK_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_CMYK_16; else #endif { source_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; source_info.scale=100.0; } break; } case cmsSigGrayData: { source_info.colorspace=GRAYColorspace; source_info.channels=1; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_GRAY_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_GRAY_16; else #endif source_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { source_info.colorspace=LabColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_Lab_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_Lab_16; else #endif { source_info.type=(cmsUInt32Number) TYPE_Lab_DBL; source_info.scale=100.0; source_info.translate=(-0.5); } break; } case cmsSigRgbData: { source_info.colorspace=sRGBColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_RGB_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_RGB_16; else #endif source_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { source_info.colorspace=XYZColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_16; else #endif source_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } signature=cmsGetPCS(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) signature=cmsGetColorSpace(target_info.profile); target_info.scale=1.0; target_info.translate=0.0; target_info.channels=3; switch (signature) { case cmsSigCmykData: { target_info.colorspace=CMYKColorspace; target_info.channels=4; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_CMYK_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_CMYK_16; else #endif { target_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; target_info.scale=0.01; } break; } case cmsSigGrayData: { target_info.colorspace=GRAYColorspace; target_info.channels=1; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_GRAY_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_GRAY_16; else #endif target_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { target_info.colorspace=LabColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_Lab_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_Lab_16; else #endif { target_info.type=(cmsUInt32Number) TYPE_Lab_DBL; target_info.scale=0.01; target_info.translate=0.5; } break; } case cmsSigRgbData: { target_info.colorspace=sRGBColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_RGB_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_RGB_16; else #endif target_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { target_info.colorspace=XYZColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_XYZ_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_16; else #endif target_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } switch (image->rendering_intent) { case AbsoluteIntent: { target_info.intent=INTENT_ABSOLUTE_COLORIMETRIC; break; } case PerceptualIntent: { target_info.intent=INTENT_PERCEPTUAL; break; } case RelativeIntent: { target_info.intent=INTENT_RELATIVE_COLORIMETRIC; break; } case SaturationIntent: { target_info.intent=INTENT_SATURATION; break; } default: { target_info.intent=INTENT_PERCEPTUAL; break; } } flags=cmsFLAGS_HIGHRESPRECALC; #if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) if (image->black_point_compensation != MagickFalse) flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; #endif transform=AcquireTransformThreadSet(&source_info,&target_info, flags,cms_context); if (transform == (cmsHTRANSFORM *) NULL) ThrowProfileException(ImageError,"UnableToCreateColorTransform", name); /* Transform image as dictated by the source & target image profiles. */ source_info.pixels=AcquirePixelThreadSet(image->columns, source_info.channels,highres); target_info.pixels=AcquirePixelThreadSet(image->columns, target_info.channels,highres); if ((source_info.pixels == (void **) NULL) || (target_info.pixels == (void **) NULL)) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); ThrowProfileException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if (source_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); return(MagickFalse); } if (target_info.colorspace == CMYKColorspace) (void) SetImageColorspace(image,target_info.colorspace,exception); progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } if (highres != MagickFalse) TransformDoublePixels(id,image,&source_info,&target_info,transform,q); else TransformQuantumPixels(id,image,&source_info,&target_info,transform,q); sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ProfileImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) SetImageColorspace(image,target_info.colorspace,exception); switch (signature) { case cmsSigRgbData: { image->type=image->alpha_trait == UndefinedPixelTrait ? TrueColorType : TrueColorAlphaType; break; } case cmsSigCmykData: { image->type=image->alpha_trait == UndefinedPixelTrait ? ColorSeparationType : ColorSeparationAlphaType; break; } case cmsSigGrayData: { image->type=image->alpha_trait == UndefinedPixelTrait ? GrayscaleType : GrayscaleAlphaType; break; } default: break; } target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if ((status != MagickFalse) && (cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass)) status=SetImageProfile(image,name,profile,exception); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); } (void) cmsCloseProfile(source_info.profile); cmsDeleteContext(cms_context); } #endif } profile=DestroyStringInfo(profile); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProfile() removes a named profile from the image and returns its % value. % % The format of the RemoveImageProfile method is: % % void *RemoveImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name) { StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); WriteTo8BimProfile(image,name,(StringInfo *) NULL); profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t P r o f i l e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageProfileIterator() resets the image profile iterator. Use it in % conjunction with GetNextImageProfile() to iterate over all the profiles % associated with an image. % % The format of the ResetImageProfileIterator method is: % % ResetImageProfileIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageProfileIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProfile() adds a named profile to the image. If a profile with the % same name already exists, it is replaced. This method differs from the % ProfileImage() method in that it does not apply CMS color profiles. % % The format of the SetImageProfile method is: % % MagickBooleanType SetImageProfile(Image *image,const char *name, % const StringInfo *profile) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name, for example icc, exif, and 8bim (8bim is the % Photoshop wrapper for iptc profiles). % % o profile: A StringInfo structure that contains the named profile. % */ static void *DestroyProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static inline const unsigned char *ReadResourceByte(const unsigned char *p, unsigned char *quantum) { *quantum=(*p++); return(p); } static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++); return(p); } static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p); } static inline void WriteResourceLong(unsigned char *p, const unsigned int quantum) { unsigned char buffer[4]; buffer[0]=(unsigned char) (quantum >> 24); buffer[1]=(unsigned char) (quantum >> 16); buffer[2]=(unsigned char) (quantum >> 8); buffer[3]=(unsigned char) quantum; (void) memcpy(p,buffer,4); } static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) memcpy(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) memcpy(extract_profile->datum,datum,offset-4); WriteResourceLong(extract_profile->datum+offset-4,(unsigned int) profile->length); (void) memcpy(extract_profile->datum+offset, profile->datum,profile->length); } (void) memcpy(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } static void GetProfilesFromResourceBlock(Image *image, const StringInfo *resource_block,ExceptionInfo *exception) { const unsigned char *datum; const unsigned char *p; size_t length; ssize_t count; StringInfo *profile; unsigned char length_byte; unsigned int value; unsigned short id; datum=GetStringInfoDatum(resource_block); length=GetStringInfoLength(resource_block); for (p=datum; p < (datum+length-16); ) { if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0)) break; switch (id) { case 0x03ed: { unsigned int resolution; unsigned short units; /* Resolution. */ if (count < 10) break; p=ReadResourceLong(p,&resolution); image->resolution.x=((double) resolution)/65536.0; p=ReadResourceShort(p,&units)+2; p=ReadResourceLong(p,&resolution)+4; image->resolution.y=((double) resolution)/65536.0; /* Values are always stored as pixels per inch. */ if ((ResolutionType) units != PixelsPerCentimeterResolution) image->units=PixelsPerInchResolution; else { image->units=PixelsPerCentimeterResolution; image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case 0x0404: { /* IPTC Profile */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"iptc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x040c: { /* Thumbnail. */ p+=count; break; } case 0x040f: { /* ICC Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"icc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0422: { /* EXIF Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"exif",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0424: { /* XMP Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"xmp",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } } static void PatchCorruptProfile(const char *name,StringInfo *profile) { unsigned char *p; size_t length; /* Detect corrupt profiles and if discovered, repair. */ if (LocaleCompare(name,"xmp") == 0) { /* Remove garbage after xpacket end. */ p=GetStringInfoDatum(profile); p=(unsigned char *) strstr((const char *) p,"<?xpacket end=\"w\"?>"); if (p != (unsigned char *) NULL) { p+=19; length=p-GetStringInfoDatum(profile); if (length != GetStringInfoLength(profile)) { *p='\0'; SetStringInfoLength(profile,length); } } return; } if (LocaleCompare(name,"exif") == 0) { /* Check if profile starts with byte order marker instead of Exif. */ p=GetStringInfoDatum(profile); if ((LocaleNCompare((const char *) p,"MM",2) == 0) || (LocaleNCompare((const char *) p,"II",2) == 0)) { const unsigned char profile_start[] = "Exif\0\0"; StringInfo *exif_profile; exif_profile=AcquireStringInfo(6); if (exif_profile != (StringInfo *) NULL) { SetStringInfoDatum(exif_profile,profile_start); ConcatenateStringInfo(exif_profile,profile); SetStringInfoLength(profile,GetStringInfoLength(exif_profile)); SetStringInfo(profile,exif_profile); exif_profile=DestroyStringInfo(exif_profile); } } } } #if defined(MAGICKCORE_XML_DELEGATE) static MagickBooleanType ValidateXMPProfile(Image *image, const StringInfo *profile,ExceptionInfo *exception) { xmlDocPtr document; /* Parse XML profile. */ document=xmlReadMemory((const char *) GetStringInfoDatum(profile),(int) GetStringInfoLength(profile),"xmp.xml",NULL,XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (document == (xmlDocPtr) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "CorruptImageProfile","`%s' (XMP)",image->filename); return(MagickFalse); } xmlFreeDoc(document); return(MagickTrue); } #else static MagickBooleanType ValidateXMPProfile(Image *image, const StringInfo *profile,ExceptionInfo *exception) { (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError, "DelegateLibrarySupportNotBuiltIn","'%s' (XML)",image->filename); return(MagickFalse); } #endif static MagickBooleanType SetImageProfileInternal(Image *image,const char *name, const StringInfo *profile,const MagickBooleanType recursive, ExceptionInfo *exception) { char key[MagickPathExtent]; MagickBooleanType status; StringInfo *clone_profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); clone_profile=CloneStringInfo(profile); PatchCorruptProfile(name,clone_profile); if ((LocaleCompare(name,"xmp") == 0) && (ValidateXMPProfile(image,clone_profile,exception) == MagickFalse)) { clone_profile=DestroyStringInfo(clone_profile); return(MagickTrue); } if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MagickPathExtent); LocaleLower(key); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),clone_profile); if (status != MagickFalse) { if (LocaleCompare(name,"8bim") == 0) GetProfilesFromResourceBlock(image,clone_profile,exception); else if (recursive == MagickFalse) WriteTo8BimProfile(image,name,clone_profile); } return(status); } MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile,ExceptionInfo *exception) { return(SetImageProfileInternal(image,name,profile,MagickFalse,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageProfiles() synchronizes image properties with the image profiles. % Currently we only support updating the EXIF resolution and orientation. % % The format of the SyncImageProfiles method is: % % MagickBooleanType SyncImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline int ReadProfileByte(unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length) { signed int value; if (*length < 4) return(0); value=ReadProfileLong(MSBEndian,*p); (*length)-=4; *p+=4; return(value); } static inline signed short ReadProfileMSBShort(unsigned char **p, size_t *length) { signed short value; if (*length < 2) return(0); value=ReadProfileShort(MSBEndian,*p); (*length)-=2; *p+=2; return(value); } static inline void WriteProfileLong(const EndianType endian, const size_t value,unsigned char *p) { unsigned char buffer[4]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); (void) memcpy(p,buffer,4); return; } buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; (void) memcpy(p,buffer,4); } static void WriteProfileShort(const EndianType endian, const unsigned short value,unsigned char *p) { unsigned char buffer[2]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); (void) memcpy(p,buffer,2); return; } buffer[0]=(unsigned char) (value >> 8); buffer[1]=(unsigned char) value; (void) memcpy(p,buffer,2); } static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile) { size_t length; ssize_t count; unsigned char *p; unsigned short id; length=GetStringInfoLength(profile); p=GetStringInfoDatum(profile); while (length != 0) { if (ReadProfileByte(&p,&length) != 0x38) continue; if (ReadProfileByte(&p,&length) != 0x42) continue; if (ReadProfileByte(&p,&length) != 0x49) continue; if (ReadProfileByte(&p,&length) != 0x4D) continue; if (length < 7) return(MagickFalse); id=ReadProfileMSBShort(&p,&length); count=(ssize_t) ReadProfileByte(&p,&length); if ((count >= (ssize_t) length) || (count < 0)) return(MagickFalse); p+=count; length-=count; if ((*p & 0x01) == 0) (void) ReadProfileByte(&p,&length); count=(ssize_t) ReadProfileMSBLong(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); if ((id == 0x3ED) && (count == 16)) { if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x*2.54* 65536.0),p); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x* 65536.0),p); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4); if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y*2.54* 65536.0),p+8); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y* 65536.0),p+8); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12); } p+=count; length-=count; } return(MagickTrue); } MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; SplayTreeInfo *exif_resources; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || ((size_t) offset >= length)) return(MagickFalse); directory=exif+offset; level=0; entry=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(int) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((offset < 0) || ((size_t) (offset+number_bytes) > length)) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(MagickTrue); } MagickPrivate MagickBooleanType SyncImageProfiles(Image *image) { MagickBooleanType status; StringInfo *profile; status=MagickTrue; profile=(StringInfo *) GetImageProfile(image,"8BIM"); if (profile != (StringInfo *) NULL) if (Sync8BimProfile(image,profile) == MagickFalse) status=MagickFalse; profile=(StringInfo *) GetImageProfile(image,"EXIF"); if (profile != (StringInfo *) NULL) if (SyncExifProfile(image,profile) == MagickFalse) status=MagickFalse; return(status); } static void UpdateClipPath(unsigned char *blob,size_t length, const size_t old_columns,const size_t old_rows, const RectangleInfo *new_geometry) { ssize_t i; ssize_t knot_count, selector; knot_count=0; while (length != 0) { selector=(ssize_t) ReadProfileMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadProfileMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot. */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { double x, y; signed int xx, yy; y=(double) ReadProfileMSBLong(&blob,&length); y=y*old_rows/4096/4096; y-=new_geometry->y; yy=(signed int) ((y*4096*4096)/new_geometry->height); WriteProfileLong(MSBEndian,(size_t) yy,blob-4); x=(double) ReadProfileMSBLong(&blob,&length); x=x*old_columns/4096/4096; x-=new_geometry->x; xx=(signed int) ((x*4096*4096)/new_geometry->width); WriteProfileLong(MSBEndian,(size_t) xx,blob-4); } knot_count--; break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } } MagickPrivate void Update8BIMClipPath(const Image *image, const size_t old_columns,const size_t old_rows, const RectangleInfo *new_geometry) { const StringInfo *profile; size_t length; ssize_t count, id; unsigned char *info; assert(image != (Image *) NULL); assert(new_geometry != (RectangleInfo *) NULL); profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while (length > 0) { if (ReadProfileByte(&info,&length) != (unsigned char) '8') continue; if (ReadProfileByte(&info,&length) != (unsigned char) 'B') continue; if (ReadProfileByte(&info,&length) != (unsigned char) 'I') continue; if (ReadProfileByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadProfileMSBShort(&info,&length); count=(ssize_t) ReadProfileByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { info+=count; length-=count; } if ((count & 0x01) == 0) (void) ReadProfileByte(&info,&length); count=(ssize_t) ReadProfileMSBLong(&info,&length); if ((count < 0) || ((size_t) count > length)) { length=0; continue; } if ((id > 1999) && (id < 2999)) UpdateClipPath(info,(size_t) count,old_columns,old_rows,new_geometry); info+=count; length-=MagickMin(count,(ssize_t) length); } }
invert.c
/* Copyright 2016. The Regents of the University of California. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2016 Jon Tamir <jtamir@eecs.berkeley.edu> */ #include <stdlib.h> #include <assert.h> #include <complex.h> #include <stdio.h> #include "num/multind.h" #include "num/init.h" #include "misc/mmio.h" #include "misc/misc.h" #include "misc/opts.h" #ifndef DIMS #define DIMS 16 #endif static const char help_str[] = "Invert array (1 / <input>). The output is set to zero in case of divide by zero."; int main_invert(int argc, char* argv[argc]) { const char* in_file = NULL; const char* out_file = NULL; struct arg_s args[] = { ARG_INFILE(true, &in_file, "input"), ARG_OUTFILE(true, &out_file, "output"), }; const struct opt_s opts[] = {}; cmdline(&argc, argv, ARRAY_SIZE(args), args, help_str, ARRAY_SIZE(opts), opts); num_init(); long dims[DIMS]; complex float* idata = load_cfl(in_file, DIMS, dims); complex float* odata = create_cfl(out_file, DIMS, dims); #pragma omp parallel for for (long i = 0; i < md_calc_size(DIMS, dims); i++) odata[i] = idata[i] == 0 ? 0. : 1. / idata[i]; unmap_cfl(DIMS, dims, idata); unmap_cfl(DIMS, dims, odata); return 0; }
hello_mp.c
// Copyright (c) 2021 B.Roden // // MIT License // // 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. // // OpenMP header #include <omp.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { int tid; // Begin parallel region, define thread private variable(s) #pragma omp parallel private(tid) { // The current thread number tid = omp_get_thread_num(); printf("thread no = %d\n", tid); // If in the master thread if (tid == 0) printf("no of threads = %d\n", omp_get_num_threads()); } }
GB_binop__pow_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__pow_int8) // A.*B function (eWiseMult): GB (_AemultB_01__pow_int8) // A.*B function (eWiseMult): GB (_AemultB_02__pow_int8) // A.*B function (eWiseMult): GB (_AemultB_03__pow_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_int8) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pow_int8) // C+=b function (dense accum): GB (_Cdense_accumb__pow_int8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_int8) // C=scalar+B GB (_bind1st__pow_int8) // C=scalar+B' GB (_bind1st_tran__pow_int8) // C=A+scalar GB (_bind2nd__pow_int8) // C=A'+scalar GB (_bind2nd_tran__pow_int8) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = GB_pow_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,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_pow_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_POW || GxB_NO_INT8 || GxB_NO_POW_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__pow_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__pow_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__pow_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_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 int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__pow_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__pow_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__pow_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__pow_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__pow_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__pow_int8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_pow_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__pow_int8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_pow_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 = GBX (Ax, pA, false) ; \ Cx [pC] = GB_pow_int8 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__pow_int8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_pow_int8 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__pow_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
DataGen.h
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under the License #pragma once #include <boost/algorithm/string/predicate.hpp> #include <cstring> #include <memory> #include <random> #include "Constants.h" #include "common/Schema.h" #include "knowhere/index/vector_index/VecIndex.h" #include "knowhere/index/vector_index/adapter/VectorAdapter.h" #include "knowhere/index/vector_index/VecIndexFactory.h" #include "knowhere/index/vector_index/IndexIVF.h" #include "query/SearchOnIndex.h" #include "segcore/SegmentGrowingImpl.h" #include "segcore/SegmentSealedImpl.h" using boost::algorithm::starts_with; namespace milvus::segcore { struct GeneratedData { std::vector<uint8_t> rows_; std::vector<aligned_vector<uint8_t>> cols_; std::vector<idx_t> row_ids_; std::vector<Timestamp> timestamps_; RowBasedRawData raw_; template <typename T> auto get_col(int index) const { auto& target = cols_.at(index); std::vector<T> ret(target.size() / sizeof(T)); memcpy(ret.data(), target.data(), target.size()); return ret; } template <typename T> auto get_mutable_col(int index) { auto& target = cols_.at(index); assert(target.size() == row_ids_.size() * sizeof(T)); auto ptr = reinterpret_cast<T*>(target.data()); return ptr; } private: GeneratedData() = default; friend GeneratedData DataGen(SchemaPtr schema, int64_t N, uint64_t seed, uint64_t ts_offset); void generate_rows(int64_t N, SchemaPtr schema); }; inline void GeneratedData::generate_rows(int64_t N, SchemaPtr schema) { std::vector<int> offset_infos(schema->size() + 1, 0); auto sizeof_infos = schema->get_sizeof_infos(); std::partial_sum(sizeof_infos.begin(), sizeof_infos.end(), offset_infos.begin() + 1); int64_t len_per_row = offset_infos.back(); assert(len_per_row == schema->get_total_sizeof()); // change column-based data to row-based data std::vector<uint8_t> result(len_per_row * N); for (int index = 0; index < N; ++index) { for (int fid = 0; fid < schema->size(); ++fid) { auto len = sizeof_infos[fid]; auto offset = offset_infos[fid]; auto src = cols_[fid].data() + index * len; auto dst = result.data() + index * len_per_row + offset; memcpy(dst, src, len); } } rows_ = std::move(result); raw_.raw_data = rows_.data(); raw_.sizeof_per_row = schema->get_total_sizeof(); raw_.count = N; } inline GeneratedData DataGen(SchemaPtr schema, int64_t N, uint64_t seed = 42, uint64_t ts_offset = 0) { using std::vector; std::vector<aligned_vector<uint8_t>> cols; std::default_random_engine er(seed); std::normal_distribution<> distr(0, 1); int offset = 0; auto insert_cols = [&cols](auto& data) { using T = std::remove_reference_t<decltype(data)>; auto len = sizeof(typename T::value_type) * data.size(); auto ptr = aligned_vector<uint8_t>(len); memcpy(ptr.data(), data.data(), len); cols.emplace_back(std::move(ptr)); }; for (auto& field : schema->get_fields()) { switch (field.get_data_type()) { case engine::DataType::VECTOR_FLOAT: { auto dim = field.get_dim(); vector<float> final(dim * N); bool is_ip = starts_with(field.get_name().get(), "normalized"); #pragma omp parallel for for (int n = 0; n < N; ++n) { vector<float> data(dim); float sum = 0; std::default_random_engine er2(seed + n); std::normal_distribution<> distr2(0, 1); for (auto& x : data) { x = distr2(er2) + offset; sum += x * x; } if (is_ip) { sum = sqrt(sum); for (auto& x : data) { x /= sum; } } std::copy(data.begin(), data.end(), final.begin() + dim * n); } insert_cols(final); break; } case engine::DataType::VECTOR_BINARY: { auto dim = field.get_dim(); Assert(dim % 8 == 0); vector<uint8_t> data(dim / 8 * N); for (auto& x : data) { x = er(); } insert_cols(data); break; } case engine::DataType::INT64: { vector<int64_t> data(N); // begin with counter if (starts_with(field.get_name().get(), "counter")) { int64_t index = 0; for (auto& x : data) { x = index++; } } else { int i = 0; for (auto& x : data) { x = er() % (2 * N); x = i; i++; } } insert_cols(data); break; } case engine::DataType::INT32: { vector<int> data(N); for (auto& x : data) { x = er() % (2 * N); } insert_cols(data); break; } case engine::DataType::FLOAT: { vector<float> data(N); for (auto& x : data) { x = distr(er); } insert_cols(data); break; } case engine::DataType::DOUBLE: { vector<double> data(N); for (auto& x : data) { x = distr(er); } insert_cols(data); break; } default: { throw std::runtime_error("unimplemented"); } } ++offset; } GeneratedData res; res.cols_ = std::move(cols); for (int i = 0; i < N; ++i) { res.row_ids_.push_back(i); res.timestamps_.push_back(i + ts_offset); } // std::shuffle(res.row_ids_.begin(), res.row_ids_.end(), er); res.generate_rows(N, schema); return std::move(res); } inline auto CreatePlaceholderGroup(int64_t num_queries, int dim, int64_t seed = 42) { namespace ser = milvus::proto::milvus; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::FloatVector); std::normal_distribution<double> dis(0, 1); std::default_random_engine e(seed); for (int i = 0; i < num_queries; ++i) { std::vector<float> vec; for (int d = 0; d < dim; ++d) { vec.push_back(dis(e)); } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size() * sizeof(float)); } return raw_group; } inline auto CreatePlaceholderGroupFromBlob(int64_t num_queries, int dim, const float* src) { namespace ser = milvus::proto::milvus; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::FloatVector); int64_t src_index = 0; for (int i = 0; i < num_queries; ++i) { std::vector<float> vec; for (int d = 0; d < dim; ++d) { vec.push_back(src[src_index++]); } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size() * sizeof(float)); } return raw_group; } inline auto CreateBinaryPlaceholderGroup(int64_t num_queries, int64_t dim, int64_t seed = 42) { assert(dim % 8 == 0); namespace ser = milvus::proto::milvus; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::BinaryVector); std::default_random_engine e(seed); for (int i = 0; i < num_queries; ++i) { std::vector<uint8_t> vec; for (int d = 0; d < dim / 8; ++d) { vec.push_back(e()); } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size()); } return raw_group; } inline auto CreateBinaryPlaceholderGroupFromBlob(int64_t num_queries, int64_t dim, const uint8_t* ptr) { assert(dim % 8 == 0); namespace ser = milvus::proto::milvus; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::BinaryVector); for (int i = 0; i < num_queries; ++i) { std::vector<uint8_t> vec; for (int d = 0; d < dim / 8; ++d) { vec.push_back(*ptr); ++ptr; } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size()); } return raw_group; } inline json SearchResultToJson(const SearchResult& sr) { int64_t num_queries = sr.num_queries_; int64_t topk = sr.topk_; std::vector<std::vector<std::string>> results; for (int q = 0; q < num_queries; ++q) { std::vector<std::string> result; for (int k = 0; k < topk; ++k) { int index = q * topk + k; result.emplace_back(std::to_string(sr.internal_seg_offsets_[index]) + "->" + std::to_string(sr.result_distances_[index])); } results.emplace_back(std::move(result)); } return json{results}; }; inline void SealedLoader(const GeneratedData& dataset, SegmentSealed& seg) { // TODO auto row_count = dataset.row_ids_.size(); { LoadFieldDataInfo info; info.blob = dataset.row_ids_.data(); info.row_count = dataset.row_ids_.size(); info.field_id = 0; // field id for RowId seg.LoadFieldData(info); } { LoadFieldDataInfo info; info.blob = dataset.timestamps_.data(); info.row_count = dataset.timestamps_.size(); info.field_id = 1; seg.LoadFieldData(info); } int field_offset = 0; for (auto& meta : seg.get_schema().get_fields()) { LoadFieldDataInfo info; info.field_id = meta.get_id().get(); info.row_count = row_count; info.blob = dataset.cols_[field_offset].data(); seg.LoadFieldData(info); ++field_offset; } } inline std::unique_ptr<SegmentSealed> SealedCreator(SchemaPtr schema, const GeneratedData& dataset, const LoadIndexInfo& index_info) { auto segment = CreateSealedSegment(schema); SealedLoader(dataset, *segment); segment->LoadIndex(index_info); return segment; } inline knowhere::VecIndexPtr GenIndexing(int64_t N, int64_t dim, const float* vec) { // {knowhere::IndexParams::nprobe, 10}, auto conf = knowhere::Config{{knowhere::meta::DIM, dim}, {knowhere::IndexParams::nlist, 1024}, {knowhere::Metric::TYPE, milvus::knowhere::Metric::L2}, {knowhere::meta::DEVICEID, 0}}; auto database = knowhere::GenDataset(N, dim, vec); auto indexing = std::make_shared<knowhere::IVF>(); indexing->Train(database, conf); indexing->AddWithoutIds(database, conf); return indexing; } } // namespace milvus::segcore
saxpy.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #define N 1024 void main() { int n = N; int a = 2; int i, begin; int *x, *y, *z; x = (int *) malloc(n * sizeof(int)); y = (int *) malloc(n * sizeof(int)); z = (int *) malloc(n * sizeof(int)); for (i = 0; i != n; i++) { x[i] = i; y[i] = 2 * i; z[i] = 0.0; } //for (i = 0; i < n; i++) // x[i] = i; #pragma omp target map(from:z[0:n]) map(to:y[0:n],x[0:n]) #pragma omp parallel for for (i = 0; i < N; ++i) z[i] = a * x[i] + y[i]; printf("Checking Result...\n"); for (i = 0; i < n; ++i) if (((a * x[i] + y[i])) != z[i]) { printf("Result is wrong at %d!!!\n", i); break; } printf("Result checked!!!\n"); return; }
zgelqs.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_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_gelqs * * Computes a minimum-norm solution min | A*X - B | using the * LQ factorization A = L*Q computed by plasma_zgelqf. * ******************************************************************************* * * @param[in] m * The number of rows of the matrix A. m >= 0. * * @param[in] n * The number of columns of the matrix A. n >= m >= 0. * * @param[in] nrhs * The number of columns of B. nrhs >= 0. * * @param[in] pA * Details of the LQ factorization of the original matrix A as returned * by plasma_zgelqf. * * @param[in] lda * The leading dimension of the array A. lda >= m. * * @param[in] T * Auxiliary factorization data, computed by plasma_zgelqf. * * @param[in,out] pB * On entry, pointer to the m-by-nrhs right hand side matrix B. * On exit, the n-by-nrhs solution matrix X. * * @param[in] ldb * The leading dimension of the array B. ldb >= n. * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************* * * @sa plasma_omp_zgelqs * @sa plasma_cgelqs * @sa plasma_dgelqs * @sa plasma_sgelqs * @sa plasma_zgelqf * ******************************************************************************/ int plasma_zgelqs(int m, int n, int nrhs, plasma_complex64_t *pA, int lda, plasma_desc_t T, plasma_complex64_t *pB, int ldb) { // 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 (m < 0) { plasma_error("illegal value of m"); return -1; } if (n < 0 || m > n) { plasma_error("illegal value of n"); return -2; } if (nrhs < 0) { plasma_error("illegal value of nrhs"); return -3; } if (lda < imax(1, m)) { plasma_error("illegal value of lda"); return -5; } if (ldb < imax(1, imax(1, n))) { plasma_error("illegal value of ldb"); return -8; } // quick return if (m == 0 || n == 0 || nrhs == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_gelqf(plasma, PlasmaComplexDouble, m, n); // Set tiling parameters. int ib = plasma->ib; int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; plasma_desc_t B; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, nrhs, 0, 0, n, nrhs, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Allocate workspace. plasma_workspace_t work; size_t lwork = ib*nb; // unmlq: work retval = plasma_workspace_create(&work, lwork, PlasmaComplexDouble); if (retval != PlasmaSuccess) { plasma_error("plasma_workspace_create() failed"); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // 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); // Call the tile async function. plasma_omp_zgelqs(A, T, B, work, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(B, pB, ldb, &sequence, &request); } // implicit synchronization plasma_workspace_destroy(&work); // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_gelqs * * Computes a minimum-norm solution using previously computed LQ factorization. * Non-blocking tile version of plasma_zgelqs(). * May return before the computation is finished. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] A * Descriptor of matrix A. * A is stored in the tile layout. * * @param[in] T * Descriptor of matrix T. * Auxiliary factorization data, computed by plasma_zgelqf. * * @param[in,out] B * Descriptor of matrix B. * On entry, right-hand side matrix B in the tile layout. * On exit, solution matrix X in the tile layout. * * @param[in] work * Workspace for the auxiliary arrays needed by some coreblas kernels. * For multiplication by Q contains preallocated space for work * arrays. Allocated by the plasma_workspace_create function. * * @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). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zgelqs * @sa plasma_omp_cgelqs * @sa plasma_omp_dgelqs * @sa plasma_omp_sgelqs * @sa plasma_omp_zgelqf * ******************************************************************************/ void plasma_omp_zgelqs(plasma_desc_t A, plasma_desc_t T, plasma_desc_t B, plasma_workspace_t work, 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 (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid descriptor A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(T) != PlasmaSuccess) { plasma_error("invalid descriptor T"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid descriptor B"); 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 (A.m == 0 || A.n == 0 || B.n == 0) return; // Zero the trailing block of the right-hand-side matrix. // B has less rows than X. plasma_pzlaset(PlasmaGeneral, 0.0, 0.0, plasma_desc_view(B, A.m, 0, A.n - A.m, B.n), sequence, request); // Solve L * Y = B. plasma_pztrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaNonUnit, 1.0, plasma_desc_view(A, 0, 0, A.m, A.m), plasma_desc_view(B, 0, 0, A.m, B.n), sequence, request); // Find X = Q^H * Y. if (plasma->householder_mode == PlasmaTreeHouseholder) { plasma_pzunmlq_tree(PlasmaLeft, Plasma_ConjTrans, A, T, B, work, sequence, request); } else { plasma_pzunmlq(PlasmaLeft, Plasma_ConjTrans, A, T, B, work, sequence, request); } }
atomic-6.c
/* PR middle-end/36106 */ /* { dg-options "-O2" } */ /* { dg-options "-O2 -mieee" { target alpha*-*-* } } */ /* { dg-options "-O2 -march=i586" { target { { i?86-*-* x86_64-*-* } && ilp32 } } } */ #ifdef __i386__ # include "cpuid.h" #endif extern void abort (void); union { unsigned long long l; double d; } u = { .l = 0x7ff0000000072301ULL }; int __attribute__((noinline)) do_test (void) { #pragma omp atomic u.d += 1.0L; return 0; } int main (void) { #ifdef __i386__ unsigned int eax, ebx, ecx, edx; if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx)) return 0; if (!(edx & bit_CMPXCHG8B)) return 0; #endif do_test (); return 0; }
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; size_t columns, number_channels, rows; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images->next,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } image->depth=32UL; AppendImageToList(&complex_images,image); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { complex_images=DestroyImageList(complex_images); return(complex_images); } /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(images,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; number_channels=MagickMin(MagickMin(MagickMin( Ar_image->number_channels,Ai_image->number_channels),MagickMin( Br_image->number_channels,Bi_image->number_channels)),MagickMin( Cr_image->number_channels,Ci_image->number_channels)); Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; columns=MagickMin(Cr_image->columns,Ci_image->columns); rows=MagickMin(Cr_image->rows,Ci_image->rows); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,rows,1L) #endif for (y=0; y < (ssize_t) rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_channels; i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=QuantumRange*PerceptibleReciprocal(QuantumScale*Br[i]*Br[i]+ QuantumScale*Bi[i]*Bi[i]+snr); Cr[i]=gamma*(QuantumScale*Ar[i]*Br[i]+QuantumScale*Ai[i]*Bi[i]); Ci[i]=gamma*(QuantumScale*Ai[i]*Br[i]-QuantumScale*Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(QuantumScale*Ar[i]*Ar[i]+QuantumScale*Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=(QuantumScale*Ar[i]*Br[i]-QuantumScale*Ai[i]*Bi[i]); Ci[i]=(QuantumScale*Ai[i]*Br[i]+QuantumScale*Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register Quantum *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"forward") == 0) { double gamma; /* Normalize forward transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register Quantum *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
partial.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" #include "aux_interp.h" /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtPIInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtPIInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] -= hypre_MPI_Wtime(); #endif /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; /*HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL;*/ HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ /*HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter, coarse_counter_offd; */ HYPRE_Int n_coarse_old; HYPRE_Int total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; /*HYPRE_Int strong_f_marker = -2;*/ /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i; /*HYPRE_Int i, ii, i1, i2, j, jj, kk, k1, jj1;*/ /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Int max_num_threads; HYPRE_Int *P_diag_array = NULL; HYPRE_Int *P_offd_array = NULL; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); max_num_threads = hypre_NumThreads(); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = num_old_cpts_global[1] - num_old_cpts_global[0]; /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]; /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); /*P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); */ } if (full_off_procNodes) { /*P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes);*/ fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } /*hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd);*/ for (i=0; i < full_off_procNodes; i++) { fine_to_coarse_offd[i] = -1; tmp_CF_marker_offd[i] = -1; } cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } P_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads+1); P_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads+1); /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i, diagonal, distribute, sgn, sum) #endif { HYPRE_Int ii, jj_counter, jj_counter_offd, jj, kk, i1, i2, k1, jj1; HYPRE_Int loc_col, jj_begin_row, jj_begin_row_offd; HYPRE_Int jj_end_row, jj_end_row_offd, strong_f_marker; HYPRE_Int size, rest, ne, ns; HYPRE_Int num_threads, my_thread_num; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; strong_f_marker = -2; num_threads = hypre_NumActiveThreads(); my_thread_num = hypre_GetThreadNum(); size = n_coarse_old/num_threads; rest = n_coarse_old - size*num_threads; if (my_thread_num < rest) { ns = my_thread_num*(size+1); ne = (my_thread_num+1)*(size+1); } else { ns = my_thread_num*size+rest; ne = (my_thread_num+1)*size+rest; } if (n_fine) P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); for (ii=0; ii < n_fine; ii++) P_marker[ii] = -1; if (full_off_procNodes) P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); for (ii=0; ii < full_off_procNodes; ii++) P_marker_offd[ii] = -1; /*coarse_counter = 0; coarse_counter_offd = 0;*/ jj_counter = start_indexing; jj_counter_offd = start_indexing; for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; /*P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd;*/ i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; /*coarse_counter++;*/ } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } P_diag_array[my_thread_num] = jj_counter; P_offd_array[my_thread_num] = jj_counter_offd; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); for (i=0; i < max_num_threads; i++) { P_diag_array[i+1] += P_diag_array[i]; P_offd_array[i+1] += P_offd_array[i]; } P_diag_size = P_diag_array[max_num_threads]; P_offd_size = P_offd_array[max_num_threads]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_coarse_old] = P_diag_size; P_offd_i[n_coarse_old] = P_offd_size; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif jj_counter = start_indexing; jj_counter_offd = start_indexing; if (my_thread_num) { jj_counter = P_diag_array[my_thread_num-1]; jj_counter_offd = P_offd_array[my_thread_num-1]; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; P_diag_i[ii] = jj_counter; P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row || i2 == i) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; if(i2 == i && (sgn*A_diag_data[jj1]) < 0) diagonal += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row || loc_col == i) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; if(loc_col == i) diagonal += distribute*A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } hypre_TFree(P_marker); hypre_TFree(P_marker_offd); } /* end parallel region */ if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(old_coarse_to_fine); hypre_TFree(P_diag_array); hypre_TFree(P_offd_array); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialStdInterp * Comment: The interpolatory weighting can be changed with the sep_weight * variable. This can enable not separating negative and positive * off diagonals in the weight formula. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialStdInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int sep_weight, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_Int total_old_global_cpts; HYPRE_Int *ihat = NULL; HYPRE_Int *ihat_offd = NULL; HYPRE_Int *ipnt = NULL; HYPRE_Int *ipnt_offd = NULL; HYPRE_Int strong_f_marker = -2; /* Interpolation weight variables */ HYPRE_Real *ahat = NULL; HYPRE_Real *ahat_offd = NULL; HYPRE_Real sum_pos, sum_pos_C, sum_neg, sum_neg_C, sum, sum_C; HYPRE_Real diagonal, distribute; HYPRE_Real alfa, beta; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, j1, jj, kk, k1; HYPRE_Int cnt_c, cnt_f, cnt_c_offd, cnt_f_offd, indx; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Real wall_1 = 0; HYPRE_Real wall_2 = 0; HYPRE_Real wall_3 = 0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag== 4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = num_old_cpts_global[1] - num_old_cpts_global[0]; /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]; /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 0)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] >= 0) { if(P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] >= 0) { if(P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } /* Initialize ahat, which is a modification to a, used in the standard * interpolation routine. */ if (n_fine) { ahat = hypre_CTAlloc(HYPRE_Real, n_fine); ihat = hypre_CTAlloc(HYPRE_Int, n_fine); ipnt = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { ahat_offd = hypre_CTAlloc(HYPRE_Real, full_off_procNodes); ihat_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); ipnt_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; ahat[i] = 0; ihat[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; ahat_offd[i] = 0; ihat_offd[i] = -1; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { if (debug_flag==4) wall_time = time_getWallclockSeconds(); strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = i1; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = k1; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd]=i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(CF_marker[loc_col] > 0) { if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = loc_col; P_diag_data[jj_counter] = zero; jj_counter++; } } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] > 0) { if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_1 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); cnt_c = 0; cnt_f = jj_end_row-jj_begin_row; cnt_c_offd = 0; cnt_f_offd = jj_end_row_offd-jj_begin_row_offd; ihat[i] = cnt_f; ipnt[cnt_f] = i; ahat[cnt_f++] = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is direct neighbor */ i1 = A_diag_j[jj]; if (P_marker[i1] != strong_f_marker) { indx = ihat[i1]; if (indx > -1) ahat[indx] += A_diag_data[jj]; else if (P_marker[i1] >= jj_begin_row) { ihat[i1] = cnt_c; ipnt[cnt_c] = i1; ahat[cnt_c++] += A_diag_data[jj]; } else if (CF_marker[i1] != -3) { ihat[i1] = cnt_f; ipnt[cnt_f] = i1; ahat[cnt_f++] += A_diag_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func[i1]) { distribute = A_diag_data[jj]/A_diag_data[A_diag_i[i1]]; for (kk = A_diag_i[i1]+1; kk < A_diag_i[i1+1]; kk++) { k1 = A_diag_j[kk]; indx = ihat[k1]; if (indx > -1) ahat[indx] -= A_diag_data[kk]*distribute; else if (P_marker[k1] >= jj_begin_row) { ihat[k1] = cnt_c; ipnt[cnt_c] = k1; ahat[cnt_c++] -= A_diag_data[kk]*distribute; } else { ihat[k1] = cnt_f; ipnt[cnt_f] = k1; ahat[cnt_f++] -= A_diag_data[kk]*distribute; } } if(num_procs > 1) { for (kk = A_offd_i[i1]; kk < A_offd_i[i1+1]; kk++) { k1 = A_offd_j[kk]; indx = ihat_offd[k1]; if(num_functions == 1 || dof_func[i1] == dof_func_offd[k1]) { if (indx > -1) ahat_offd[indx] -= A_offd_data[kk]*distribute; else if (P_marker_offd[k1] >= jj_begin_row_offd) { ihat_offd[k1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = k1; ahat_offd[cnt_c_offd++] -= A_offd_data[kk]*distribute; } else { ihat_offd[k1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = k1; ahat_offd[cnt_f_offd++] -= A_offd_data[kk]*distribute; } } } } } } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] != strong_f_marker) { indx = ihat_offd[i1]; if (indx > -1) ahat_offd[indx] += A_offd_data[jj]; else if (P_marker_offd[i1] >= jj_begin_row_offd) { ihat_offd[i1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = i1; ahat_offd[cnt_c_offd++] += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { ihat_offd[i1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = i1; ahat_offd[cnt_f_offd++] += A_offd_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { distribute = A_offd_data[jj]/A_ext_data[A_ext_i[i1]]; for (kk = A_ext_i[i1]+1; kk < A_ext_i[i1+1]; kk++) { k1 = A_ext_j[kk]; if(k1 >= col_1 && k1 < col_n) { /*diag*/ loc_col = k1 - col_1; indx = ihat[loc_col]; if (indx > -1) ahat[indx] -= A_ext_data[kk]*distribute; else if (P_marker[loc_col] >= jj_begin_row) { ihat[loc_col] = cnt_c; ipnt[cnt_c] = loc_col; ahat[cnt_c++] -= A_ext_data[kk]*distribute; } else { ihat[loc_col] = cnt_f; ipnt[cnt_f] = loc_col; ahat[cnt_f++] -= A_ext_data[kk]*distribute; } } else { loc_col = -k1 - 1; if(num_functions == 1 || dof_func_offd[loc_col] == dof_func_offd[i1]) { indx = ihat_offd[loc_col]; if (indx > -1) ahat_offd[indx] -= A_ext_data[kk]*distribute; else if(P_marker_offd[loc_col] >= jj_begin_row_offd) { ihat_offd[loc_col] = cnt_c_offd; ipnt_offd[cnt_c_offd] = loc_col; ahat_offd[cnt_c_offd++] -= A_ext_data[kk]*distribute; } else { ihat_offd[loc_col] = cnt_f_offd; ipnt_offd[cnt_f_offd] = loc_col; ahat_offd[cnt_f_offd++] -= A_ext_data[kk]*distribute; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_2 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); diagonal = ahat[cnt_c]; ahat[cnt_c] = 0; sum_pos = 0; sum_pos_C = 0; sum_neg = 0; sum_neg_C = 0; sum = 0; sum_C = 0; if(sep_weight == 1) { for (jj=0; jj < cnt_c; jj++) { if (ahat[jj] > 0) { sum_pos_C += ahat[jj]; } else { sum_neg_C += ahat[jj]; } } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos_C += ahat_offd[jj]; } else { sum_neg_C += ahat_offd[jj]; } } } sum_pos = sum_pos_C; sum_neg = sum_neg_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { if (ahat[jj] > 0) { sum_pos += ahat[jj]; } else { sum_neg += ahat[jj]; } ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos += ahat_offd[jj]; } else { sum_neg += ahat_offd[jj]; } ahat_offd[jj] = 0; } } if (sum_neg_C*diagonal) alfa = sum_neg/sum_neg_C/diagonal; if (sum_pos_C*diagonal) beta = sum_pos/sum_pos_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; if (ahat[j1] > 0) P_diag_data[jj] = -beta*ahat[j1]; else P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; if (ahat_offd[j1] > 0) P_offd_data[jj] = -beta*ahat_offd[j1]; else P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } else { for (jj=0; jj < cnt_c; jj++) { sum_C += ahat[jj]; } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { sum_C += ahat_offd[jj]; } } sum = sum_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { sum += ahat[jj]; ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { sum += ahat_offd[jj]; ahat_offd[jj] = 0; } } if (sum_C*diagonal) alfa = sum/sum_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_3 += wall_time; fflush(NULL); } } } if (debug_flag==4) { hypre_printf("Proc = %d fill part 1 %f part 2 %f part 3 %f\n", my_id, wall_1, wall_2, wall_3); fflush(NULL); } P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(old_coarse_to_fine); hypre_TFree(P_marker); hypre_TFree(ahat); hypre_TFree(ihat); hypre_TFree(ipnt); if (full_off_procNodes) { hypre_TFree(ahat_offd); hypre_TFree(ihat_offd); hypre_TFree(ipnt_offd); } if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_Int total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, i2, jj, kk, k1, jj1; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = num_old_cpts_global[1] - num_old_cpts_global[0]; /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]; /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row ) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd && (sgn*A_ext_data[jj1]) < 0) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(old_coarse_to_fine); hypre_TFree(P_marker); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; }
incrementalAggregation.c
// ----------------------------------------------------------------------------- // // "00_AccelGraph" // // ----------------------------------------------------------------------------- // Copyright (c) 2014-2019 All rights reserved // ----------------------------------------------------------------------------- // Author : Abdullah Mughrabi // Email : atmughra@ncsu.edu||atmughrabi@gmail.com // File : incrementalAggregation.c // Create : 2019-06-29 12:31:24 // Revise : 2019-09-28 15:34:11 // Editor : Abdullah Mughrabi // ----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <omp.h> #include <limits.h> //UINT_MAX #include "timer.h" #include "myMalloc.h" #include "boolean.h" #include "reorder.h" #include "graphConfig.h" #include "arrayQueue.h" #include "graphCSR.h" #include "graphGrid.h" #include "graphAdjArrayList.h" #include "graphAdjLinkedList.h" #include "incrementalAggregation.h" #include "reorder.h" // ******************************************************************************************** // *************** Stats DataStructure ************** // ******************************************************************************************** struct IncrementalAggregationStats *newIncrementalAggregationStatsGraphCSR(struct GraphCSR *graph) { uint32_t v; struct IncrementalAggregationStats *stats = (struct IncrementalAggregationStats *) malloc(sizeof(struct IncrementalAggregationStats)); stats->totalQ = 0.0; stats->num_clusters = 0; stats->atom = (union Atom *) my_malloc(graph->num_vertices * sizeof(union Atom));; stats->vertices = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->degrees = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->weightSum = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomDegree = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomChild = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); // union Atom *atom = (union Atom *) my_malloc(graph->num_vertices * sizeof(union Atom)); stats->sibling = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->dest = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->vertices[v] = v; stats->degrees[v] = graph->vertices->out_degree[v]; } return stats; } struct IncrementalAggregationStats *newIncrementalAggregationStatsGraphGrid(struct GraphGrid *graph) { uint32_t v; struct IncrementalAggregationStats *stats = (struct IncrementalAggregationStats *) malloc(sizeof(struct IncrementalAggregationStats)); stats->totalQ = 0.0; stats->num_clusters = 0; stats->vertices = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->degrees = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->weightSum = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomDegree = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomChild = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); // union Atom *atom = (union Atom *) my_malloc(graph->num_vertices * sizeof(union Atom)); stats->sibling = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->dest = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->vertices[v] = v; stats->degrees[v] = graph->grid->out_degree[v]; } return stats; } struct IncrementalAggregationStats *newIncrementalAggregationStatsGraphAdjArrayList(struct GraphAdjArrayList *graph) { uint32_t v; struct IncrementalAggregationStats *stats = (struct IncrementalAggregationStats *) malloc(sizeof(struct IncrementalAggregationStats)); stats->totalQ = 0.0; stats->num_clusters = 0; stats->vertices = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->degrees = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->weightSum = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomDegree = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomChild = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); // union Atom *atom = (union Atom *) my_malloc(graph->num_vertices * sizeof(union Atom)); stats->sibling = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->dest = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->vertices[v] = v; stats->degrees[v] = graph->vertices[v].out_degree; } return stats; } struct IncrementalAggregationStats *newIncrementalAggregationStatsGraphAdjLinkedList(struct GraphAdjLinkedList *graph) { uint32_t v; struct IncrementalAggregationStats *stats = (struct IncrementalAggregationStats *) malloc(sizeof(struct IncrementalAggregationStats)); stats->time_total = 0.0; stats->totalQ = 0.0; stats->num_clusters = 0; stats->vertices = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->degrees = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->weightSum = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomDegree = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->atomChild = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); // union Atom *atom = (union Atom *) my_malloc(graph->num_vertices * sizeof(union Atom)); stats->sibling = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->dest = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->vertices[v] = v; stats->degrees[v] = graph->vertices[v].out_degree; } return stats; } void freeIncrementalAggregationStats(struct IncrementalAggregationStats *stats) { if(stats) { if(stats->vertices) free(stats->vertices); if(stats->degrees) free(stats->degrees); if(stats->weightSum) free(stats->weightSum); if(stats->atomDegree) free(stats->atomDegree); if(stats->atomChild) free(stats->atomChild); if(stats->sibling) free(stats->sibling); if(stats->dest) free(stats->dest); if(stats->labels) free(stats->labels); free(stats); } } // ******************************************************************************************** // *************** CSR DataStructure ************** // ******************************************************************************************** struct IncrementalAggregationStats *incrementalAggregationGraphCSR( struct GraphCSR *graph) { uint32_t v; float deltaQ = -1.0; struct IncrementalAggregationStats *stats = newIncrementalAggregationStatsGraphCSR(graph); struct ArrayQueue *topLevelSet = newArrayQueue(graph->num_vertices); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting Incremental Aggregation"); printf(" -----------------------------------------------------\n"); Start(timer); //order vertices according to degree stats->vertices = radixSortEdgesByDegree(stats->degrees, stats->vertices, graph->num_vertices); //initialize variables #pragma omp parallel for for(v = 0 ; v < graph->num_vertices; v++) { stats->atomDegree[v] = graph->vertices->out_degree[v]; stats->atomChild[v] = UINT_MAX; stats->atom[v].pair.degree = graph->vertices->out_degree[v]; stats->atom[v].pair.child = UINT_MAX; stats->sibling[v] = UINT_MAX; stats->dest[v] = v; stats->weightSum[v] = 0; } #pragma omp parallel shared(stats, graph, topLevelSet) { //incrementally aggregate vertices struct ArrayQueue *Neighbors = newArrayQueue(graph->num_vertices); struct ArrayQueue *reachableSet = newArrayQueue(graph->num_vertices); #pragma omp for schedule (dynamic,1024) for(v = 0 ; v < graph->num_vertices; v++) { uint32_t u; uint32_t n; deltaQ = -1.0; u = stats->vertices[v]; n = u; uint32_t degreeU = UINT_MAX; //atomic swap degreeU = __sync_val_compare_and_swap(&(stats->atom[u].pair.degree), stats->atom[u].pair.degree, UINT_MAX ); findBestDestination(Neighbors, reachableSet, &deltaQ, &n, degreeU, u, stats, graph); if(deltaQ <= 0) { stats->atom[u].pair.degree = degreeU; enArrayQueueAtomic(topLevelSet, u); continue; } //atomic load union Atom atomv; #pragma omp atomic read atomv.atomicPair = stats->atom[n].atomicPair; if(atomv.pair.degree != UINT_MAX) { union Atom atomp; stats->sibling[u] = atomv.pair.child; atomp.pair.degree = atomv.pair.degree + degreeU; atomp.pair.child = u; if(__sync_bool_compare_and_swap(&(stats->atom[n].atomicPair), stats->atom[n].atomicPair, atomp.atomicPair)) { stats->dest[u] = n; continue; } } stats->atom[u].pair.degree = degreeU; stats->sibling[u] = UINT_MAX; stats->totalQ += (double)deltaQ; } freeArrayQueue(reachableSet); freeArrayQueue(Neighbors); } stats->labels = returnLabelsOfNodesFromDendrogram(topLevelSet, stats->atom, stats->sibling, graph->num_vertices); stats->num_clusters = sizeArrayQueueCurr(topLevelSet); Stop(timer); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "num_clusters", sizeArrayQueueCurr(topLevelSet), stats->time_total); printf(" -----------------------------------------------------\n"); freeArrayQueue(topLevelSet); return stats; } void findBestDestination(struct ArrayQueue *Neighbors, struct ArrayQueue *reachableSet, float *deltaQ, uint32_t *u, uint32_t degreeVout, uint32_t v, struct IncrementalAggregationStats *stats, struct GraphCSR *graph) { uint32_t j; uint32_t k; uint32_t t; uint32_t tempV; uint32_t tempU; uint32_t degreeTemp; uint32_t edgeTemp; uint32_t edgeWeightUV = 0; float deltaQtemp = 0.0; float numEdgesm = 1.0 / ((graph->num_edges)); float numEdgesm2 = numEdgesm * numEdgesm; struct Bitmap *bitmapNC = newBitmap(graph->num_vertices); returnReachableSetOfNodesFromDendrogram(v, stats->atom, stats->sibling, reachableSet); // #pragma omp parallel for private(degreeTemp,edgeTemp,tempV,k,tempU) shared (bitmapNC,reachableSet,stats) for(j = reachableSet->head ; j < reachableSet->tail; j++) { tempV = reachableSet->queue[j]; degreeTemp = graph->vertices->out_degree[tempV]; edgeTemp = graph->vertices->edges_idx[tempV]; for(k = edgeTemp ; k < (edgeTemp + degreeTemp) ; k++) { tempU = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[k]); while(stats->dest[stats->dest[tempU]] != stats->dest[tempU]) { // #pragma omp atomic write stats->dest[tempU] = stats->dest[stats->dest[tempU]]; } setBitAtomic(bitmapNC, tempU); // edgeWeightUV++; } } // #pragma omp parallel for shared(Neighbors, graph, stats) reduction (+:edgeWeightUV) for(t = 0; t < graph->num_vertices ; t++) { if(getBit(bitmapNC, t)) { if(!isEnArrayQueued(Neighbors, stats->dest[t])) { edgeWeightUV++; enArrayQueueWithBitmapAtomic(Neighbors, stats->dest[t]); } } } deltaQtemp = 0.0; for(j = Neighbors->head ; j < Neighbors->tail; j++) { uint32_t i = Neighbors->queue[j]; uint32_t degreeUout = 0; degreeUout = stats->atom[stats->dest[i]].pair.degree; if(degreeUout != UINT_MAX) { deltaQtemp = 2 * ((edgeWeightUV * numEdgesm) - (float)(degreeVout * degreeUout * numEdgesm2)); if((*deltaQ) < deltaQtemp && i != v) { (*deltaQ) = deltaQtemp; (*u) = i; } } } resetArrayQueue(reachableSet); resetArrayQueue(Neighbors); freeBitmap(bitmapNC); } void returnReachableSetOfNodesFromDendrogram(uint32_t v, union Atom *atom, uint32_t *sibling, struct ArrayQueue *reachableSet) { traversDendrogramReachableSetDFS(v, atom, sibling, reachableSet); } void traversDendrogramReachableSetDFS(uint32_t v, union Atom *atom, uint32_t *sibling, struct ArrayQueue *reachableSet) { if(atom[v].pair.child != UINT_MAX) traversDendrogramReachableSetDFS(atom[v].pair.child, atom, sibling, reachableSet); enArrayQueueWithBitmap(reachableSet, v); if(sibling[v] != UINT_MAX) traversDendrogramReachableSetDFS(sibling[v], atom, sibling, reachableSet); } uint32_t *returnLabelsOfNodesFromDendrogram(struct ArrayQueue *reachableSet, union Atom *atom, uint32_t *sibling, uint32_t num_vertices) { uint32_t i; uint32_t newLablesCounter = 0; uint32_t *newLables = (uint32_t *) my_malloc(num_vertices * sizeof(uint32_t)); for(i = reachableSet->head ; i < reachableSet->tail; i++) { // printf("%u \n", reachableSet->queue[i]); traversDendrogramLabelsDFS(&newLablesCounter, newLables, reachableSet->queue[i], atom, sibling); } return newLables; } void traversDendrogramLabelsDFS(uint32_t *newLablesCounter, uint32_t *newLables, uint32_t v, union Atom *atom, uint32_t *sibling) { if(v == UINT_MAX) return; traversDendrogramLabelsDFS(newLablesCounter, newLables, atom[v].pair.child, atom, sibling); // printf("%u %u \n", v, (*newLablesCounter)); newLables[v] = (*newLablesCounter); (*newLablesCounter)++; traversDendrogramLabelsDFS(newLablesCounter, newLables, sibling[v], atom, sibling); } void printSet(struct ArrayQueue *Set) { uint32_t i; printf("S : "); for(i = Set->head ; i < Set->tail; i++) { printf("%u|", Set->queue[i]); } printf("\n"); }
fac_zero_stencilcoef.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision: 2.17 $ ***********************************************************************EHEADER*/ #include "_hypre_sstruct_ls.h" #include "fac.h" #define AbsStencilShape(stencil, abs_shape) \ { \ HYPRE_Int ii,jj,kk; \ ii = hypre_IndexX(stencil); \ jj = hypre_IndexY(stencil); \ kk = hypre_IndexZ(stencil); \ abs_shape= abs(ii) + abs(jj) + abs(kk); \ } /*-------------------------------------------------------------------------- * hypre_FacZeroCFSten: Zeroes the coarse stencil coefficients that reach * into an underlying coarsened refinement box. * Algo: For each cbox * { * 1) refine cbox and expand by one in each direction * 2) boxman_intersect with the fboxman * 3) loop over intersection boxes to see if stencil * reaches over. * } *--------------------------------------------------------------------------*/ HYPRE_Int hypre_FacZeroCFSten( hypre_SStructPMatrix *Af, hypre_SStructPMatrix *Ac, hypre_SStructGrid *grid, HYPRE_Int fine_part, hypre_Index rfactors ) { hypre_BoxManager *fboxman; hypre_BoxManEntry **boxman_entries; HYPRE_Int nboxman_entries; hypre_SStructPGrid *p_cgrid; hypre_Box fgrid_box; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_Box scaled_box; hypre_Box *shift_ibox; hypre_StructMatrix *smatrix; hypre_StructStencil *stencils; HYPRE_Int stencil_size; hypre_Index refine_factors, upper_shift; hypre_Index stride; hypre_Index stencil_shape; hypre_Index zero_index, ilower, iupper; HYPRE_Int nvars, var1, var2; HYPRE_Int ndim; hypre_Box *ac_dbox; double *ac_ptr; hypre_Index loop_size; HYPRE_Int iac; HYPRE_Int ci, i, j; HYPRE_Int abs_shape; HYPRE_Int ierr = 0; p_cgrid = hypre_SStructPMatrixPGrid(Ac); nvars = hypre_SStructPMatrixNVars(Ac); ndim = hypre_SStructPGridNDim(p_cgrid); hypre_ClearIndex(zero_index); hypre_ClearIndex(stride); hypre_ClearIndex(upper_shift); for (i= 0; i< ndim; i++) { stride[i]= 1; upper_shift[i]= rfactors[i]-1; } hypre_CopyIndex(rfactors, refine_factors); if (ndim < 3) { for (i= ndim; i< 3; i++) { refine_factors[i]= 1; } } for (var1= 0; var1< nvars; var1++) { cgrid= hypre_SStructPGridSGrid(hypre_SStructPMatrixPGrid(Ac), var1); cgrid_boxes= hypre_StructGridBoxes(cgrid); fboxman= hypre_SStructGridBoxManager(grid, fine_part, var1); /*------------------------------------------------------------------ * For each parent coarse box find all fboxes that may be connected * through a stencil entry- refine this box, expand it by one * in each direction, and boxman_intersect with fboxman *------------------------------------------------------------------*/ hypre_ForBoxI(ci, cgrid_boxes) { cgrid_box= hypre_BoxArrayBox(cgrid_boxes, ci); hypre_StructMapCoarseToFine(hypre_BoxIMin(cgrid_box), zero_index, refine_factors, hypre_BoxIMin(&scaled_box)); hypre_StructMapCoarseToFine(hypre_BoxIMax(cgrid_box), upper_shift, refine_factors, hypre_BoxIMax(&scaled_box)); hypre_SubtractIndex(hypre_BoxIMin(&scaled_box), stride, hypre_BoxIMin(&scaled_box)); hypre_AddIndex(hypre_BoxIMax(&scaled_box), stride, hypre_BoxIMax(&scaled_box)); hypre_BoxManIntersect(fboxman, hypre_BoxIMin(&scaled_box), hypre_BoxIMax(&scaled_box), &boxman_entries, &nboxman_entries); for (var2= 0; var2< nvars; var2++) { stencils= hypre_SStructPMatrixSStencil(Ac, var1, var2); if (stencils != NULL) { stencil_size= hypre_StructStencilSize(stencils); smatrix = hypre_SStructPMatrixSMatrix(Ac, var1, var2); ac_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(smatrix), ci); /*--------------------------------------------------------- * Find the stencil coefficients that must be zeroed off. * Loop over all possible boxes. *---------------------------------------------------------*/ for (i= 0; i< stencil_size; i++) { hypre_CopyIndex(hypre_StructStencilElement(stencils, i), stencil_shape); AbsStencilShape(stencil_shape, abs_shape); if (abs_shape) /* non-centre stencils are zeroed */ { /* look for connecting fboxes that must be zeroed. */ for (j= 0; j< nboxman_entries; j++) { hypre_BoxManEntryGetExtents(boxman_entries[j], ilower, iupper); hypre_BoxSetExtents(&fgrid_box, ilower, iupper); shift_ibox= hypre_CF_StenBox(&fgrid_box, cgrid_box, stencil_shape, refine_factors, ndim); if ( hypre_BoxVolume(shift_ibox) ) { ac_ptr= hypre_StructMatrixExtractPointerByIndex(smatrix, ci, stencil_shape); hypre_BoxGetSize(shift_ibox, loop_size); hypre_BoxLoop1Begin(ndim, loop_size, ac_dbox, hypre_BoxIMin(shift_ibox), stride, iac); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iac) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop1For(iac) { ac_ptr[iac] = 0.0; } hypre_BoxLoop1End(iac); } /* if ( hypre_BoxVolume(shift_ibox) ) */ hypre_BoxDestroy(shift_ibox); } /* for (j= 0; j< nboxman_entries; j++) */ } /* if (abs_shape) */ } /* for (i= 0; i< stencil_size; i++) */ } /* if (stencils != NULL) */ } /* for (var2= 0; var2< nvars; var2++) */ hypre_TFree(boxman_entries); } /* hypre_ForBoxI ci */ } /* for (var1= 0; var1< nvars; var1++) */ return ierr; } /*-------------------------------------------------------------------------- * hypre_FacZeroFCSten: Zeroes the fine stencil coefficients that reach * into a coarse box. * Idea: zero off any stencil connection of a fine box that does not * connect to a sibling box * Algo: For each fbox * { * 1) expand by one in each direction so that sibling boxes can be * reached * 2) boxman_intersect with the fboxman to get all fboxes including * itself and the siblings * 3) loop over intersection boxes, shift them in the stencil * direction (now we are off the fbox), and subtract any sibling * extents. The remaining chunks (boxes of a box_array) are * the desired but shifted extents. * 4) shift these shifted extents in the negative stencil direction * to get back into fbox. Zero-off the matrix over these latter * extents. * } *--------------------------------------------------------------------------*/ HYPRE_Int hypre_FacZeroFCSten( hypre_SStructPMatrix *A, hypre_SStructGrid *grid, HYPRE_Int fine_part) { MPI_Comm comm= hypre_SStructGridComm(grid); hypre_BoxManager *fboxman; hypre_BoxManEntry **boxman_entries; HYPRE_Int nboxman_entries; hypre_SStructPGrid *p_fgrid; hypre_StructGrid *fgrid; hypre_BoxArray *fgrid_boxes; hypre_Box *fgrid_box; hypre_Box scaled_box; hypre_BoxArray *intersect_boxes, *tmp_box_array1, *tmp_box_array2; hypre_StructMatrix *smatrix; hypre_StructStencil *stencils; HYPRE_Int stencil_size; hypre_Index stride, ilower, iupper; hypre_Index stencil_shape, shift_index; hypre_Box shift_ibox; hypre_Box intersect_box; hypre_Index size_ibox; HYPRE_Int nvars, var1, var2; HYPRE_Int ndim; hypre_Box *a_dbox; double *a_ptr; hypre_Index loop_size; HYPRE_Int ia; HYPRE_Int fi, fj, i, j; HYPRE_Int abs_shape; HYPRE_Int myid, proc; HYPRE_Int ierr = 0; hypre_MPI_Comm_rank(comm, &myid); p_fgrid = hypre_SStructPMatrixPGrid(A); nvars = hypre_SStructPMatrixNVars(A); ndim = hypre_SStructPGridNDim(p_fgrid); hypre_ClearIndex(stride); for (i= 0; i< ndim; i++) { stride[i]= 1; } tmp_box_array1= hypre_BoxArrayCreate(1); for (var1= 0; var1< nvars; var1++) { fgrid = hypre_SStructPGridSGrid(hypre_SStructPMatrixPGrid(A), var1); fgrid_boxes= hypre_StructGridBoxes(fgrid); fboxman = hypre_SStructGridBoxManager(grid, fine_part, var1); hypre_ForBoxI(fi, fgrid_boxes) { fgrid_box= hypre_BoxArrayBox(fgrid_boxes, fi); hypre_ClearIndex(size_ibox); for (i= 0; i< ndim; i++) { size_ibox[i] = hypre_BoxSizeD(fgrid_box, i) - 1; } /* expand fgrid_box & boxman_intersect with fboxman. */ hypre_SubtractIndex(hypre_BoxIMin(fgrid_box), stride, hypre_BoxIMin(&scaled_box)); hypre_AddIndex(hypre_BoxIMax(fgrid_box), stride, hypre_BoxIMax(&scaled_box)); hypre_BoxManIntersect(fboxman, hypre_BoxIMin(&scaled_box), hypre_BoxIMax(&scaled_box), &boxman_entries, &nboxman_entries); for (var2= 0; var2< nvars; var2++) { stencils= hypre_SStructPMatrixSStencil(A, var1, var2); if (stencils != NULL) { stencil_size= hypre_StructStencilSize(stencils); smatrix = hypre_SStructPMatrixSMatrix(A, var1, var2); a_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(smatrix), fi); for (i= 0; i< stencil_size; i++) { hypre_CopyIndex(hypre_StructStencilElement(stencils, i), stencil_shape); AbsStencilShape(stencil_shape, abs_shape); if (abs_shape) /* non-centre stencils are zeroed */ { hypre_SetIndex(shift_index, size_ibox[0]*stencil_shape[0], size_ibox[1]*stencil_shape[1], size_ibox[2]*stencil_shape[2]); hypre_AddIndex(shift_index, hypre_BoxIMin(fgrid_box), hypre_BoxIMin(&shift_ibox)); hypre_AddIndex(shift_index, hypre_BoxIMax(fgrid_box), hypre_BoxIMax(&shift_ibox)); hypre_IntersectBoxes(&shift_ibox, fgrid_box, &shift_ibox); hypre_SetIndex(shift_index, -stencil_shape[0], -stencil_shape[1], -stencil_shape[2]); /*----------------------------------------------------------- * Check to see if the stencil does not couple to a sibling * box. These boxes should be in boxman_entries. But do not * subtract fgrid_box itself, which is also in boxman_entries. *-----------------------------------------------------------*/ hypre_AddIndex(stencil_shape, hypre_BoxIMin(&shift_ibox), hypre_BoxIMin(&shift_ibox)); hypre_AddIndex(stencil_shape, hypre_BoxIMax(&shift_ibox), hypre_BoxIMax(&shift_ibox)); intersect_boxes= hypre_BoxArrayCreate(1); hypre_CopyBox(&shift_ibox, hypre_BoxArrayBox(intersect_boxes,0)); for (j= 0; j< nboxman_entries; j++) { hypre_SStructBoxManEntryGetProcess(boxman_entries[j], &proc); hypre_SStructBoxManEntryGetBoxnum(boxman_entries[j], &fj); if ((proc != myid) || (fj != fi)) { hypre_BoxManEntryGetExtents(boxman_entries[j], ilower, iupper); hypre_BoxSetExtents(&scaled_box, ilower, iupper); hypre_IntersectBoxes(&shift_ibox, &scaled_box, &intersect_box); if ( hypre_BoxVolume(&intersect_box) ) { hypre_CopyBox(&intersect_box, hypre_BoxArrayBox(tmp_box_array1, 0)); tmp_box_array2= hypre_BoxArrayCreate(0); hypre_SubtractBoxArrays(intersect_boxes, tmp_box_array1, tmp_box_array2); hypre_BoxArrayDestroy(tmp_box_array2); } } } /* for (j= 0; j< nboxman_entries; j++) */ /*----------------------------------------------------------- * intersect_boxes now has the shifted extents for the * coefficients to be zeroed. *-----------------------------------------------------------*/ a_ptr= hypre_StructMatrixExtractPointerByIndex(smatrix, fi, stencil_shape); hypre_ForBoxI(fj, intersect_boxes) { hypre_CopyBox(hypre_BoxArrayBox(intersect_boxes, fj), &intersect_box); hypre_AddIndex(shift_index, hypre_BoxIMin(&intersect_box), hypre_BoxIMin(&intersect_box)); hypre_AddIndex(shift_index, hypre_BoxIMax(&intersect_box), hypre_BoxIMax(&intersect_box)); hypre_BoxGetSize(&intersect_box, loop_size); hypre_BoxLoop1Begin(ndim, loop_size, a_dbox, hypre_BoxIMin(&intersect_box), stride, ia); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ia) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop1For(ia) { a_ptr[ia] = 0.0; } hypre_BoxLoop1End(ia); } /* hypre_ForBoxI(fj, intersect_boxes) */ hypre_BoxArrayDestroy(intersect_boxes); } /* if (abs_shape) */ } /* for (i= 0; i< stencil_size; i++) */ } /* if (stencils != NULL) */ } /* for (var2= 0; var2< nvars; var2++) */ hypre_TFree(boxman_entries); } /* hypre_ForBoxI(fi, fgrid_boxes) */ } /* for (var1= 0; var1< nvars; var1++) */ hypre_BoxArrayDestroy(tmp_box_array1); return ierr; }
matmul_mdev.c
/* * Rectangular matrix multiplication, started from MIT Cilk matmul.cilk example * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "homp.h" #include "omp.h" #include "matmul.h" #if defined(DEVICE_ITLMIC_SUPPORT) #include <mkl.h> #endif void zero(REAL *A, long n) { long i, j; #pragma omp for private (i, j) for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { A[i * n + j] = 0.0; } } } void init(REAL *A, long n) { long i, j; #pragma omp for private (i, j) for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { A[i * n + j] = (double) drand48(); } } } void print_array(char *title, char *name, REAL *A, long m, long n) { printf("%s:\n", title); long i, j; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%s[%d][%d]:%f\n", name, i, j, A[i * n + j]); } } printf("\n"); } double maxerror(REAL *A, REAL *B, long n) { long i, j; double error = 0.0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { double diff = (A[i * n + j] - B[i * n + j]) / A[i * n + j]; // printf("%4f -- %4f\n", A[i*n+j], B[i*n+j]); if (diff < 0) diff = -diff; if (diff > error) error = diff; } } return error; } void iter_matmul(float *A, float *B, float *C, long n) { long i, j, k; for (i = 0; i < n; i++) for (j = 0; j < n; j++) { float c = 0.0; for (k = 0; k < n; k++) c += (A[(i * n) + k] * B[(k * n) + j]); C[(i * n) + j] = c; } } void omp_matmul(REAL *A, REAL *B, REAL *C, long n) { long i, j, k; #pragma omp parallel for shared(A, B, C, n) private(i,j,k) for (i = 0; i < n; i++) for (j = 0; j < n; j++) { float c = 0.0; for (k = 0; k < n; k++) c += (A[(i * n) + k] * B[(k * n) + j]); C[(i * n) + j] = c; } } void openacc_matmul(float *A, float *B, float *C, long n) { long i, j, k; /* #pragma acc kernels copyin(A[0:n][0:n],B[0:n][0:n]) copyout(C[0:n][0:n]) */ //#pragma acc kernels loop copyin(A[0:n*n],B[0:n*n]) copyout(C[0:n*n]) #pragma acc parallel loop copyin ( A [ 0 : n * n ], B [ 0 : n * n ] ) copyout ( C [ 0 : n * n ] ) collapse ( 2 ) for (i = 0; i < n; i++) for (k = 0; k < n; k++) { float c = 0.0; for (j = 0; j < n; j++) c += (A[(i * n) + j] * B[(j * n) + k]); C[(i * n) + k] = c; } } #if 0 /* multiple device */ /* A, C row-major partition */ void ompacc_matmul_mdev_v1_block_block(REAL *A, REAL *B, REAL *C, long n) { long i, j, k; #pragma omp target device(*) map(from:C[0:n][0:n] dist_data(BLOCK,DUPLICATE)), map(to:n,A[0:n][0:n] dist_data(BLOCK, DUPLICATE), B[0:n][0:n] dist_data(DUPLICATE,DUPLICATE)) #pragma omp parallel for private(i,j,k) dist_iteration(BLOCK) for (i = 0; i < n; i++) for (k = 0; k < n; k++) { REAL c = 0.0; for (j = 0; j < n; j++) c += A[i * n + j] * B[j * n + k]; C[i * n + k] = c; } } void ompacc_matmul_mdev_v1_block_align(REAL *A, REAL *B, REAL *C, long n) { long i, j, k; #pragma omp target device(*) map(from:C[0:n][0:n] dist_data(BLOCK,DUPLICATE)), map(to:n,A[0:n][0:n] dist_data(ALIGN(C)), B[0:n][0:n] dist_data(DUPLICATE,DUPLICATE)) #pragma omp parallel for private(i,j,k) dist_iteration(ALIGN(C[])) for (i = 0; i < n; i++) for (k = 0; k < n; k++) { REAL c = 0.0; for (j = 0; j < n; j++) c += A[i * n + j] * B[j * n + k]; C[i * n + k] = c; } } void ompacc_matmul_mdev_v1_align_auto(REAL *A, REAL *B, REAL *C, long n) { long i, j, k; #pragma omp target device(*) map(from:C[0:n][0:n] dist_data(ALIGN(lp1),DUPLICATE)), map(to:n,A[0:n][0:n] dist_data(ALIGN(lp1),DUPLICATE), B[0:n][0:n] dist_data(DUPLICATE,DUPLICATE)) #pragma omp parallel for private(i,j,k) dist_iteration(AUTO) lp1: for (i = 0; i < n; i++) for (k = 0; k < n; k++) { REAL c = 0.0; for (j = 0; j < n; j++) c += A[i * n + j] * B[j * n + k]; C[i * n + k] = c; } } /* multiple device */ /* B, C column-major partition */ void ompacc_matmul_mdev_v2(REAL *A, REAL *B, REAL *C, long n) { long i, j, k; #pragma omp target device(*) map(from:C[0:n]{0:n}>>(*)), map(to:n,A[0:n][0:n],B[0:n]{0:n}>>(*) for (i = 0; i < n; i++) #pragma omp parallel for private(i,j,k) dist_iteration match_range C[]{} for (k = 0; k < n; k++) { REAL c = 0.0; for (j = 0; j < n; j++) c += A[i * n + j] * B[j * n + k]; C[i * n + k] = c; } } /* multiple device */ /* A,B, C row-column partition */ void ompacc_matmul_mdev_v3(REAL *A, REAL *B, REAL *C, long n) { long i, j, k; #pragma omp target device(*)=>(:)(:) map(from:C{0:n}{0:n}>>{:}{:}), map(to:n,A{0:n}[0:n]>>{:}(:),B[0:n]{0:n}>>(:){:}) #pragma omp parallel for private(i,j,k) dist_iteration match_range C[]{} for (i = 0; i < n; i++) #pragma omp parallel for private(i,j,k) dist_iteration match_range C{}[] for (k = 0; k < n; k++) { REAL c = 0.0; for (j = 0; j < n; j++) c += A[i * n + j] * B[j * n + k]; C[i * n + k] = c; } } #endif /** * For each of the above three version of the matmul onto multiple device, the differences between them are the data distribution method. * The actual compiler will normally generate three set of methods for each of the dist type, in this * hand-written compiler code, we combine them together * we use dist para to do that in the compiler-generated code to do that: * dist = 1: A/C row dist, * dist = 2: B/C column dist, * dist = 3: A-row, B-column dist */ double matmul_ompacc_mdev(int ndevs, int *targets, REAL *A, REAL *B, REAL *C, long n); int main(int argc, char *argv[]) { long n = 256; float *A; float *B; float *C_seq; float *C_ompacc; float *C_itlmkl_cpumic; double seq_elapsed; double ompacc_elapsed; fprintf(stderr, "Usage: matmul <n> for nxn matrix, n default: %d\n", n); if (argc >= 2) n = atoi(argv[1]); A = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); B = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); C_seq = ((float *) (malloc(((n * n) * sizeof(float))))); C_ompacc = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); zero(C_seq, n); zero(C_ompacc, n); #if defined(DEVICE_ITLMIC_SUPPORT) C_itlmkl_cpumic = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); zero(C_itlmkl_cpumic,n); #endif srand48((1 << 12)); init(A, n); init(B, n); // print_array("Array A", "A", A, n, n); // print_array("Array B", "B", B, n, n); /* sequential run */ seq_elapsed = read_timer_ms(); int i; int num_its = 10; //for (i=0; i<num_its;i++) //iter_matmul(A, B, C_seq, n); seq_elapsed = (read_timer_ms() - seq_elapsed)/num_its; // print_array("Array C_seq", "C", C_seq, n, n); #if defined(DEVICE_ITLMIC_SUPPORT) REAL alpha = 1; REAL beta = 0; //mkl_mic_enable(); double itlmkl_cpumic = read_timer_ms(); for (i=0; i<num_its;i++) cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,n, n, n, alpha, A, n, B, n, beta, C_itlmkl_cpumic, n); itlmkl_cpumic = (read_timer_ms() - itlmkl_cpumic)/num_its; mkl_mic_disable(); #endif /* we currently cannot do the OpenMP acc and OpenACC run in once */ /* openmp acc version */ omp_init_devices(); int num_active_devs = omp_get_num_active_devices(); int targets[num_active_devs]; int num_targets = 1; #if 0 /* one HOSTCPU */ num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* one NVGPU */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 1); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* two NVGPU */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 2); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* three NVGPU */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 3); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* four NVGPU */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 4); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* one ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_ITLMIC, targets, 1); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* two ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_ITLMIC, targets, 2); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* one HOSTCPU and one NVGPU */ num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); num_targets += omp_get_devices(OMP_DEVICE_NVGPU, targets+num_targets, 1); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n, dist_dim, dist_policy); /* one HOSTCPU and one ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 1); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n, dist_dim, dist_policy); /* one NVGPU and one ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 1); num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 1); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n, dist_dim, dist_policy); /* two NVGPU and two ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 2); num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 2); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n, dist_dim, dist_policy); /* one HOSTCPU and four NVGPU */ num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); num_targets += omp_get_devices(OMP_DEVICE_NVGPU, targets+num_targets, 4); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* one HOSTCPU and two ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 2); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* four NVGPU and two ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_NVGPU, targets, 4); num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 2); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); /* one CPU, two NVGPU and two ITLMIC */ //num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); //num_targets += omp_get_devices(OMP_DEVICE_NVGPU, targets+num_targets, 2); //num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 2); //ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n, dist_dim, dist_policy); /* one CPU, four NVGPU and two ITLMIC */ num_targets = omp_get_devices(OMP_DEVICE_HOSTCPU, targets, 1); num_targets += omp_get_devices(OMP_DEVICE_NVGPU, targets+num_targets, 4); num_targets += omp_get_devices(OMP_DEVICE_ITLMIC, targets+num_targets, 2); ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); #endif /* run on all devices */ num_targets = num_active_devs; for (i=0;i<num_active_devs;i++) targets[i] = i; ompacc_elapsed = matmul_ompacc_mdev(num_targets, targets, A, B, C_ompacc, n); //print_array("Array C_ompacc", "C", C_ompacc, n, n); omp_fini_devices(); printf("======================================================================================================\n"); printf("\tmatmul(%dx%d) example on %d devices\n", n, n, omp_get_num_active_devices()); printf("------------------------------------------------------------------------------------------------------\n"); printf("Error: %g\n", maxerror(C_seq, C_ompacc, n)); printf("------------------------------------------------------------------------------------------------------\n"); printf("Performance:\t\tRuntime (ms)\t MFLOPS\n"); printf("Sequential:\t\t%4f\t%4f\n", seq_elapsed, ((((2.0 * n) * n) * n) / (1.0e3 * seq_elapsed))); printf("OMPACC mdev:\t\t%4f\t%4f\n", ompacc_elapsed, ((((2.0 * n) * n) * n) / (1.0e3 * ompacc_elapsed))); #if defined(DEVICE_ITLMIC_SUPPORT) printf("Itlmkl_cpumic:\t\t%4f\t%4f\n", itlmkl_cpumic, ((((2.0 * n) * n) * n) / (1.0e3 * itlmkl_cpumic))); #endif omp_unified_free(C_ompacc); free(C_seq); #if defined(DEVICE_ITLMIC_SUPPORT) free(C_itlmkl_cpumic); #endif omp_unified_free(B); omp_unified_free(A); return 0; } /* compiler should generate three of and three laucher, for simplicity, we use vx to indicate whether * this is for v1, v2 or v3 version of the code */ struct OUT__1__11058__args { long i; long j; long k; REAL *A; REAL *B; REAL *C; }; void OUT__1__11058__launcher(omp_offloading_t *off, void *args) { struct OUT__1__11058__args *iargs = (struct OUT__1__11058__args *) args; long i = iargs->i; long j = iargs->j; long k = iargs->k; omp_data_map_t *map_A = omp_map_get_map(off, iargs->A, 0); /* 0 means the map A */ omp_data_map_t *map_B = omp_map_get_map(off, iargs->B, 1); /* 1 means the map B */ omp_data_map_t *map_C = omp_map_get_map(off, iargs->C, 2); /* 2 means the map C */ REAL *A = (REAL *) map_A->map_dev_ptr; /* A is ixk array */ REAL *B = (REAL *) map_B->map_dev_ptr; /* B is kxj array */ REAL *C = (REAL *) map_C->map_dev_ptr; #if CORRECTNESS_CHECK printf("kernel launcher: A: %X, B: %X, C: %X\n", A, B, C); print_array("A in device: ", "Adev", A, i, k); print_array("B in device: ", "Bdev", B, i, k); #endif long start; omp_loop_get_range(off, 0, &start, &i); #if 0 /* for col-wise distribution */ omp_loop_get_range(off, 0, &start, &j); /* for row/col-wise distribution */ omp_loop_get_range(off, 0, &start, &i); omp_loop_get_range(off, 0, &start, &j); //printf("dist: %d, dev: %d, i: %d, j: %d, k: %d\n", dist, off->devseqid, i, j, k); #endif omp_device_type_t devtype = off->dev->type; if (devtype == OMP_DEVICE_NVGPU) { #if defined (DEVICE_NVGPU_CUDA_SUPPORT) matmul_nvgpu_cuda_wrapper(off, i, j, k, (REAL *)A, (REAL *)B, (REAL *)C); #endif } else if (devtype == OMP_DEVICE_ITLMIC) { #if defined(DEVICE_ITLMIC_SUPPORT) matmul_itlmic_wrapper(off, i, j, k, (REAL *)A, (REAL *)B, (REAL *)C); #endif } else if (devtype == OMP_DEVICE_THSIM || devtype == OMP_DEVICE_HOSTCPU) { matmul_cpu_omp_wrapper(off, i, j, k, (REAL *)A, (REAL *)B, (REAL *)C); } else { fprintf(stderr, "device type is not supported for this call\n"); abort(); } #if CORRECTNESS_CHECK print_array("C in device: ", "Cdev", C, i, j); #endif } double matmul_ompacc_mdev(int ndevs, int *targets, REAL *A, REAL *B, REAL *C, long n) { double ompacc_init_time = read_timer_ms(); /* get number of target devices specified by the programmers */ int __top_ndims__ = 1; /**************************************** dist-specific *****************************************/ /* TODO: to use row/col-wise dist, __top_ndims__ should be set to 2 */ omp_grid_topology_t * __top__ = omp_grid_topology_init(ndevs, targets, __top_ndims__); /* init other infos (dims, periodic, idmaps) of top if needed */ int __num_maps__ = 3; /* XXX: need compiler output */ /* we use universal args and launcher because matmul can do it */ struct OUT__1__11058__args args; args.i = n;args.j = n;args.k = n;args.A = A;args.B = B;args.C = C; omp_offloading_info_t * __off_info__ = omp_offloading_init_info("matmul_kernel", __top__, 0, OMP_OFFLOADING_DATA_CODE, __num_maps__, OUT__1__11058__launcher, &args, 1); omp_offloading_append_profile_per_iteration(__off_info__, 2*n*n, 2*n*n, n); /* A map info */ omp_data_map_info_t *__A_map_info__ = &__off_info__->data_map_info[0]; omp_data_map_init_info("A", __A_map_info__, __off_info__, A, 2, sizeof(REAL), OMP_DATA_MAP_TO, OMP_DATA_MAP_AUTO); omp_data_map_info_set_dims_2d(__A_map_info__, n, n); /* B map info */ omp_data_map_info_t *__B_map_info__ = &__off_info__->data_map_info[1]; omp_data_map_init_info("B", __B_map_info__, __off_info__, B, 2, sizeof(REAL), OMP_DATA_MAP_TO, OMP_DATA_MAP_AUTO); omp_data_map_info_set_dims_2d(__B_map_info__, n, n); /* C map info */ omp_data_map_info_t *__C_map_info__ = &__off_info__->data_map_info[2]; omp_data_map_init_info("C", __C_map_info__, __off_info__, C, 2, sizeof(REAL), OMP_DATA_MAP_FROM, OMP_DATA_MAP_AUTO); omp_data_map_info_set_dims_2d(__C_map_info__, n, n); /**************************************** dist-specific *****************************************/ /* row-wise distribution */ #if 0 /* block_block */ omp_data_map_dist_init_info(__C_map_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); omp_data_map_dist_init_info(__C_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_loop_dist_init_info(__off_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); printf("BLOCK dist policy for arrays and loop dist\n"); #endif #if 0 /* block_align */ omp_data_map_dist_init_info(__C_map_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); omp_data_map_dist_init_info(__C_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_loop_dist_align_with_data_map(__off_info__, 0, 0, __C_map_info__, 0); printf("BLOCK dist policy for arrays, and loop dist align with array C/A row dist\n"); #endif /* align_auto */ omp_loop_dist_init_info(__off_info__, 0, LOOP_DIST_POLICY, 0, n, LOOP_DIST_CHUNK_SIZE, 0); omp_data_map_dist_align_with_loop(__C_map_info__, 0, 0, __off_info__, 0); omp_data_map_dist_init_info(__C_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 0); /* this is common for all row-wise distribution */ omp_data_map_dist_init_info(__B_map_info__, 0, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_data_map_dist_init_info(__B_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_data_map_dist_align_with_loop(__A_map_info__, 0, 0, __off_info__, 0); omp_data_map_dist_init_info(__A_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 0); //omp_data_map_dist_align_with_data_map(__A_map_info__, OMP_ALL_DIMENSIONS, 0, __C_map_info__, OMP_ALL_DIMENSIONS); #if 0 /* col-wise distribution */ omp_data_map_dist_init_info(__A_map_info__, 0, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_data_map_dist_init_info(__A_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_data_map_dist_init_info(__C_map_info__, 0, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_data_map_dist_init_info(__C_map_info__, 1, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); omp_data_map_dist_align_with_data_map(__B_map_info__, OMP_ALL_DIMENSIONS, 0, __C_map_info__, OMP_ALL_DIMENSIONS); omp_loop_dist_init_info(__off_info__, 1, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); #endif #if 0 /* row/col-wise distribution */ omp_data_map_dist_init_info(__C_map_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); omp_data_map_dist_init_info(__C_map_info__, 1, OMP_DIST_POLICY_BLOCK, 0, n, 0, 1); omp_data_map_dist_init_info(__A_map_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); /* or align with C[0] */ omp_data_map_dist_init_info(__A_map_info__, 1, OMP_DIST_POLICY_FULL, 0, n, 0, 1); omp_data_map_dist_init_info(__B_map_info__, 0, OMP_DIST_POLICY_FULL, 0, n, 0, 0); omp_data_map_dist_init_info(__B_map_info__, 1, OMP_DIST_POLICY_BLOCK, 0, n, 0, 1); /* or align with C[1] */ omp_loop_dist_init_info(__off_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0); omp_loop_dist_init_info(__off_info__, 1, OMP_DIST_POLICY_BLOCK, 0, n, 0, 1); #endif /************************************************************************************************/ /*********** NOW notifying helper thread to work on this offload ******************/ #if DEBUG_MSG printf("=========================================== offloading to %d targets ==========================================\n", __num_target_devices__); #endif ompacc_init_time = read_timer_ms() - ompacc_init_time; /* here we do not need sync start */ double off_total = read_timer_ms(); int it; int total_its = 10; for (it = 0; it < total_its; it++) { __off_info__->count = 0; omp_offloading_start(__off_info__); } off_total = (read_timer_ms() - off_total) / total_its; #if defined (OMP_BREAKDOWN_TIMING) omp_print_map_info(__A_map_info__); omp_print_map_info(__B_map_info__); omp_print_map_info(__C_map_info__); omp_offloading_info_report_profile(__off_info__, total_its); #endif omp_offloading_fini_info(__off_info__); omp_grid_topology_fini(__top__); off_total += ompacc_init_time; return off_total; }
basic_openmp.c
#include <stdio.h> #include <stdlib.h> int main(){ #pragma omp parallel { printf( "Hello World\n" ); } return EXIT_SUCCESS; }
GB_binop__lt_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__lt_int32 // A.*B function (eWiseMult): GB_AemultB__lt_int32 // A*D function (colscale): GB_AxD__lt_int32 // D*A function (rowscale): GB_DxB__lt_int32 // C+=B function (dense accum): GB_Cdense_accumB__lt_int32 // C+=b function (dense accum): GB_Cdense_accumb__lt_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lt_int32 // C=scalar+B GB_bind1st__lt_int32 // C=scalar+B' GB_bind1st_tran__lt_int32 // C=A+scalar GB_bind2nd__lt_int32 // C=A'+scalar GB_bind2nd_tran__lt_int32 // C type: bool // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x < y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LT || GxB_NO_INT32 || GxB_NO_LT_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__lt_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__lt_int32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__lt_int32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__lt_int32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__lt_int32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__lt_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lt_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lt_int32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t bij = Bx [p] ; Cx [p] = (x < bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__lt_int32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; 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++) { int32_t aij = Ax [p] ; Cx [p] = (aij < y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB_bind1st_tran__lt_int32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #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 typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB_bind2nd_tran__lt_int32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
TBBHashBackend.h
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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. // ---------------------------------------------------------------------------- #pragma once #include <tbb/concurrent_unordered_map.h> #include <limits> #include <unordered_map> #include "open3d/core/hashmap/CPU/CPUHashBackendBufferAccessor.hpp" #include "open3d/core/hashmap/DeviceHashBackend.h" #include "open3d/utility/Parallel.h" namespace open3d { namespace core { template <typename Key, typename Hash, typename Eq> class TBBHashBackend : public DeviceHashBackend { public: TBBHashBackend(int64_t init_capacity, int64_t key_dsize, const std::vector<int64_t>& value_dsizes, const Device& device); ~TBBHashBackend(); void Reserve(int64_t capacity) override; void Insert(const void* input_keys, const std::vector<const void*>& input_values_soa, buf_index_t* output_buf_indices, bool* output_masks, int64_t count) override; void Find(const void* input_keys, buf_index_t* output_buf_indices, bool* output_masks, int64_t count) override; void Erase(const void* input_keys, bool* output_masks, int64_t count) override; int64_t GetActiveIndices(buf_index_t* output_indices) override; void Clear() override; int64_t Size() const override; int64_t GetBucketCount() const override; std::vector<int64_t> BucketSizes() const override; float LoadFactor() const override; std::shared_ptr<tbb::concurrent_unordered_map<Key, buf_index_t, Hash, Eq>> GetImpl() const { return impl_; } void Allocate(int64_t capacity) override; void Free() override{}; protected: std::shared_ptr<tbb::concurrent_unordered_map<Key, buf_index_t, Hash, Eq>> impl_; std::shared_ptr<CPUHashBackendBufferAccessor> buffer_accessor_; }; template <typename Key, typename Hash, typename Eq> TBBHashBackend<Key, Hash, Eq>::TBBHashBackend( int64_t init_capacity, int64_t key_dsize, const std::vector<int64_t>& value_dsizes, const Device& device) : DeviceHashBackend(init_capacity, key_dsize, value_dsizes, device) { Allocate(init_capacity); } template <typename Key, typename Hash, typename Eq> TBBHashBackend<Key, Hash, Eq>::~TBBHashBackend() {} template <typename Key, typename Hash, typename Eq> int64_t TBBHashBackend<Key, Hash, Eq>::Size() const { return impl_->size(); } template <typename Key, typename Hash, typename Eq> void TBBHashBackend<Key, Hash, Eq>::Find(const void* input_keys, buf_index_t* output_buf_indices, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); #pragma omp parallel for num_threads(utility::EstimateMaxThreads()) for (int64_t i = 0; i < count; ++i) { const Key& key = input_keys_templated[i]; auto iter = impl_->find(key); bool flag = (iter != impl_->end()); output_masks[i] = flag; output_buf_indices[i] = flag ? iter->second : 0; } } template <typename Key, typename Hash, typename Eq> void TBBHashBackend<Key, Hash, Eq>::Erase(const void* input_keys, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); for (int64_t i = 0; i < count; ++i) { const Key& key = input_keys_templated[i]; auto iter = impl_->find(key); bool flag = (iter != impl_->end()); output_masks[i] = flag; if (flag) { buffer_accessor_->DeviceFree(iter->second); impl_->unsafe_erase(iter); } } } template <typename Key, typename Hash, typename Eq> int64_t TBBHashBackend<Key, Hash, Eq>::GetActiveIndices( buf_index_t* output_buf_indices) { int64_t count = impl_->size(); int64_t i = 0; for (auto iter = impl_->begin(); iter != impl_->end(); ++iter, ++i) { output_buf_indices[i] = static_cast<int64_t>(iter->second); } return count; } template <typename Key, typename Hash, typename Eq> void TBBHashBackend<Key, Hash, Eq>::Clear() { impl_->clear(); this->buffer_->ResetHeap(); } template <typename Key, typename Hash, typename Eq> void TBBHashBackend<Key, Hash, Eq>::Reserve(int64_t capacity) { impl_->rehash(std::ceil(capacity / impl_->max_load_factor())); } template <typename Key, typename Hash, typename Eq> int64_t TBBHashBackend<Key, Hash, Eq>::GetBucketCount() const { return impl_->unsafe_bucket_count(); } template <typename Key, typename Hash, typename Eq> std::vector<int64_t> TBBHashBackend<Key, Hash, Eq>::BucketSizes() const { int64_t bucket_count = impl_->unsafe_bucket_count(); std::vector<int64_t> ret; for (int64_t i = 0; i < bucket_count; ++i) { ret.push_back(impl_->unsafe_bucket_size(i)); } return ret; } template <typename Key, typename Hash, typename Eq> float TBBHashBackend<Key, Hash, Eq>::LoadFactor() const { return impl_->load_factor(); } template <typename Key, typename Hash, typename Eq> void TBBHashBackend<Key, Hash, Eq>::Insert( const void* input_keys, const std::vector<const void*>& input_values_soa, buf_index_t* output_buf_indices, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); size_t n_values = input_values_soa.size(); #pragma omp parallel for num_threads(utility::EstimateMaxThreads()) for (int64_t i = 0; i < count; ++i) { output_buf_indices[i] = 0; output_masks[i] = false; const Key& key = input_keys_templated[i]; // Try to insert a dummy buffer index. auto res = impl_->insert({key, 0}); // Lazy copy key value pair to buffer only if succeeded if (res.second) { buf_index_t buf_index = buffer_accessor_->DeviceAllocate(); void* key_ptr = buffer_accessor_->GetKeyPtr(buf_index); // Copy templated key to buffer *static_cast<Key*>(key_ptr) = key; // Copy/reset non-templated value in buffer for (size_t j = 0; j < n_values; ++j) { uint8_t* dst_value = static_cast<uint8_t*>( buffer_accessor_->GetValuePtr(buf_index, j)); const uint8_t* src_value = static_cast<const uint8_t*>(input_values_soa[j]) + this->value_dsizes_[j] * i; std::memcpy(dst_value, src_value, this->value_dsizes_[j]); } // Update from dummy 0 res.first->second = buf_index; // Write to return variables output_buf_indices[i] = buf_index; output_masks[i] = true; } } } template <typename Key, typename Hash, typename Eq> void TBBHashBackend<Key, Hash, Eq>::Allocate(int64_t capacity) { this->capacity_ = capacity; this->buffer_ = std::make_shared<HashBackendBuffer>( this->capacity_, this->key_dsize_, this->value_dsizes_, this->device_); buffer_accessor_ = std::make_shared<CPUHashBackendBufferAccessor>(*this->buffer_); impl_ = std::make_shared< tbb::concurrent_unordered_map<Key, buf_index_t, Hash, Eq>>( capacity, Hash(), Eq()); } } // namespace core } // namespace open3d
pt_to_pt_multiPingping.c
/***************************************************************************** * * * Mixed-mode OpenMP/MPI MicroBenchmark Suite - Version 1.0 * * * * produced by * * * * Mark Bull, Jim Enright and Fiona Reid * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: markb@epcc.ed.ac.uk, fiona@epcc.ed.ac.uk * * * * * * Copyright 2012, The University of Edinburgh * * * * * * 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. * * * ****************************************************************************/ /*-----------------------------------------------------------*/ /* Contains the point-to-point multi-pingping mixed mode */ /* OpenMP/MPI benchmarks. */ /* This includes: -masteronly multiPingping */ /* -funnelled multiPingping */ /* -multiple multiPingping */ /*-----------------------------------------------------------*/ #include "pt_to_pt_multiPingping.h" /*-----------------------------------------------------------*/ /* multiPingPing */ /* */ /* Driver subroutine for the multi-pingping benchmark. */ /*-----------------------------------------------------------*/ int multiPingping(int benchmarkType){ int dataSizeIter; char otherProcName[MPI_MAX_PROCESSOR_NAME]; int balance; pingNodeA = 0; pingNodeB = 1; /* Check if there's a balance in num of MPI processes on pingNodeA and pingNodeB. */ balance = crossCommBalance(pingNodeA, pingNodeB); /* If not balanced.. */ if (balance == FALSE){ /* ..master prints error */ if (myMPIRank == 0){ printBalanceError(); } /* ..and all process exit function. */ return 1; } /* Exchange MPI_COMM_WORLD ranks for processes in same crossComm */ exchangeWorldRanks(pingNodeA, pingNodeB, &otherPingRank); /* Processes on pongNode send processor name to pingNode procs. */ sendProcName(pingNodeA, pingNodeB, otherProcName); /* Print comm world ranks & processor name of processes * taking part in multi-pingpong benchmark. */ printMultiProcInfo(pingNodeA, otherPingRank, otherProcName); /* Barrier to ensure that all procs have completed * printMultiProcInfo before prinring column headings. */ MPI_Barrier(comm); /* Master process then prints report column headings */ if (myMPIRank == 0){ printBenchHeader(); } /* Initialise repsToDo to defaultReps at start of benchmark */ repsToDo = defaultReps; /* Initialise dataSizeIter */ dataSizeIter = minDataSize; /* Start loop over data sizes */ while (dataSizeIter <= maxDataSize){ /* set size of buffer */ sizeofBuffer = dataSizeIter * numThreads; /* Allocate space for the main data arrays */ allocateMultiPingpingData(sizeofBuffer); /* warm-up */ if (benchmarkType == MASTERONLY){ /* Masteronly warm-up */ masteronlyMultiPingping(warmUpIters, dataSizeIter); } else if (benchmarkType == FUNNELLED){ /* Funnelled warm-up sweep */ funnelledMultiPingping(warmUpIters, dataSizeIter); } else if (benchmarkType == MULTIPLE){ /* Multiple pingpong warm-up */ multipleMultiPingping(warmUpIters, dataSizeIter); } /* Verification test for multi-pingpong */ testMultiPingping(sizeofBuffer, dataSizeIter); /* Initialise benchmark */ benchComplete = FALSE; /* Keep executing benchmark until target time is reached */ while (benchComplete != TRUE){ /* MPI_Barrier to synchronise processes. Then start the timer. */ MPI_Barrier(comm); startTime = MPI_Wtime(); if (benchmarkType == MASTERONLY){ /* Execute masteronly multipingpong repsToDo times */ masteronlyMultiPingping(repsToDo, dataSizeIter); } else if (benchmarkType == FUNNELLED){ /* Execute funnelled multipingpong */ funnelledMultiPingping(repsToDo, dataSizeIter); } else if (benchmarkType == MULTIPLE){ multipleMultiPingping(repsToDo, dataSizeIter); } /* Stop the timer..MPI_Barrier to synchronise processes * for more accurate timing. */ MPI_Barrier(comm); finishTime = MPI_Wtime(); totalTime = finishTime - startTime; /* Call repTimeCheck to check if target time is reached. */ if (myMPIRank==0){ benchComplete = repTimeCheck(totalTime, repsToDo); } /* Ensure all procs have the same value of benchComplete */ /* and repsToDo */ MPI_Bcast(&benchComplete, 1, MPI_INT, 0, comm); MPI_Bcast(&repsToDo, 1, MPI_INT, 0, comm); } /* End of loop to check if benchComplete is true */ /* Master process sets benchmark results */ if (myMPIRank == 0){ setReportParams(dataSizeIter, repsToDo, totalTime); printReport(); } /* Free the allocated space for the main data arrays */ freeMultiPingpingData(); /* Update dataSize before next iteration */ dataSizeIter = dataSizeIter * 2; } return 0; } /*-----------------------------------------------------------*/ /* masteronlyMultiPingping */ /* */ /* All Processes with rank of pingNodeA or pingNodeB in */ /* crossComm send a message to each other. */ /* MPI communication takes place outside of the parallel */ /* region. */ /*-----------------------------------------------------------*/ int masteronlyMultiPingping(int totalReps, int dataSize){ int repIter, i; int destRank; /* set destRank to ID of other process */ if (crossCommRank == pingNodeA){ destRank = pingNodeB; } else if (crossCommRank == pingNodeB){ destRank = pingNodeA; } /* loop totalRep times */ for (repIter=1; repIter<=totalReps; repIter++){ if ((crossCommRank == pingNodeA) || (crossCommRank == pingNodeB) ){ /* Each thread writes its globalID to pingSendBuf * with a parallel for directive. */ #pragma omp parallel for default(none) \ private(i) \ shared(pingSendBuf,dataSize,sizeofBuffer,globalIDarray) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pingSendBuf[i] = globalIDarray[myThreadID]; } /* Process calls non-blocking send to start transfer of * pingSendBuf to other process. */ MPI_Isend(pingSendBuf, sizeofBuffer, MPI_INT, destRank, TAG,\ crossComm, &requestID); /* Processes then wait for message from other process. */ MPI_Recv(pingRecvBuf, sizeofBuffer, MPI_INT, destRank, TAG, \ crossComm, &status); /* Finish the send operation with an MPI_Wait */ MPI_Wait(&requestID, &status); /* Threads under the MPI processes read their part of the * received buffer. */ #pragma omp parallel for default(none) \ private(i) \ shared(finalRecvBuf,dataSize,sizeofBuffer,pingRecvBuf) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalRecvBuf[i] = pingRecvBuf[i]; } } } /* End repetitions loop */ return 0; } /*-----------------------------------------------------------*/ /* funnelledMultiPingping */ /* */ /* All processes with rank of pingNodeA or pingNodeB in */ /* crossComm send a message to each other. */ /* Inter-process communication takes place inside the */ /* OpenMP parallel region by the master thread. */ /*-----------------------------------------------------------*/ int funnelledMultiPingping(int totalReps, int dataSize){ int repIter, i; int destRank; /* Set destRank to id of other process */ if (crossCommRank == pingNodeA){ destRank = pingNodeB; } else if (crossCommRank == pingNodeB){ destRank = pingNodeA; } /* Open the parallel region */ #pragma omp parallel \ private(i,repIter) \ shared(dataSize,sizeofBuffer,pingSendBuf,globalIDarray) \ shared(pingRecvBuf,finalRecvBuf,status,requestID,destRank) \ shared(crossComm,crossCommRank,pingNodeA,pingNodeB,totalReps) { /* loop totalRep times */ for (repIter = 1; repIter <= totalReps; repIter++){ if (crossCommRank == pingNodeA || crossCommRank == pingNodeB){ /* Each thread writes its globalID to its part of * pingSendBuf with an omp for. */ #pragma omp for schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pingSendBuf[i] = globalIDarray[myThreadID]; } /* Implicit barrier here takes care of necessary synchronisation. */ #pragma omp master { /* Master thread of each process starts send. */ MPI_Isend(pingSendBuf, sizeofBuffer, MPI_INT, \ destRank, TAG, crossComm, &requestID); /* Processes then wait for message. */ MPI_Recv(pingRecvBuf, sizeofBuffer, MPI_INT, \ destRank, TAG, crossComm, &status); /* Finish the send operation with an MPI_Wait */ MPI_Wait(&requestID, &status); } /* Barrier to ensure master thread has completed transfer. */ #pragma omp barrier /* Each thread reads its part of the received buffer */ #pragma omp for schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalRecvBuf[i] = pingRecvBuf[i]; } } } /* End repetitions loop */ } /* End parallel region */ return 0; } /*-----------------------------------------------------------*/ /* multipleMultiPingping */ /* */ /* All processes with crossCommRank of pingNodeA and */ /* pingNodeB in crossComm send a message to each other. */ /* Multiple threads take part in the communication. */ /*-----------------------------------------------------------*/ int multipleMultiPingping(int totalReps, int dataSize){ int repIter, i; int destRank; int lBound; /* set destRank to be id of other process */ if (crossCommRank == pingNodeA){ destRank = pingNodeB; } else if (crossCommRank == pingNodeB){ destRank = pingNodeA; } /* Open parallel region */ #pragma omp parallel \ private(i,repIter,lBound,requestID,status) \ shared(dataSize,sizeofBuffer,pingSendBuf,globalIDarray) \ shared(pingRecvBuf,finalRecvBuf,destRank,crossComm) \ shared(crossCommRank,pingNodeA,pingNodeB,totalReps) { /* loop totalRep times */ for (repIter = 1; repIter <= totalReps; repIter++){ if (crossCommRank == pingNodeA || crossCommRank == pingNodeB){ /* Calculate lower bound of each threads portion * of the data array. */ lBound = (myThreadID * dataSize); /* Each thread writes to its part of pingSendBuf */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pingSendBuf[i] = globalIDarray[myThreadID]; } /* Each thread starts send of dataSize items from * pingSendBuf. */ MPI_Isend(&pingSendBuf[lBound], dataSize, MPI_INT, \ destRank, myThreadID, crossComm, &requestID); /* Thread then waits for message from destRank * with tag equal to its threadID. */ MPI_Recv(&pingRecvBuf[lBound], dataSize, MPI_INT, destRank, \ myThreadID, crossComm, &status); /* Thread completes send using MPI_Wait */ MPI_Wait(&requestID, &status); /* Each thread reads its part of received buffer. */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalRecvBuf[i] = pingRecvBuf[i]; } } } /* End repetitions loop */ } return 0; } /*-----------------------------------------------------------*/ /* allocateMultiPingpingData */ /* */ /* Allocates space for the main data arrays. */ /* Size of each array is specified by subroutine argument. */ /*-----------------------------------------------------------*/ int allocateMultiPingpingData(int sizeofBuffer){ if (crossCommRank == pingNodeA || crossCommRank == pingNodeB){ pingSendBuf = (int *)malloc(sizeof(int) * sizeofBuffer); pingRecvBuf = (int *)malloc(sizeof(int) * sizeofBuffer); finalRecvBuf = (int *)malloc(sizeof(int) * sizeofBuffer); } return 0; } /*-----------------------------------------------------------*/ /* freeMultiPingpingData */ /* */ /* Free allocated memory for main data arrays. */ /*-----------------------------------------------------------*/ int freeMultiPingpingData(){ if (crossCommRank == pingNodeA || crossCommRank == pingNodeB){ free(pingSendBuf); free(pingRecvBuf); free(finalRecvBuf); } return 0; } /*-----------------------------------------------------------*/ /* testMultiPingping */ /* */ /* Verifies the the multi-pingping benchmark worked */ /* correctly. */ /*-----------------------------------------------------------*/ int testMultiPingping(int sizeofBuffer, int dataSize){ int i; int testFlag, localTestFlag; /* set localTestFlag to true */ localTestFlag = TRUE; /* Testing done for processes on pingNodeA & pingNodeB */ if (crossCommRank == pingNodeA || crossCommRank == pingNodeB) { /* allocate space for testBuf */ testBuf = (int *)malloc(sizeof(int) * sizeofBuffer); /* Construct testBuf with correct values */ #pragma omp parallel for default(none) \ private(i) \ shared(otherPingRank,numThreads,dataSize,sizeofBuffer,testBuf) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ /* calculate globalID of thread expected in finalRecvBuf. * This is done using otherPingRank. */ testBuf[i] = (otherPingRank * numThreads) + myThreadID; } /* Compare each element of testBuf and finalRecvBuf */ for (i=0; i<sizeofBuffer; i++){ if (testBuf[i] != finalRecvBuf[i]){ localTestFlag = FALSE; } } /* Free space for testBuf */ free(testBuf); } /* Reduce testFlag into master with logical AND */ MPI_Reduce(&localTestFlag, &testFlag, 1, MPI_INT, MPI_LAND, 0, comm); /* master sets testOutcome flag */ if (myMPIRank == 0){ setTestOutcome(testFlag); } return 0; }
gusp.c
/* This code implements a parallel version of Gusfield's flow equivalent tree algorithm using OpenMP. If results are reported, references should include: J. Cohen, L. A. Rodrigues, F. Silva, R. Carmo, A. Guedes, E. P. Duarte Jr., "Parallel Implementations of Gusfield's Cut Tree Algorithm," 11th International Conference Algorithms and Architectures for Parallel Processing (ICA3PP), pp. 258-269, Lecture Notes in Computer Science (LNCS) 7016, ISSN 0302-9743, Melbourne, Australia, 2011. This code is derived from HIPR by IG Systems, Inc. HIPR implements a maximum flow - highest level push-relabel algorithm http://www.igsystems.com/hipr/ Commercial use requires a license. */ /* gusp_opt3.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #include <omp.h> //(lar) #include "values.h" #include "types.h" /* type definitions */ #include "parser_undirected.c" /* parser */ #include "timer.c" /* timing routine */ /* #define GLOB_UPDT_FREQ 0.5 */ #define GLOB_UPDT_FREQ 0.5 #define ALPHA 6 #define BETA 12 #define WHITE 0 #define GREY 1 #define BLACK 2 /* global variables */ long n; /* number of nodes */ long m; /* number of arcs */ long nm; /* n + ALPHA * m */ long nMin; /* smallest node id */ cType *cap; /* array of capacities */ float globUpdtFreq; /* global update frequency */ int seed; // typedef struct graph *Graph; typedef struct graph { node *nodes; /* array of nodes */ arc *arcs; /* array of arcs */ bucket *buckets; /* array of buckets */ node *source; /* source node pointer */ node *sink; /* sink node pointer */ //node **queue; /* queue for BFS */ //node **qHead, **qTail, **qLast; /* queue pointers */ long dMax; /* maximum label */ long aMax; /* maximum active node label */ long aMin; /* minimum active node label */ double flow; /* flow value */ long pushCnt; /* number of pushes */ long relabelCnt; /* number of relabels */ long updateCnt; /* number of updates */ long gapCnt; /* number of gaps */ long gNodeCnt; /* number of nodes after gap */ float t, t2; /* for saving times */ node *sentinelNode; /* end of the node list marker */ arc *stopA; /* used in forAllArcs */ long workSinceUpdate; /* the number of arc scans since last update */ /* more variables that can't be shared by threads */ long i_dist; node *i_next, *i_prev; } *Graph;//end graph // begin: variables declarations (jc) long *tree; double *tree_weights; long step; // end: variables (jc) /* macros */ #define forAllNodes(i, G) for ( i = G->nodes; i != G->sentinelNode; i++ ) #define forAllArcs(i,a, G) for (a = i->first, G->stopA = (i+1)->first; a != G->stopA; a++) #define nNode( i, G ) ( (i) - G->nodes + nMin ) // Index(): from pointer to index (jc) #define Index( i, G ) ( (i) - G->nodes ) #define nArc( a, G ) ( ( a == NULL )? -1 : (a) - G->arcs ) #define min( a, b ) ( ( (a) < (b) ) ? a : b ) /* FIFO queue for BFS macros */ /* #define qInit() \ {\ qHead = qTail = queue;\ } #define qEmpty ( qHead == qTail ) #define qEnqueue(i) \ {\ *qTail = i;\ if ( qTail == qLast ) qTail = queue;\ else qTail++;\ } #define qDequeue(i) \ {\ i = *qHead;\ if ( qHead == qLast ) qHead = queue;\ else qHead++;\ } */ /* bucket macros: bucket's active node list is singly-linked operations aAdd, aRemove (from the front) bucket's inactive list is doubly-linked operations iAdd, iDelete (from arbitrary position) */ #define aAdd(l,i, G)\ {\ i->bNext = l->firstActive;\ l->firstActive = i;\ G->i_dist = i->d;\ if (G->i_dist < G->aMin)\ G->aMin = G->i_dist;\ if (G->i_dist > G->aMax)\ G->aMax = G->i_dist;\ if (G->dMax < G->aMax)\ G->dMax = G->aMax;\ } /* i must be the first element */ #define aRemove(l,i) \ {\ l->firstActive = i->bNext;\ } #define iAdd(l,i, G)\ {\ G->i_next = l->firstInactive;\ i->bNext = G->i_next;\ i->bPrev = G->sentinelNode;\ G->i_next->bPrev = i;\ l->firstInactive = i;\ } #define iDelete(l,i, G) \ {\ G->i_next = i->bNext;\ if (l->firstInactive == i) {\ l->firstInactive = G->i_next;\ G->i_next->bPrev = G->sentinelNode;\ }\ else {\ G->i_prev = i->bPrev;\ G->i_prev->bNext = G->i_next;\ G->i_next->bPrev = G->i_prev;\ }\ } /* allocate datastructures, initialize related variables */ int allocDS( Graph G ) { nm = ALPHA * n + m; /* queue = (node**) calloc ( n, sizeof (node*) ); if ( queue == NULL ) return ( 1 ); qLast = queue + n - 1; qInit(); */ G->buckets = (bucket*) calloc ( n+2, sizeof (bucket) ); if ( G->buckets == NULL ) return ( 1 ); G->sentinelNode = G->nodes + n; G->sentinelNode->first = G->arcs + 2*m; return ( 0 ); } /* end of allocate */ void init( Graph G ) { node *i; /* current node */ int overflowDetected; bucket *l; arc *a; #ifdef EXCESS_TYPE_LONG double testExcess; #endif #ifndef OLD_INIT unsigned long delta; #endif G->pushCnt = 0; /* number of pushes */ G->relabelCnt = 0; /* number of relabels */ G->updateCnt = 0; /* number of updates */ G->gapCnt = 0; /* number of gaps */ G->gNodeCnt = 0; /* number of nodes after gap */ G->workSinceUpdate=0; // initialize excesses forAllNodes(i, G) { i->excess = 0; i->current = i->first; forAllArcs(i, a, G) { a->resCap = cap[a-G->arcs]; // a->rev->resCap = cap[a-arcs]; // for undirected graphs, did not work. jc } } for (l = G->buckets; l <= G->buckets + n-1; l++) { l -> firstActive = G->sentinelNode; l -> firstInactive = G->sentinelNode; } overflowDetected = 0; #ifdef EXCESS_TYPE_LONG testExcess = 0; forAllArcs(source,a, G) { if (a->head != G->source) { testExcess += a->resCap; } } if (testExcess > MAXLONG) { printf("c WARNING: excess overflow. See README for details.\nc\n"); overflowDetected = 1; } #endif #ifdef OLD_INIT G->source -> excess = MAXLONG; #else if (overflowDetected) { G->source -> excess = MAXLONG; } else { G->source->excess = 0; forAllArcs(G->source,a, G) { if (a->head != G->source) { G->pushCnt ++; delta = a -> resCap; a -> resCap -= delta; (a -> rev) -> resCap += delta; a->head->excess += delta; } } } /* setup labels and buckets */ l = G->buckets + 1; G->aMax = 0; G->aMin = n; forAllNodes(i, G) { if (i == G->sink) { i->d = 0; iAdd(G->buckets,i, G); continue; } if ((i == G->source) && (!overflowDetected)) { i->d = n; } else i->d = 1; if (i->excess > 0) { /* put into active list */ aAdd(l,i, G); } else { /* i -> excess == 0 */ /* put into inactive list */ if (i->d < n) iAdd(l,i, G); } } G->dMax = 1; #endif // dMax = n-1; G->flow = 0.0; } /* end of init */ void checkMax(Graph G) { bucket *l; for (l = G->buckets + G->dMax + 1; l < G->buckets + n; l++) { assert(l->firstActive == G->sentinelNode); assert(l->firstInactive == G->sentinelNode); } } /* global update via backward breadth first search from the sink */ void globalUpdate (Graph G) { node *i, *j; /* node pointers */ arc *a; /* current arc pointers */ bucket *l, *jL; /* bucket */ long curDist, jD; long state; G->updateCnt ++; /* initialization */ forAllNodes(i, G) i -> d = n; G->sink -> d = 0; // Era "l <= buckets + dmax". // Essa modificacao evita o segmentation fault na // instancia dblcyc.1024 e produz a resposta correta. // As linha abaixo apenas inicializam os buckets. for (l = G->buckets; l <= G->buckets + n; l++) { l -> firstActive = G->sentinelNode; l -> firstInactive = G->sentinelNode; } G->dMax = G->aMax = 0; G->aMin = n; /* breadth first search */ // add sink to bucket zero iAdd(G->buckets, G->sink, G); for (curDist = 0; 1; curDist++) { state = 0; l = G->buckets + curDist; jD = curDist + 1; jL = l + 1; /* jL -> firstActive = sentinelNode; jL -> firstInactive = sentinelNode; */ if ((l->firstActive == G->sentinelNode) && (l->firstInactive == G->sentinelNode)) break; while (1) { switch (state) { case 0: i = l->firstInactive; state = 1; break; case 1: i = i->bNext; break; case 2: i = l->firstActive; state = 3; break; case 3: i = i->bNext; break; default: assert(0); break; } if (i == G->sentinelNode) { if (state == 1) { state = 2; continue; } else { assert(state == 3); break; } } /* scanning arcs incident to node i */ forAllArcs(i,a, G) { if (a->rev->resCap > 0 ) { j = a->head; if (j->d == n) { j->d = jD; j->current = j->first; if (jD > G->dMax) G->dMax = jD; if (j->excess > 0) { /* put into active list */ aAdd(jL,j, G); } else { /* put into inactive list */ iAdd(jL,j, G); } } } } /* node i is scanned */ } } } /* end of global update */ /* second stage -- preflow to flow */ void stageTwo ( Graph G ) /* do dsf in the reverse flow graph from nodes with excess cancel cycles if found return excess flow in topological order */ /* i->d is used for dfs labels i->bNext is used for topological order list buckets[i-nodes]->firstActive is used for DSF tree */ { node *i, *j, *tos, *bos, *restart, *r; arc *a; cType delta; /* deal with self-loops */ forAllNodes(i, G) { forAllArcs(i,a, G) if ( a -> head == i ) { a -> resCap = cap[a - G->arcs]; } } /* initialize */ tos = bos = NULL; forAllNodes(i, G) { i -> d = WHITE; // buckets[i-nodes].firstActive = NULL; G->buckets[i-G->nodes].firstActive = G->sentinelNode; i -> current = i -> first; } /* eliminate flow cycles, topologicaly order vertices */ forAllNodes(i, G) if (( i -> d == WHITE ) && ( i -> excess > 0 ) && ( i != G->source ) && ( i != G->sink )) { r = i; r -> d = GREY; do { for ( ; i->current != (i+1)->first; i->current++) { a = i -> current; if (( cap[a - G->arcs] == 0 ) && ( a -> resCap > 0 )) { j = a -> head; if ( j -> d == WHITE ) { /* start scanning j */ j -> d = GREY; G->buckets[j-G->nodes].firstActive = i; i = j; break; } else if ( j -> d == GREY ) { /* find minimum flow on the cycle */ delta = a -> resCap; while ( 1 ) { delta = min ( delta, j -> current -> resCap ); if ( j == i ) break; else j = j -> current -> head; } /* remove delta flow units */ j = i; while ( 1 ) { a = j -> current; a -> resCap -= delta; a -> rev -> resCap += delta; j = a -> head; if ( j == i ) break; } /* backup DFS to the first saturated arc */ restart = i; for ( j = i -> current -> head; j != i; j = a -> head ) { a = j -> current; if (( j -> d == WHITE ) || ( a -> resCap == 0 )) { j -> current -> head -> d = WHITE; if ( j -> d != WHITE ) restart = j; } } if ( restart != i ) { i = restart; i->current++; break; } } } } if (i->current == (i+1)->first) { /* scan of i complete */ i -> d = BLACK; if ( i != G->source ) { if ( bos == NULL ) { bos = i; tos = i; } else { i -> bNext = tos; tos = i; } } if ( i != r ) { i = G->buckets[i-G->nodes].firstActive; i->current++; } else break; } } while ( 1 ); } /* return excesses */ /* note that sink is not on the stack */ if ( bos != NULL ) { for ( i = tos; i != bos; i = i -> bNext ) { a = i -> first; while ( i -> excess > 0 ) { if (( cap[a - G->arcs] == 0 ) && ( a -> resCap > 0 )) { if (a->resCap < i->excess) delta = a->resCap; else delta = i->excess; a -> resCap -= delta; a -> rev -> resCap += delta; i -> excess -= delta; a -> head -> excess += delta; } a++; } } /* now do the bottom */ i = bos; a = i -> first; while ( i -> excess > 0 ) { if (( cap[a - G->arcs] == 0 ) && ( a -> resCap > 0 )) { if (a->resCap < i->excess) delta = a->resCap; else delta = i->excess; a -> resCap -= delta; a -> rev -> resCap += delta; i -> excess -= delta; a -> head -> excess += delta; } a++; } } } /* gap relabeling */ int gap (bucket *emptyB, Graph G) { bucket *l; node *i; long r; /* index of the bucket before l */ int cc; /* cc = 1 if no nodes with positive excess before the gap */ G->gapCnt ++; r = ( emptyB - G->buckets ) - 1; /* set labels of nodes beyond the gap to "infinity" */ for ( l = emptyB + 1; l <= G->buckets + G->dMax; l ++ ) { /* this does nothing for high level selection for (i = l -> firstActive; i != sentinelNode; i = i -> bNext) { i -> d = n; gNodeCnt++; } l -> firstActive = sentinelNode; */ for ( i = l -> firstInactive; i != G->sentinelNode; i = i -> bNext ) { i -> d = n; G->gNodeCnt ++; } l -> firstInactive = G->sentinelNode; } cc = ( G->aMin > r ) ? 1 : 0; G->dMax = r; G->aMax = r; return ( cc ); } /*--- relabelling node i */ long relabel (node *i, Graph G) { node *j; long minD; /* minimum d of a node reachable from i */ arc *minA; /* an arc which leads to the node with minimal d */ arc *a; assert(i->excess > 0); G->relabelCnt++; G->workSinceUpdate += BETA; i->d = minD = n; minA = NULL; /* find the minimum */ forAllArcs(i,a, G) { G->workSinceUpdate++; if (a -> resCap > 0) { j = a -> head; if (j->d < minD) { minD = j->d; minA = a; } } } minD++; if (minD < n) { i->d = minD; i->current = minA; if (G->dMax < minD) G->dMax = minD; } /* end of minD < n */ return ( minD ); } /* end of relabel */ /* discharge: push flow out of i until i becomes inactive */ void discharge (node *i, Graph G) { node *j; /* sucsessor of i */ long jD; /* d of the next bucket */ bucket *lj; /* j's bucket */ bucket *l; /* i's bucket */ arc *a; /* current arc (i,j) */ cType delta; arc *stopA; assert(i->excess > 0); assert(i != G->sink); do { jD = i->d - 1; l = G->buckets + i->d; /* scanning arcs outgoing from i */ for (a = i->current, stopA = (i+1)->first; a != stopA; a++) { if (a -> resCap > 0) { j = a -> head; if (j->d == jD) { G->pushCnt ++; if (a->resCap < i->excess) delta = a->resCap; else delta = i->excess; a->resCap -= delta; a->rev->resCap += delta; if (j != G->sink) { lj = G->buckets + jD; if (j->excess == 0) { /* remove j from inactive list */ iDelete(lj,j, G); /* add j to active list */ aAdd(lj,j, G); } } j -> excess += delta; i -> excess -= delta; if (i->excess == 0) break; } /* j belongs to the next bucket */ } /* a is not saturated */ } /* end of scanning arcs from i */ if (a == stopA) { /* i must be relabeled */ relabel (i, G); if (i->d == n) break; if ((l -> firstActive == G->sentinelNode) && (l -> firstInactive == G->sentinelNode) ) gap (l, G); if (i->d == n) break; } else { /* i no longer active */ i->current = a; /* put i on inactive list */ iAdd(l,i, G); break; } } while (1); } // go from higher to lower buckets, push flow void wave( Graph G) { node *i; bucket *l; for (l = G->buckets + G->aMax; l > G->buckets; l--) { for (i = l->firstActive; i != G->sentinelNode; i = l->firstActive) { aRemove(l,i); assert(i->excess > 0); discharge (i, G); } } } /* first stage -- maximum preflow*/ void stageOne ( Graph G ) { node *i; bucket *l; /* current bucket */ #if defined(INIT_UPDATE) || defined(OLD_INIT) || defined(WAVE_INIT) globalUpdate (); #endif G->workSinceUpdate = 0; #ifdef WAVE_INIT wave(); #endif /* main loop */ while ( G->aMax >= G->aMin ) { l = G->buckets + G->aMax; i = l->firstActive; if (i == G->sentinelNode) G->aMax--; else { aRemove(l,i); assert(i->excess > 0); discharge (i, G); if (G->aMax < G->aMin) break; /* is it time for global update? */ if (G->workSinceUpdate * globUpdtFreq > nm) { globalUpdate (G); G->workSinceUpdate = 0; } // check wether the sink is still the neighbor of the source // in the tree or if it was changed by another Thread #ifdef SHORTFLOW if (G->sink != G->nodes + tree[Index(G->source, G)]) return ; #endif } } /* end of the main loop */ G->flow = G->sink -> excess; } void check_solution(Graph g) { node *i; arc *a; excessType sum; bucket *l; /* check if you have a flow (pseudoflow) */ /* check arc flows */ //printf("before tree - t%d step %d\n", id, step); forAllNodes(i, g) { forAllArcs(i,a, g) { if (cap[a - g->arcs] > 0) { /* original arc */ if ((a->resCap + a->rev->resCap != cap[a - g->arcs]) || (a->resCap < 0) || (a->rev->resCap < 0)) { printf("ERROR: bad arc flow\n"); exit(2); } } } } /* check conservation */ stageTwo(g); forAllNodes(i, g) if ((i != g->source) && (i != g->sink)) { if (i->excess != 0) { printf("ERROR: nonzero node excess\n"); exit(2); } sum = 0; forAllArcs(i,a, g) { if (cap[a - g->arcs] > 0) /* original arc */ sum -= cap[a - g->arcs] - a->resCap; else sum += a->resCap; } if (i->excess != sum) { printf("ERROR: conservation constraint violated\n"); exit(2); } } /* check if mincut is saturated */ g->aMax = g->dMax = 0; for (l = g->buckets; l < g->buckets + n; l++) { l->firstActive = g->sentinelNode; l->firstInactive = g->sentinelNode; } globalUpdate(g); if (g->source->d < n) { printf("ERROR: the solution is not optimal\n"); exit(2); } printf("c Solution checks (feasible and optimal)\n"); } void print_stat(Graph G) { printf ("c pushes: %10ld\n", G->pushCnt); printf ("c relabels: %10ld\n", G->relabelCnt); printf ("c updates: %10ld\n", G->updateCnt); printf ("c gaps: %10ld\n", G->gapCnt); printf ("c gap nodes: %10ld\n", G->gNodeCnt); printf ("c\n"); } void print_graph(Graph G) { node *i; arc *a; forAllNodes(i, G) { long ni = nNode(i, G); printf("n=%ld\n", ni); forAllArcs(i, a, G) { printf("{%ld, %ld}, ", ni, nNode( a -> head, G )); } printf("\n"); } } int RandomInteger (int low, int high); typedef struct neighbor { long node; struct neighbor *next; } * neighbor; int main (int argc, char *argv[]) { node *j; int cc; if (argc > 4 || argc < 3) { printf("Usage: %s nthreads inputfile [update frequency]\n", argv[0]); exit(1); } if (argc < 4) seed = 1; else seed = (unsigned) atoi(argv[3]); if (argc != 5) globUpdtFreq = GLOB_UPDT_FREQ; else globUpdtFreq = (float) atof(argv[4]); int NTHREADS = (int) atoi(argv[1]); // printf("c\nc hi_pr version 3.6\n"); // printf("c Copyright C by IG Systems, igsys@eclipse.net\nc\n"); // Allocate and read one copy of the graph for each thread Graph *G = (Graph *) calloc(NTHREADS, sizeof(Graph)); if (G == NULL) { fprintf ( stderr, "Allocation error\n"); exit ( 1 ); } int k; long max_degree = -1; for (k=0; k<NTHREADS; k++) { G[k] = (Graph ) malloc(sizeof(struct graph)); if (G[k] == NULL) { fprintf ( stderr, "Allocation error\n"); exit ( 1 ); } parse(argv[2], &n, &m, &(G[k]->nodes), &(G[k]->arcs), &cap, &nMin ); cc = allocDS(G[k]); if ( cc ) { fprintf ( stderr, "Allocation error\n"); exit ( 1 ); } // weighted degree computation (capacities of the trivial cuts - jc 03/2011) node *v; arc *a; forAllNodes(v, G[k]) { v->degree = 0; forAllArcs(v, a, G[k]) { v->degree += a->resCap; } if (v->degree > max_degree) max_degree = v->degree; } } // end of allocate and read graphs // initial permutation of the nodes long *permut = (long *)calloc(n, sizeof(long)); if (permut == NULL) { fprintf ( stderr, "Allocation error\n"); exit ( 1 ); } int i; for (i = 0; i < n; i++) permut[i] = i; #ifndef DONTPERMUTE srand (seed); for (i = 0; i < n-1; i++) { long s_rand = RandomInteger(i, n-1); long tmp = permut[s_rand]; permut[s_rand] = permut[i]; permut[i] = tmp; } #endif #ifdef DEGREE_HEURISTIC long *count = (long *)calloc(max_degree+1, sizeof(long)); long *permut2 = (long *)calloc(n, sizeof(long)); if (count == NULL || permut2 == NULL) { fprintf ( stderr, "Allocation error\n"); exit ( 1 ); } // counting sort the nodes by degree for (i=0; i<=max_degree; i++) count[i] = 0; for (i=0; i<n; i++) count[ (G[0]->nodes + permut[i])->degree]++; for (i=1; i<=max_degree; i++) count[i] += count[i-1]; for (i=0; i<n; i++) #ifdef DECREASING permut2[n - count[(G[0]->nodes+permut[i])->degree]--] = permut[i]; #else permut2[--count[(G[0]->nodes+permut[i])->degree]] = permut[i]; #endif #ifdef VERBOSE for (i=0; i<n; i++) printf("c Node: %ld Degree: %ld\n", permut2[i]+1, (G[0]->nodes+permut2[i])->degree); #endif free(permut); permut = permut2; free(count); #endif // optimization with neighbor lists - jaime 29/10/2010 neighbor st_neighbors = (neighbor) calloc(n+1, sizeof(struct neighbor)); neighbor *neighbors = (neighbor*) calloc(n, sizeof(neighbor)); if (st_neighbors == NULL || neighbors == NULL) { printf("cannot obtain enough memory.\n"); exit(1); } printf("c nodes: %10ld\nc arcs: %10ld\nc\n", n, m); timer1(); double topenstart = omp_get_wtime(); // Tree initialization: // the tree is represented by a vector tree[] such that each node points to its parent // plus linked lists where each node points to its neighbors that have not yet been // separated by a cut. tree = (long *) calloc(n, sizeof(long)); tree_weights = (double *) calloc (n, sizeof(double)); if (tree == NULL || tree_weights == NULL) { printf("can't obtain enough memory to solve this problem.\n"); exit(1); } tree[permut[0]] = -1; tree_weights[permut[0]] = -1.0; st_neighbors[0].node = permut[0]; neighbors[permut[0]] = &st_neighbors[1]; for (i=1; i < n; ++i) { tree[permut[i]] = permut[0]; tree_weights[permut[i]] = -1.0; st_neighbors[i].node = permut[i]; st_neighbors[i].next = &st_neighbors[i+1]; neighbors[permut[i]] = NULL; } st_neighbors[n-1].next = NULL; long success=0, unsuccess=0; //-------------------------------------------------------------------------- // MAIN LOOP //--------------------------------------------------------------------------- // gusfield iteration starts here // , i, a, l, cap, sum #pragma omp parallel for default(none) \ num_threads(NTHREADS) \ private(step) shared(j, tree,tree_weights,G,n, success, unsuccess, \ permut, neighbors) // schedule(guided) // reduction(+:success, unsuccess) //lar for (step=1; step < n; step++) { int id = omp_get_thread_num(); int done = 0; // set the source long source = permut[step]; G[id]->source = G[id]->nodes + source; do { // do until the cut is usefull for this source // set the sink G[id]->sink = G[id]->nodes + tree[source]; // run and time MaxFlow (stageOne) init( G[id] ); stageOne ( G[id] ); #ifdef VERBOSE printf("c Thread %d: source=%ld sink=%ld flow=%.1lf\n", id, source+1, tree[source]+1, G[id]->flow); #endif // adjust labels globalUpdate(G[id]); // verify optimality if (G[id]->source->d < n) { printf("ERROR: the solution is not optimal\n"); exit(2); } #ifdef CHECK_SOLUTION check_solution(G[id]); #endif #ifdef PRINT_STAT print_stat(G[id]); #endif // adjust the tree - CRITICAL REGION #pragma omp critical //(lar) { long target = tree[source]; if (G[id]->sink == G[id]->nodes + target) { done = 1; success++; tree_weights[source] = G[id]->flow; // printf("c >>> source %ld target %ld\n", source+1,target+1); #ifndef NOTRIVIALCUT if (G[id]->source->degree > G[id]->flow) { #endif // for all target's neighbor neighbor nb, prev_nb, next_nb; for (nb = neighbors[target], prev_nb = NULL; nb != NULL; nb = next_nb) { next_nb = nb->next; j = G[id]->nodes + nb->node; if (j->d >= n) // j is a node on the source side { // remove nb from target's list if (prev_nb == NULL) neighbors[target] = nb->next; else prev_nb->next = nb->next; // move nb from target list to source list if (nb->node != source) { nb->next = neighbors[source]; neighbors[source] = nb; tree[nb->node] = source; // nb on the 'source' side } // in both cases above, prev_nb remains unchanged // because nb was removed from the list } else prev_nb = nb; } #ifndef NOTRIVIALCUT } // end if d(v) > flow #endif } else { // cannot use the cut and it will compute another one unsuccess++; #ifdef VERBOSE printf("c fail thread=%d source=%ld sink=%d new_sink=%ld\n",id, source+1, Index(G[id]->sink, G[id])+1, tree[source]+1); #endif } } // end of omp critical } while(!done); } // end of gus main loop (for) // -- End of parallel for ------------------------------------------------ // begin: print the flow equivalent tree printf("c flow equivalent tree\n"); printf("p cut %ld %ld\n", n, n-1); for (step = 1; step < n; ++step) printf("a %ld %ld %lf\n", permut[step]+1, tree[permut[step]]+1, tree_weights[permut[step]]); // end: print tree double topenfinish = omp_get_wtime(); timer2(); printf("c timer: real: %.7lf user: %.7lf sys: %.7lf\n", topenfinish-topenstart, getUserTime(), getSystemTime()); printf("c success: %ld unsuccess: %ld\n",success, unsuccess); exit(0); } int RandomInteger (int low, int high) { int k; double d; d = (double) rand () / ((double) RAND_MAX + 1); k = d * (high - low + 1); return low + k; }
valid.res10.src.h
#pragma once #include "ukr.h" #include "omp.h" #include "transpose.h" #include "gen_ukr_A6B2gemm_1_512_7_7_256_3_3.h" #include "gen_ukr_A1B2gemm_1_512_7_7_256_3_3.h" void testrun(float* A ,float*B, float*C, float*oriB ){ int tid = omp_get_thread_num(); int Nx = 7; int Ny = 7; int Nh = 3; long long Astrides[6] = {0,2,4,6,8,10}; int b1 = 0; for (int fpck = (tid%1)*16; fpck < uNf; fpck+=1*16){ for(int cwh = (tid/1)*8; cwh < uNc*uNw*uNh/8*8; cwh+=8*1){ transpose8x8_avx(oriB+ (fpck+0)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 0, uNc*uNw*uNh, 16); transpose8x8_avx(oriB+ (fpck+8)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 8, uNc*uNw*uNh, 16); } } #pragma omp barrier// begin push button generated block for(int c5=0;c5<256+0;c5+=256) { for(int xy5=0;xy5<49+0;xy5+=49) { for(int f5=0;f5<512+0;f5+=512) { for(int xy4=xy5;xy4<min(49, 49+xy5);xy4+=49) { for(int f4=f5;f4<min(512, 512+f5);f4+=512) { for(int c4=c5;c4<min(256, 256+c5);c4+=256) { for(int c3=c4;c3<min(256, 256+c4);c3+=Tc1) { for(int f3=f4;f3<min(512, 512+f4);f3+=Tf2) { for(int xy3=xy4;xy3<min(49, 49+xy4);xy3+=Txy3) { for(int xy2=xy3;xy2<min(49, Txy3+xy3);xy2+=6) { for(int f2=f3;f2<min(512, Tf2+f3);f2+=16) { for(int c2=c3;c2<min(256, Tc1+c3);c2+=Tc1) { for(int c1=c2;c1<min(256, Tc1+c2);c1+=Tc1) { for(int xy1=xy2;xy1<min(49, 6+xy2);xy1+=6) { for(int f1=f2;f1<min(512, 16+f2);f1+=16) { int ctile=min(Tc1, 256-c1); int x1=xy1/7; int y1=xy1%7/1; int c1_1=c1/1; int c1_2=c1%1/1; int kf1_1=f1/16; int kf1_2=f1%16/1; int of1_1=f1/1; int of1_2=f1%1/1; int offsetA=0+b1*65536+c1_1*256+2*x1*16+2*y1*1+c1_2*1; int offsetB=0+kf1_1*36864+c1*144+0*48+0*16+kf1_2*1; int offsetC=0+b1*25088+of1_1*49+x1*7+y1*1+of1_2*1; if(7-y1>=6){ cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } else if(7*7-xy1>=6){ for(int sti=7-y1;sti<6;sti+=1) { Astrides[sti]+=18; } cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); for(int sti=7-y1;sti<6;sti+=1) { Astrides[sti]-=18; } } else{ cnn_ukr_float_scatter_1x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } } } } } } } } } } } } } } } } // end push button generated block }
par_csr_matvec.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "_hypre_parcsr_mv.h" #include "_hypre_utilities.hpp" //RL: TODO par_csr_matvec_device.c, include cuda there /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvec *--------------------------------------------------------------------------*/ // y = alpha*A*x + beta*b HYPRE_Int hypre_ParCSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *b, hypre_ParVector *y ) { hypre_ParCSRCommHandle **comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *b_local = hypre_ParVectorLocalVector(b); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); hypre_Vector *x_tmp; HYPRE_BigInt num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt num_cols = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt x_size = hypre_ParVectorGlobalSize(x); HYPRE_BigInt b_size = hypre_ParVectorGlobalSize(b); HYPRE_BigInt y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x_local); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, jv; HYPRE_Int vecstride = hypre_VectorVectorStride( x_local ); HYPRE_Int idxstride = hypre_VectorIndexStride( x_local ); HYPRE_Complex *x_tmp_data, **x_buf_data; HYPRE_Complex *x_local_data = hypre_VectorData(x_local); #if defined(HYPRE_USING_GPU) HYPRE_Int sync_stream; hypre_GetSyncCudaCompute(&sync_stream); hypre_SetSyncCudaCompute(0); #endif HYPRE_ANNOTATE_FUNC_BEGIN; /*--------------------------------------------------------------------- * Check for size compatibility. ParMatvec returns ierr = 11 if * length of X doesn't equal the number of columns of A, * ierr = 12 if the length of Y doesn't equal the number of rows * of A, and ierr = 13 if both are true. * * Because temporary vectors are often used in ParMatvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( idxstride > 0 ); if (num_cols != x_size) { ierr = 11; } if (num_rows != y_size || num_rows != b_size) { ierr = 12; } if (num_cols != x_size && (num_rows != y_size || num_rows != b_size)) { ierr = 13; } hypre_assert( hypre_VectorNumVectors(b_local) == num_vectors ); hypre_assert( hypre_VectorNumVectors(y_local) == num_vectors ); if ( num_vectors == 1 ) { x_tmp = hypre_SeqVectorCreate( num_cols_offd ); } else { hypre_assert( num_vectors > 1 ); x_tmp = hypre_SeqMultiVectorCreate( num_cols_offd, num_vectors ); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); hypre_assert( num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, hypre_ParCSRCommPkgNumRecvs(comm_pkg)) ); hypre_assert( hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0) == 0 ); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif HYPRE_Int use_persistent_comm = 0; #ifdef HYPRE_USING_PERSISTENT_COMM use_persistent_comm = num_vectors == 1; // JSP TODO: we can use persistent communication for multi-vectors, // but then we need different communication handles for different // num_vectors. hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg); #endif } else { comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*, num_vectors, HYPRE_MEMORY_HOST); } /* x_tmp */ #if defined(HYPRE_USING_GPU) /* for GPU and single vector, alloc persistent memory for x_tmp (in comm_pkg) and reuse */ if (num_vectors == 1) { if (!hypre_ParCSRCommPkgTmpData(comm_pkg)) { #if 1 hypre_ParCSRCommPkgTmpData(comm_pkg) = hypre_TAlloc(HYPRE_Complex, num_cols_offd, HYPRE_MEMORY_DEVICE); #else hypre_ParCSRCommPkgTmpData(comm_pkg) = _hypre_TAlloc(HYPRE_Complex, num_cols_offd, hypre_MEMORY_DEVICE); #endif } hypre_VectorData(x_tmp) = hypre_ParCSRCommPkgTmpData(comm_pkg); hypre_SeqVectorSetDataOwner(x_tmp, 0); } #else if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_VectorData(x_tmp) = (HYPRE_Complex *) hypre_ParCSRCommHandleRecvDataBuffer( persistent_comm_handle); hypre_SeqVectorSetDataOwner(x_tmp, 0); #endif } #endif hypre_SeqVectorInitialize_v2(x_tmp, HYPRE_MEMORY_DEVICE); x_tmp_data = hypre_VectorData(x_tmp); /* x_buff_data */ x_buf_data = hypre_CTAlloc(HYPRE_Complex*, num_vectors, HYPRE_MEMORY_HOST); for (jv = 0; jv < num_vectors; ++jv) { #if defined(HYPRE_USING_GPU) if (jv == 0) { if (!hypre_ParCSRCommPkgBufData(comm_pkg)) { #if 1 hypre_ParCSRCommPkgBufData(comm_pkg) = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_DEVICE); #else hypre_ParCSRCommPkgBufData(comm_pkg) = _hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), hypre_MEMORY_DEVICE); #endif } x_buf_data[0] = hypre_ParCSRCommPkgBufData(comm_pkg); continue; } #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM x_buf_data[0] = (HYPRE_Complex *) hypre_ParCSRCommHandleSendDataBuffer(persistent_comm_handle); continue; #endif } x_buf_data[jv] = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_DEVICE); } /* The assert is because the following loop only works for 'column' storage of a multivector. This needs to be fixed to work more generally, at least for 'row' storage. This in turn, means either change CommPkg so num_sends is no.zones*no.vectors (not no.zones) or, less dangerously, put a stride in the logic of CommHandleCreate (stride either from a new arg or a new variable inside CommPkg). Or put the num_vector iteration inside CommHandleCreate (perhaps a new multivector variant of it). */ hypre_assert( idxstride == 1 ); //hypre_SeqVectorPrefetch(x_local, HYPRE_MEMORY_DEVICE); /* send_map_elmts on device */ hypre_ParCSRCommPkgCopySendMapElmtsToDevice(comm_pkg); for (jv = 0; jv < num_vectors; ++jv) { HYPRE_Complex *send_data = (HYPRE_Complex *) x_buf_data[jv]; HYPRE_Complex *locl_data = x_local_data + jv * vecstride; /* if on device, no need to Sync: send_data is on device memory */ #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) /* pack send data on device */ HYPRE_THRUST_CALL( gather, hypre_ParCSRCommPkgDeviceSendMapElmts(comm_pkg), hypre_ParCSRCommPkgDeviceSendMapElmts(comm_pkg) + hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), locl_data, send_data ); #elif defined(HYPRE_USING_DEVICE_OPENMP) /* pack send data on device */ HYPRE_Int i; HYPRE_Int *device_send_map_elmts = hypre_ParCSRCommPkgDeviceSendMapElmts(comm_pkg); HYPRE_Int start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); #pragma omp target teams distribute parallel for private(i) is_device_ptr(send_data, locl_data, device_send_map_elmts) for (i = start; i < end; i++) { send_data[i] = locl_data[device_send_map_elmts[i]]; } #else HYPRE_Int i; /* pack send data on host */ #if defined(HYPRE_USING_OPENMP) #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); i < hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); i ++) { send_data[i] = locl_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i)]; } #endif } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif /* nonblocking communication starts */ if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle, HYPRE_MEMORY_DEVICE, x_buf_data[0]); #endif } else { for ( jv = 0; jv < num_vectors; ++jv ) { comm_handle[jv] = hypre_ParCSRCommHandleCreate_v2( 1, comm_pkg, HYPRE_MEMORY_DEVICE, x_buf_data[jv], HYPRE_MEMORY_DEVICE, &x_tmp_data[jv * num_cols_offd] ); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif /* overlapped local computation */ hypre_CSRMatrixMatvecOutOfPlace( alpha, diag, x_local, beta, b_local, y_local, 0 ); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif /* nonblocking communication ends */ if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle, HYPRE_MEMORY_DEVICE, x_tmp_data); #endif } else { for ( jv = 0; jv < num_vectors; ++jv ) { hypre_ParCSRCommHandleDestroy(comm_handle[jv]); comm_handle[jv] = NULL; } hypre_TFree(comm_handle, HYPRE_MEMORY_HOST); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif /* computation offd part */ if (num_cols_offd) { hypre_CSRMatrixMatvec( alpha, offd, x_tmp, 1.0, y_local ); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif hypre_SeqVectorDestroy(x_tmp); x_tmp = NULL; if (!use_persistent_comm) { for ( jv = 0; jv < num_vectors; ++jv ) { #if defined(HYPRE_USING_GPU) if (jv == 0) { continue; } #endif hypre_TFree(x_buf_data[jv], HYPRE_MEMORY_DEVICE); } hypre_TFree(x_buf_data, HYPRE_MEMORY_HOST); } #if defined(HYPRE_USING_GPU) hypre_SetSyncCudaCompute(sync_stream); hypre_SyncCudaComputeStream(hypre_handle()); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif HYPRE_ANNOTATE_FUNC_END; return ierr; } HYPRE_Int hypre_ParCSRMatrixMatvec( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y ) { return hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvecT * * Performs y <- alpha * A^T * x + beta * y * *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixMatvecT( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y ) { hypre_ParCSRCommHandle **comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *diagT = hypre_ParCSRMatrixDiagT(A); hypre_CSRMatrix *offdT = hypre_ParCSRMatrixOffdT(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); hypre_Vector *y_tmp; HYPRE_BigInt num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt num_cols = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt x_size = hypre_ParVectorGlobalSize(x); HYPRE_BigInt y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(y_local); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, jv; HYPRE_Int vecstride = hypre_VectorVectorStride(y_local); HYPRE_Int idxstride = hypre_VectorIndexStride(y_local); HYPRE_Complex *y_tmp_data, **y_buf_data; HYPRE_Complex *y_local_data = hypre_VectorData(y_local); #if defined(HYPRE_USING_GPU) HYPRE_Int sync_stream; hypre_GetSyncCudaCompute(&sync_stream); hypre_SetSyncCudaCompute(0); #endif HYPRE_ANNOTATE_FUNC_BEGIN; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_rows != x_size) { ierr = 1; } if (num_cols != y_size) { ierr = 2; } if (num_rows != x_size && num_cols != y_size) { ierr = 3; } hypre_assert( hypre_VectorNumVectors(x_local) == num_vectors ); hypre_assert( hypre_VectorNumVectors(y_local) == num_vectors ); if ( num_vectors == 1 ) { y_tmp = hypre_SeqVectorCreate(num_cols_offd); } else { hypre_assert( num_vectors > 1 ); y_tmp = hypre_SeqMultiVectorCreate(num_cols_offd, num_vectors); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); hypre_assert( num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, hypre_ParCSRCommPkgNumRecvs(comm_pkg)) ); hypre_assert( hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0) == 0 ); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif HYPRE_Int use_persistent_comm = 0; #ifdef HYPRE_USING_PERSISTENT_COMM use_persistent_comm = num_vectors == 1; // JSP TODO: we can use persistent communication for multi-vectors, // but then we need different communication handles for different // num_vectors. hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(2, comm_pkg); #endif } else { comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*, num_vectors, HYPRE_MEMORY_HOST); } /* y_tmp */ #if defined(HYPRE_USING_GPU) /* for GPU and single vector, alloc persistent memory for y_tmp (in comm_pkg) and reuse */ if (num_vectors == 1) { if (!hypre_ParCSRCommPkgTmpData(comm_pkg)) { #if 1 hypre_ParCSRCommPkgTmpData(comm_pkg) = hypre_TAlloc(HYPRE_Complex, num_cols_offd, HYPRE_MEMORY_DEVICE); #else hypre_ParCSRCommPkgTmpData(comm_pkg) = _hypre_TAlloc(HYPRE_Complex, num_cols_offd, hypre_MEMORY_DEVICE); #endif } hypre_VectorData(y_tmp) = hypre_ParCSRCommPkgTmpData(comm_pkg); hypre_SeqVectorSetDataOwner(y_tmp, 0); } #else if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_VectorData(y_tmp) = (HYPRE_Complex *) hypre_ParCSRCommHandleSendDataBuffer( persistent_comm_handle); hypre_SeqVectorSetDataOwner(y_tmp, 0); #endif } #endif hypre_SeqVectorInitialize_v2(y_tmp, HYPRE_MEMORY_DEVICE); y_tmp_data = hypre_VectorData(y_tmp); /* y_buf_data */ y_buf_data = hypre_CTAlloc(HYPRE_Complex*, num_vectors, HYPRE_MEMORY_HOST); for (jv = 0; jv < num_vectors; ++jv) { #if defined(HYPRE_USING_GPU) if (jv == 0) { if (!hypre_ParCSRCommPkgBufData(comm_pkg)) { #if 1 hypre_ParCSRCommPkgBufData(comm_pkg) = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_DEVICE); #else hypre_ParCSRCommPkgBufData(comm_pkg) = _hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), hypre_MEMORY_DEVICE); #endif } y_buf_data[0] = hypre_ParCSRCommPkgBufData(comm_pkg); continue; } #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM y_buf_data[0] = (HYPRE_Complex *) hypre_ParCSRCommHandleRecvDataBuffer(persistent_comm_handle); continue; #endif } y_buf_data[jv] = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_DEVICE); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif if (num_cols_offd) { if (offdT) { // offdT is optional. Used only if it's present hypre_CSRMatrixMatvec(alpha, offdT, x_local, 0.0, y_tmp); } else { hypre_CSRMatrixMatvecT(alpha, offd, x_local, 0.0, y_tmp); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle, HYPRE_MEMORY_DEVICE, y_tmp_data); #endif } else { for ( jv = 0; jv < num_vectors; ++jv ) { /* this is where we assume multivectors are 'column' storage */ comm_handle[jv] = hypre_ParCSRCommHandleCreate_v2( 2, comm_pkg, HYPRE_MEMORY_DEVICE, &y_tmp_data[jv * num_cols_offd], HYPRE_MEMORY_DEVICE, y_buf_data[jv] ); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif /* overlapped local computation */ if (diagT) { // diagT is optional. Used only if it's present. hypre_CSRMatrixMatvec(alpha, diagT, x_local, beta, y_local); } else { hypre_CSRMatrixMatvecT(alpha, diag, x_local, beta, y_local); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif /* nonblocking communication ends */ if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle, HYPRE_MEMORY_DEVICE, y_buf_data[0]); #endif } else { for ( jv = 0; jv < num_vectors; ++jv ) { hypre_ParCSRCommHandleDestroy(comm_handle[jv]); comm_handle[jv] = NULL; } hypre_TFree(comm_handle, HYPRE_MEMORY_HOST); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif /* The assert is because the following loop only works for 'column' storage of a multivector. This needs to be fixed to work more generally, at least for 'row' storage. This in turn, means either change CommPkg so num_sends is no.zones*no.vectors (not no.zones) or, less dangerously, put a stride in the logic of CommHandleCreate (stride either from a new arg or a new variable inside CommPkg). Or put the num_vector iteration inside CommHandleCreate (perhaps a new multivector variant of it). */ hypre_assert( idxstride == 1 ); /* send_map_elmts on device */ hypre_ParCSRCommPkgCopySendMapElmtsToDevice(comm_pkg); for (jv = 0; jv < num_vectors; ++jv) { HYPRE_Complex *recv_data = (HYPRE_Complex *) y_buf_data[jv]; HYPRE_Complex *locl_data = y_local_data + jv * vecstride; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) /* unpack recv data on device */ if (!hypre_ParCSRCommPkgWorkSpace(comm_pkg)) { hypre_ParCSRCommPkgWorkSpace(comm_pkg) = hypre_TAlloc( char, (2 * sizeof(HYPRE_Int) + sizeof(HYPRE_Real)) * hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_DEVICE ); } hypreDevice_GenScatterAdd(locl_data, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), hypre_ParCSRCommPkgDeviceSendMapElmts(comm_pkg), recv_data, hypre_ParCSRCommPkgWorkSpace(comm_pkg)); #elif defined(HYPRE_USING_DEVICE_OPENMP) HYPRE_Int i, j; /* unpack recv data on device */ for (i = 0; i < num_sends; i++) { HYPRE_Int *device_send_map_elmts = hypre_ParCSRCommPkgDeviceSendMapElmts(comm_pkg); HYPRE_Int start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); #pragma omp target teams distribute parallel for private(j) is_device_ptr(recv_data, locl_data, device_send_map_elmts) for (j = start; j < end; j++) { locl_data[device_send_map_elmts[j]] += recv_data[j]; } } #else HYPRE_Int i; /* unpack recv data on host, TODO OMP? */ for (i = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); i < hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); i ++) { locl_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i)] += recv_data[i]; } #endif } hypre_SeqVectorDestroy(y_tmp); y_tmp = NULL; if (!use_persistent_comm) { for ( jv = 0; jv < num_vectors; ++jv ) { #if defined(HYPRE_USING_GPU) if (jv == 0) { continue; } #endif hypre_TFree(y_buf_data[jv], HYPRE_MEMORY_DEVICE); } hypre_TFree(y_buf_data, HYPRE_MEMORY_HOST); } #if defined(HYPRE_USING_GPU) hypre_SetSyncCudaCompute(sync_stream); hypre_SyncCudaComputeStream(hypre_handle()); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif HYPRE_ANNOTATE_FUNC_END; return ierr; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvec_FF *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixMatvec_FF( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y, HYPRE_Int *CF_marker, HYPRE_Int fpt ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommHandle *comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); HYPRE_BigInt num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt num_cols = hypre_ParCSRMatrixGlobalNumCols(A); hypre_Vector *x_tmp; HYPRE_BigInt x_size = hypre_ParVectorGlobalSize(x); HYPRE_BigInt y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, i, j, index, start, num_procs; HYPRE_Int *int_buf_data = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Complex *x_tmp_data = NULL; HYPRE_Complex *x_buf_data = NULL; HYPRE_Complex *x_local_data = hypre_VectorData(x_local); /*--------------------------------------------------------------------- * Check for size compatibility. ParMatvec returns ierr = 11 if * length of X doesn't equal the number of columns of A, * ierr = 12 if the length of Y doesn't equal the number of rows * of A, and ierr = 13 if both are true. * * Because temporary vectors are often used in ParMatvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); if (num_cols != x_size) { ierr = 11; } if (num_rows != y_size) { ierr = 12; } if (num_cols != x_size && num_rows != y_size) { ierr = 13; } if (num_procs > 1) { if (num_cols_offd) { x_tmp = hypre_SeqVectorCreate( num_cols_offd ); hypre_SeqVectorInitialize(x_tmp); x_tmp_data = hypre_VectorData(x_tmp); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_sends) x_buf_data = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends), HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) x_buf_data[index++] = x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate ( 1, comm_pkg, x_buf_data, x_tmp_data ); } hypre_CSRMatrixMatvec_FF( alpha, diag, x_local, beta, y_local, CF_marker, CF_marker, fpt); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (num_sends) int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends), HYPRE_MEMORY_HOST); if (num_cols_offd) { CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd ); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (num_cols_offd) hypre_CSRMatrixMatvec_FF( alpha, offd, x_tmp, 1.0, y_local, CF_marker, CF_marker_offd, fpt); hypre_SeqVectorDestroy(x_tmp); x_tmp = NULL; hypre_TFree(x_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); } return ierr; }
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.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/configure.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ #if MAGICKCORE_ZERO_CONFIGURATION_SUPPORT #include "MagickCore/threshold-map.h" #else static const char *const BuiltinMap= "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; #endif /* Forward declarations. */ static ThresholdMap *GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image,const size_t width, % const size_t height,const double bias,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o bias: the mean bias. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if ((width == 0) || (height == 0)) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; const Quantum *magick_restrict p, *magick_restrict pixels; Quantum *magick_restrict q; ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically performs image thresholding % dependent on which method you specify. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const double *histogram) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; 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++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(histogram); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property,exception); if (IsStringTrue(GetImageArtifact(image,"auto-threshold:verbose")) != MagickFalse) (void) FormatLocaleFile(stdout,"%.*g%%\n",GetMagickPrecision(),threshold); return(BilevelImage(image,QuantumRange*threshold/100.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImage method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % % o exception: return any errors or warnings in this structure. % % Aside: You can get the same results as operator using LevelImages() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); /* Bilevel threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < GetPixelInfoChannel(&threshold,channel)) q[i]=(Quantum) 0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImage method is: % % MagickBooleanType ClampImage(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 ClampImage(Image *image,ExceptionInfo *exception) { #define ClampImageTag "Clamp/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { ssize_t i; PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) ClampPixel(q->red); q->green=(double) ClampPixel(q->green); q->blue=(double) ClampPixel(q->blue); q->alpha=(double) ClampPixel(q->alpha); q++; } return(SyncImage(image,exception)); } /* Clamp image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampPixel((MagickRealType) q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClampImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorThresholdImage() forces all pixels in the color range to white % otherwise black. % % The format of the ColorThresholdImage method is: % % MagickBooleanType ColorThresholdImage(Image *image, % const PixelInfo *start_color,const PixelInfo *stop_color, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o start_color, stop_color: define the start and stop color range. Any % pixel within the range returns white otherwise black. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorThresholdImage(Image *image, const PixelInfo *start_color,const PixelInfo *stop_color, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; const char *artifact; IlluminantType illuminant = D65Illuminant; MagickBooleanType status; MagickOffsetType progress; PixelInfo start, stop; ssize_t y; /* Color threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=AcquireImageColormap(image,2,exception); if (status == MagickFalse) return(status); artifact=GetImageArtifact(image,"color:illuminant"); if (artifact != (const char *) NULL) { illuminant=(IlluminantType) ParseCommandOption(MagickIlluminantOptions, MagickFalse,artifact); if ((ssize_t) illuminant < 0) illuminant=UndefinedIlluminant; } start=(*start_color); stop=(*stop_color); switch (image->colorspace) { case HCLColorspace: { ConvertRGBToHCL(start_color->red,start_color->green,start_color->blue, &start.red,&start.green,&start.blue); ConvertRGBToHCL(stop_color->red,stop_color->green,stop_color->blue, &stop.red,&stop.green,&stop.blue); break; } case HSBColorspace: { ConvertRGBToHSB(start_color->red,start_color->green,start_color->blue, &start.red,&start.green,&start.blue); ConvertRGBToHSB(stop_color->red,stop_color->green,stop_color->blue, &stop.red,&stop.green,&stop.blue); break; } case HSLColorspace: { ConvertRGBToHSL(start_color->red,start_color->green,start_color->blue, &start.red,&start.green,&start.blue); ConvertRGBToHSL(stop_color->red,stop_color->green,stop_color->blue, &stop.red,&stop.green,&stop.blue); break; } case HSVColorspace: { ConvertRGBToHSV(start_color->red,start_color->green,start_color->blue, &start.red,&start.green,&start.blue); ConvertRGBToHSV(stop_color->red,stop_color->green,stop_color->blue, &stop.red,&stop.green,&stop.blue); break; } case HWBColorspace: { ConvertRGBToHWB(start_color->red,start_color->green,start_color->blue, &start.red,&start.green,&start.blue); ConvertRGBToHWB(stop_color->red,stop_color->green,stop_color->blue, &stop.red,&stop.green,&stop.blue); break; } case LabColorspace: { ConvertRGBToLab(start_color->red,start_color->green,start_color->blue, illuminant,&start.red,&start.green,&start.blue); ConvertRGBToLab(stop_color->red,stop_color->green,stop_color->blue, illuminant,&stop.red,&stop.green,&stop.blue); break; } default: { start.red*=QuantumScale; start.green*=QuantumScale; start.blue*=QuantumScale; stop.red*=QuantumScale; stop.green*=QuantumScale; stop.blue*=QuantumScale; break; } } start.red*=QuantumRange; start.green*=QuantumRange; start.blue*=QuantumRange; stop.red*=QuantumRange; stop.green*=QuantumRange; stop.blue*=QuantumRange; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickBooleanType foreground = MagickTrue; ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((q[i] < GetPixelInfoChannel(&start,channel)) || (q[i] > GetPixelInfoChannel(&stop,channel))) foreground=MagickFalse; } SetPixelIndex(image,(Quantum) (foreground != MagickFalse ? 1 : 0),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 atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->colorspace=sRGBColorspace; return(SyncImage(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() loads and searches one or more threshold map files for the % map matching the given name or alias. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { ThresholdMap *map; map=GetThresholdMapFile(BuiltinMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); #if !MAGICKCORE_ZERO_CONFIGURATION_SUPPORT { const StringInfo *option; LinkedListInfo *options; options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); } #endif return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename, const char *map_id,ExceptionInfo *exception) { char *p; const char *attribute, *content; double value; ssize_t i; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); map=(ThresholdMap *) NULL; thresholds=NewXMLTree(xml,exception); if (thresholds == (XMLTreeInfo *) NULL) return(map); for (threshold=GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { attribute=GetXMLTreeAttribute(threshold,"map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold,"alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map)); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); for (i=0; i < (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { const char *alias, *content, *map; XMLTreeInfo *description, *threshold, *thresholds; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); threshold=GetXMLTreeChild(thresholds,"threshold"); for ( ; threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { map=GetXMLTreeAttribute(threshold,"map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias=GetXMLTreeAttribute(threshold,"alias"); description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels to dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with an ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; char token[MagickPathExtent]; const char *p; double levels[CompositePixelChannel]; MagickBooleanType status; MagickOffsetType progress; ssize_t i, y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (threshold_map == (const char *) NULL) return(MagickTrue); p=(char *) threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MagickPathExtent-1)) break; token[p-threshold_map]=(*p); p++; } token[p-threshold_map]='\0'; map=GetThresholdMap(token,exception); if (map == (ThresholdMap *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } for (i=0; i < MaxPixelChannels; i++) levels[i]=2.0; p=strchr((char *) threshold_map,','); if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0)) { (void) GetNextToken(p,&p,MagickPathExtent,token); for (i=0; (i < MaxPixelChannels); i++) levels[i]=StringToDouble(token,(char **) NULL); for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); levels[i]=StringToDouble(token,(char **) NULL); } } for (i=0; i < MaxPixelChannels; i++) if (fabs(levels[i]) >= 1) levels[i]-=1.0; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j, n; n=0; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { ssize_t level, threshold; PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (fabs(levels[n]) < MagickEpsilon) { n++; continue; } threshold=(ssize_t) (QuantumScale*q[j]*(levels[n]*(map->divisor-1)+1)); level=threshold/(map->divisor-1); threshold-=level*(map->divisor-1); q[j]=ClampToQuantum((double) (level+(threshold >= map->levels[(x % map->width)+map->width*(y % map->height)]))* QuantumRange/levels[n]); n++; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,DitherImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImage method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon,ExceptionInfo *exception) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { ssize_t i; PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red), epsilon); q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green), epsilon); q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue), epsilon); q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha), epsilon); q++; } return(SyncImage(image,exception)); } /* Perceptible image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PerceptibleThreshold(q[i],epsilon); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,PerceptibleImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImage(Image *image, % const char *thresholds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low,high: Specify the high and low thresholds. These values range from % 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const double min_threshold, const double max_threshold,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Random threshold image. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoTLS(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; 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++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] < min_threshold) threshold=min_threshold; else if ((double) q[i] > max_threshold) threshold=max_threshold; else threshold=(double) (QuantumRange* GetPseudoRandomValue(random_info[id])); q[i]=(double) q[i] <= threshold ? 0 : QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoTLS(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n g e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RangeThresholdImage() applies soft and hard thresholding. % % The format of the RangeThresholdImage method is: % % MagickBooleanType RangeThresholdImage(Image *image, % const double low_black,const double low_white,const double high_white, % const double high_black,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low_black: Define the minimum black threshold value. % % o low_white: Define the minimum white threshold value. % % o high_white: Define the maximum white threshold value. % % o high_black: Define the maximum black threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RangeThresholdImage(Image *image, const double low_black,const double low_white,const double high_white, const double high_black,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Range threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < low_black) q[i]=(Quantum) 0; else if ((pixel >= low_black) && (pixel < low_white)) q[i]=ClampToQuantum(QuantumRange* PerceptibleReciprocal(low_white-low_black)*(pixel-low_black)); else if ((pixel >= low_white) && (pixel <= high_white)) q[i]=QuantumRange; else if ((pixel > high_white) && (pixel <= high_black)) q[i]=ClampToQuantum(QuantumRange*PerceptibleReciprocal( high_black-high_white)*(high_black-pixel)); else if (pixel > high_black) q[i]=(Quantum) 0; else q[i]=(Quantum) 0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel > GetPixelInfoChannel(&threshold,channel)) q[i]=QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
tm_efficientdet.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. */ /* * Author: zylo117 * * original model: https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch */ #include <stdlib.h> #include <stdio.h> #include "common.h" #include "tengine/c_api.h" #include "tengine_operations.h" #define DEFAULT_IMG_H 512 #define DEFAULT_IMG_W 512 #define DEFAULT_SCALE1 0.017124754f #define DEFAULT_SCALE2 0.017507003f #define DEFAULT_SCALE3 0.017429194f #define DEFAULT_MEAN1 123.675 #define DEFAULT_MEAN2 116.280 #define DEFAULT_MEAN3 103.530 #define DEFAULT_LOOP_COUNT 1 #define DEFAULT_THREAD_COUNT 1 #define DEFAULT_CPU_AFFINITY 255 typedef struct Box { int x0; int y0; int x1; int y1; int class_idx; float score; } Box_t; void qsort_descent_inplace(Box_t* boxes, int left, int right) { int i = left; int j = right; float p = boxes[(left + right) / 2].score; while (i <= j) { while (boxes[i].score > p) i++; while (boxes[j].score < p) j--; if (i <= j) { // swap Box_t tmp = boxes[i]; boxes[i] = boxes[j]; boxes[j] = tmp; i++; j--; } } #pragma omp parallel sections { #pragma omp section { if (left < j) qsort_descent_inplace(boxes, left, j); } #pragma omp section { if (i < right) qsort_descent_inplace(boxes, i, right); } } } int nms(const Box_t* boxes, const int num_boxes, int* suppressed, float nms_threshold) { int num_outputs = num_boxes; float* areas = malloc(num_boxes * sizeof(float)); for (int i = 0; i < num_boxes; i++) { areas[i] = (float) ((boxes[i].x1 - boxes[i].x0) * (boxes[i].y1 - boxes[i].y0)); } for (int i = 0; i < num_boxes; i++) { const Box_t a = boxes[i]; if (suppressed[i] == 1) continue; for (int j = i + 1; j < num_boxes; j++) { const Box_t b = boxes[j]; if (suppressed[j] == 1) continue; // iou float intersection = fmaxf(fminf(a.x1, b.x1) - fmaxf(a.x0, b.x0), 0) * fmaxf(fminf(a.y1, b.y1) - fmaxf(a.y0, b.y0), 0); float total_area = (a.x1 - a.x0) * (a.y1 - a.y0) + (b.x1 - b.x0) * (b.y1 - b.y0) - intersection; float iou = fmaxf(intersection / total_area, 0); if (iou > nms_threshold){ suppressed[j] = 1; num_outputs--; } else{ suppressed[j] = 0; } } } free(areas); return num_outputs; } float* arange(int start, int end, float stride) { int length = (int) ((float) ceilf((float) (end - start) / stride)); float* result = malloc(length * sizeof(float)); result[0] = (float) start; for (int i = 1; i < length; i++) { result[i] = result[i - 1] + stride; } return result; } void tile(const float* arr, int arr_length, int times, float offset, float* result, int arr_starts_from, int arr_stride) { int length = arr_length * times; if (result == NULL) { result = malloc(length * sizeof(float)); arr_starts_from = 0; } for (int i = 0, j = 0; i < length; i++, j += arr_stride) { result[j + arr_starts_from] = arr[i % arr_length] + offset; } } void repeat(const float* arr, int arr_length, int times, float offset, float* result, int arr_starts_from, int arr_stride) { int length = arr_length * times; if (result == NULL) { result = malloc(length * sizeof(float)); arr_starts_from = 0; } for (int i = 0, j = 0; i < length; i++, j += arr_stride) { result[j + arr_starts_from] = arr[i / times] + offset; } } int argmax(const float* arr, int arr_starts_from, int arr_length) { float max_value = arr[arr_starts_from]; int max_idx = 0; for (int i = 1; i < arr_length; i++) { float this_value = arr[arr_starts_from + i]; if (this_value > max_value) { max_value = this_value; max_idx = i; } } return max_idx; } int tengine_detect(const char* model_file, const char* image_file, int img_h, int img_w, const float* mean, const float* scale, int loop_count, int num_thread, int affinity) { /* setup network */ const char* CLASSES_NAME[] = {"person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "", "backpack", "umbrella", "", "", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "", "dining table", "", "", "toilet", "", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"}; int PYRAMID_LEVELS[] = {3, 4, 5, 6, 7}; int STRIDES[] = {8, 16, 32, 64, 128}; float SCALES[] = { (float) pow(2, 0.), (float) pow(2, 1. / 3.), (float) pow(2, 2. / 3.), }; float RATIOS_X[] = {1.f, 1.4f, 0.7f}; float RATIOS_Y[] = {1.f, 0.7f, 1.4f}; float ANCHOR_SCALE = 4.f; float CONFIDENCE_THRESHOLD = 0.2f; float NMS_THRESHOLD = 0.2f; int num_levels = sizeof(PYRAMID_LEVELS) / sizeof(int); int num_scales = sizeof(SCALES) / sizeof(float); int num_ratios = sizeof(RATIOS_X) / sizeof(float); /* set runtime options */ struct options opt; opt.num_thread = num_thread; opt.cluster = TENGINE_CLUSTER_ALL; opt.precision = TENGINE_MODE_FP32; opt.affinity = affinity; /* inital tengine */ if (init_tengine() != 0) { fprintf(stderr, "Initial tengine failed.\n"); return -1; } fprintf(stderr, "tengine-lite library version: %s\n", get_tengine_version()); /* create graph, load tengine model xxx.tmfile */ graph_t graph = create_graph(NULL, "tengine", model_file); if (NULL == graph) { fprintf(stderr, "Create graph failed.\n"); return -1; } /* set the shape, data buffer of input_tensor of the graph */ int img_size = img_h * img_w * 3; int dims[] = {1, 3, img_h, img_w}; // nchw float* input_data = ( float* )malloc(img_size * sizeof(float)); tensor_t input_tensor = get_graph_input_tensor(graph, 0, 0); if (input_tensor == NULL) { fprintf(stderr, "Get input tensor failed\n"); return -1; } if (set_tensor_shape(input_tensor, dims, 4) < 0) { fprintf(stderr, "Set input tensor shape failed\n"); return -1; } if (set_tensor_buffer(input_tensor, input_data, img_size * 4) < 0) { fprintf(stderr, "Set input tensor buffer failed\n"); return -1; } /* prerun graph, set work options(num_thread, cluster, precision) */ if (prerun_graph_multithread(graph, opt) < 0) { fprintf(stderr, "Prerun multithread graph failed.\n"); return -1; } /* prepare process input data, set the data mem to input tensor */ float means[3] = {mean[0], mean[1], mean[2]}; float scales[3] = {scale[0], scale[1], scale[2]}; image im = imread(image_file); image im_vis = copy_image(im); im = imread2caffe(im, img_w, img_h, means, scales); int raw_h = im.h; int raw_w = im.w; int resized_h, resized_w; float resize_scale; image resImg; if (raw_h > raw_w){ resized_h = img_h; resized_w = (int) ((float) img_h / raw_h * raw_w); resImg = resize_image(im, resized_w, img_h); resize_scale = (float) raw_h / img_h; } else{ resized_w = img_w; resized_h = (int) ((float) img_w / raw_w * raw_h); resImg = resize_image(im, img_w, resized_h); resize_scale = (float) raw_w / img_w; } free_image(im); image paddedImg = copyMaker(resImg, 0, img_h - resized_h, 0, img_w - resized_w, 0); free_image(resImg); memcpy(input_data, paddedImg.data, sizeof(float) * paddedImg.c * img_w * img_h); free_image(paddedImg); /* run graph */ double min_time = DBL_MAX; double max_time = DBL_MIN; double total_time = 0.; for (int i = 0; i < loop_count; i++) { double start = get_current_time(); if (run_graph(graph, 1) < 0) { fprintf(stderr, "Run graph failed\n"); return -1; } double end = get_current_time(); double cur = end - start; total_time += cur; if (min_time > cur) min_time = cur; if (max_time < cur) max_time = cur; } fprintf(stderr, "\nmodel file : %s\n", model_file); fprintf(stderr, "image file : %s\n", image_file); fprintf(stderr, "img_h, img_w, scale[3], mean[3] : %d %d , %.3f %.3f %.3f, %.1f %.1f %.1f\n", img_h, img_w, scale[0], scale[1], scale[2], mean[0], mean[1], mean[2]); fprintf(stderr, "Repeat %d times, thread %d, avg time %.2f ms, max_time %.2f ms, min_time %.2f ms\n", loop_count, num_thread, total_time / loop_count, max_time, min_time); fprintf(stderr, "--------------------------------------\n"); /* get the result of classification */ tensor_t output_tensor_regression = get_graph_output_tensor(graph, 0, 0); float* output_data_regression = ( float* )get_tensor_buffer(output_tensor_regression); int num_anchors = get_tensor_buffer_size(output_tensor_regression) / sizeof(float) / 4; tensor_t output_tensor_classification = get_graph_output_tensor(graph, 1, 0); float* output_data_classification = ( float* )get_tensor_buffer(output_tensor_classification); int num_classes = get_tensor_buffer_size(output_tensor_classification) / sizeof(float) / num_anchors; // postprocess // generate anchors float* anchors_x0 = malloc(num_anchors * sizeof(float)); float* anchors_x1 = malloc(num_anchors * sizeof(float)); float* anchors_y0 = malloc(num_anchors * sizeof(float)); float* anchors_y1 = malloc(num_anchors * sizeof(float)); int anchor_idx = 0; for (int stride_idx = 0; stride_idx < num_levels; stride_idx++) { int stride = STRIDES[stride_idx]; float arange_stride = powf(2, (float) PYRAMID_LEVELS[stride_idx]); int length_x = (int) ceilf(((float) img_w - (float) stride / 2) / (float) arange_stride); int length_y = (int) ceilf(((float) img_h - (float) stride / 2) / (float) arange_stride); float* x = arange(stride / 2, img_w, arange_stride); float* y = arange(stride / 2, img_h, arange_stride); int start_idx = anchor_idx; int num_anchor_types = num_scales * num_ratios; for (int i = 0; i < num_scales; i++) { float anchor_scale = SCALES[i]; float base_anchor_size = ANCHOR_SCALE * (float) stride * anchor_scale; for (int j = 0; j < num_ratios; j++) { float ratio_x = RATIOS_X[j]; float ratio_y = RATIOS_Y[j]; float anchor_size_x_2 = base_anchor_size * ratio_x / 2.f; float anchor_size_y_2 = base_anchor_size * ratio_y / 2.f; tile(x, length_x, length_y, -anchor_size_x_2, anchors_x0, start_idx + i * num_scales + j, num_anchor_types); repeat(y, length_y, length_x, -anchor_size_y_2, anchors_y0, start_idx + i * num_scales + j, num_anchor_types); tile(x, length_x, length_y, anchor_size_x_2, anchors_x1, start_idx + i * num_scales + j, num_anchor_types); repeat(y, length_y, length_x, anchor_size_y_2, anchors_y1, start_idx + i * num_scales + j, num_anchor_types); anchor_idx += (length_x * length_y); } } free(x); free(y); } // loop over anchors Box_t* proposals = malloc(sizeof(Box_t) * num_anchors); int num_proposals_over_threshold = 0; #pragma omp parallel for num_threads(opt.num_thread) for (int i = 0; i < num_anchors; i++) { // loop over anchors // confidence int max_idx = argmax(output_data_classification, i * num_classes, num_classes); float max_score = output_data_classification[i * num_classes + max_idx]; if (isinf(max_score) || max_score < CONFIDENCE_THRESHOLD){ proposals[i].class_idx = -1; continue; } proposals[i].class_idx = max_idx; proposals[i].score = max_score; // box transform float ha = anchors_y1[i] - anchors_y0[i]; float wa = anchors_x1[i] - anchors_x0[i]; float y_center_a = (anchors_y1[i] + anchors_y0[i]) / 2; float x_center_a = (anchors_x1[i] + anchors_x0[i]) / 2; float w = expf(output_data_regression[i * 4 + 3]) * wa; float h = expf(output_data_regression[i * 4 + 2]) * ha; float y_center = output_data_regression[i * 4] * ha + y_center_a; float x_center = output_data_regression[i * 4 + 1] * wa + x_center_a; float ymin = y_center - h / 2; float xmin = x_center - w / 2; float ymax = y_center + h / 2; float xmax = x_center + w / 2; // scaling ymin *= resize_scale; xmin *= resize_scale; ymax *= resize_scale; xmax *= resize_scale; // clipping xmin = fmaxf(fminf(xmin, (float) (raw_w - 1)), 0.f); xmax = fmaxf(fminf(xmax, (float) (raw_w - 1)), 0.f); ymin = fmaxf(fminf(ymin, (float) (raw_h - 1)), 0.f); ymax = fmaxf(fminf(ymax, (float) (raw_h - 1)), 0.f); // area filtering float area = (xmax - xmin) * (ymax - ymin); if (area < 4){ proposals[i].class_idx = -1; continue; } num_proposals_over_threshold++; proposals[i].x0 = (int) xmin; proposals[i].x1 = (int) xmax; proposals[i].y0 = (int) ymin; proposals[i].y1 = (int) ymax; } free(anchors_x0); free(anchors_x1); free(anchors_y0); free(anchors_y1); free(output_data_regression); free(output_data_classification); // filter boxes with confidence threshold Box_t* proposals_over_threshold = malloc(sizeof(Box_t) * num_proposals_over_threshold); int proposals_over_threshold_idx = 0; for (int i = 0; i < num_anchors; i++) { Box_t box = proposals[i]; if(box.class_idx == -1) continue; proposals_over_threshold[proposals_over_threshold_idx] = box; proposals_over_threshold_idx++; } free(proposals); if (num_proposals_over_threshold > 0){ // sort boxes qsort_descent_inplace(proposals_over_threshold, 0, num_proposals_over_threshold - 1); // nms int* suppressed = calloc(num_proposals_over_threshold, sizeof(int)); int num_outputs = nms(proposals_over_threshold, num_proposals_over_threshold, suppressed, NMS_THRESHOLD); Box_t* proposals_after_nms = malloc(num_outputs * sizeof(Box_t)); int proposals_after_nms_idx = 0; for(int i = 0; i < num_proposals_over_threshold; i++){ Box_t box = proposals_over_threshold[i]; if(suppressed[i] == 1) continue; proposals_after_nms[proposals_after_nms_idx] = box; proposals_after_nms_idx++; } free(suppressed); for (int i = 0; i < num_outputs; i++) { Box_t box = proposals_after_nms[i]; draw_box(im_vis, box.x0, box.y0, box.x1, box.y1, 2, 125, 0, 125); fprintf(stderr, "%s\t:%.1f%%\n", CLASSES_NAME[box.class_idx], box.score * 100); fprintf(stderr, "BOX:( %d , %d ),( %d , %d )\n", box.x0, box.y0, box.x1, box.y1); } save_image(im_vis, "efficientdet_out"); free(proposals_after_nms); } free(proposals_over_threshold); /* release tengine */ free(input_data); postrun_graph(graph); destroy_graph(graph); release_tengine(); return 0; } void show_usage() { fprintf( stderr, "[Usage]: [-h]\n [-m model_file] [-i image_file]\n [-g img_h,img_w] [-s scale[0],scale[1],scale[2]] [-w " "mean[0],mean[1],mean[2]] [-r loop_count] [-t thread_count] [-a cpu_affinity]\n"); fprintf( stderr, "\nefficientdet example: \n ./classification -m /path/to/efficientdet.tmfile -i /path/to/img.jpg -g 512,512 -s " "0.017,0.017,0.017 -w 103.53,116.28,123.675\n"); } int main(int argc, char* argv[]) { int loop_count = DEFAULT_LOOP_COUNT; int num_thread = DEFAULT_THREAD_COUNT; int cpu_affinity = DEFAULT_CPU_AFFINITY; char* model_file = NULL; char* image_file = NULL; float img_hw[2] = {0.f}; int img_h = 0; int img_w = 0; float mean[3] = {-1.f, -1.f, -1.f}; float scale[3] = {0.f, 0.f, 0.f}; int res; while ((res = getopt(argc, argv, "m:i:l:g:s:w:r:t:a:h")) != -1) { switch (res) { case 'm': model_file = optarg; break; case 'i': image_file = optarg; break; case 'g': split(img_hw, optarg, ","); img_h = ( int )img_hw[0]; img_w = ( int )img_hw[1]; break; case 's': split(scale, optarg, ","); break; case 'w': split(mean, optarg, ","); break; case 'r': loop_count = atoi(optarg); break; case 't': num_thread = atoi(optarg); break; case 'a': cpu_affinity = atoi(optarg); break; case 'h': show_usage(); return 0; default: break; } } /* check files */ if (model_file == NULL) { fprintf(stderr, "Error: Tengine model file not specified!\n"); show_usage(); return -1; } if (image_file == NULL) { fprintf(stderr, "Error: Image file not specified!\n"); show_usage(); return -1; } if (!check_file_exist(model_file) || !check_file_exist(image_file)) return -1; if (img_h == 0) { img_h = DEFAULT_IMG_H; fprintf(stderr, "Image height not specified, use default %d\n", img_h); } if (img_w == 0) { img_w = DEFAULT_IMG_W; fprintf(stderr, "Image width not specified, use default %d\n", img_w); } if (scale[0] == 0.f || scale[1] == 0.f || scale[2] == 0.f) { scale[0] = DEFAULT_SCALE1; scale[1] = DEFAULT_SCALE2; scale[2] = DEFAULT_SCALE3; fprintf(stderr, "Scale value not specified, use default %.3f, %.3f, %.3f\n", scale[0], scale[1], scale[2]); } if (mean[0] == -1.0 || mean[1] == -1.0 || mean[2] == -1.0) { mean[0] = DEFAULT_MEAN1; mean[1] = DEFAULT_MEAN2; mean[2] = DEFAULT_MEAN3; fprintf(stderr, "Mean value not specified, use default %.1f, %.1f, %.1f\n", mean[0], mean[1], mean[2]); } if (tengine_detect(model_file, image_file, img_h, img_w, mean, scale, loop_count, num_thread, cpu_affinity) < 0) return -1; return 0; }
openmp.h
#ifndef _OPENMP_H #define _OPENMP_H #if defined(_OPENMP) #include <omp.h> #else typedef int omp_int_t; inline omp_int_t omp_get_thread_num() { return 0;} inline omp_int_t omp_get_num_threads() { return 1;} inline omp_int_t omp_get_max_threads() { return 1;} #endif #include <complex> // #include "complex_ops.h" namespace basis_general { template<class T> inline void atomic_add(const std::complex<double> m,std::complex<T> *M){ T * M_v = reinterpret_cast<T*>(M); const T m_real = m.real(); const T m_imag = m.imag(); #pragma omp atomic M_v[0] += m_real; #pragma omp atomic M_v[1] += m_imag; } template<class T> inline void atomic_add(const std::complex<double> m,T *M){ const T m_real = m.real(); #pragma omp atomic M[0] += m_real; } } /* namespace basis_general_addition { int inline atomic_add(const npy_cdouble_wrapper m,npy_cdouble_wrapper *M){ double * M_v = reinterpret_cast<double*>(M); const double m_real = m.real; const double m_imag = m.imag; #pragma omp atomic M_v[0] += m_real; #pragma omp atomic M_v[1] += m_imag; return 0; } int inline atomic_add(const npy_cdouble_wrapper m,npy_cfloat_wrapper *M){ float * M_v = reinterpret_cast<float*>(M); const float m_real = m.real; const float m_imag = m.imag; #pragma omp atomic M_v[0] += m_real; #pragma omp atomic M_v[1] += m_imag; return 0; } template<class T> int inline atomic_add(const npy_cdouble_wrapper m,T *M){ if(std::abs(m.imag)>1.1e-15){ return 1; } else{ const T m_real = (T)m.real; #pragma omp atomic M[0] += m_real; return 0; } } } */ #endif
GB_binop__rdiv_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__rdiv_int16) // A.*B function (eWiseMult): GB (_AemultB_01__rdiv_int16) // A.*B function (eWiseMult): GB (_AemultB_02__rdiv_int16) // A.*B function (eWiseMult): GB (_AemultB_03__rdiv_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_int16) // A*D function (colscale): GB (_AxD__rdiv_int16) // D*A function (rowscale): GB (_DxB__rdiv_int16) // C+=B function (dense accum): GB (_Cdense_accumB__rdiv_int16) // C+=b function (dense accum): GB (_Cdense_accumb__rdiv_int16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_int16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_int16) // C=scalar+B GB (_bind1st__rdiv_int16) // C=scalar+B' GB (_bind1st_tran__rdiv_int16) // C=A+scalar GB (_bind2nd__rdiv_int16) // C=A'+scalar GB (_bind2nd_tran__rdiv_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = GB_IDIV_SIGNED (bij, aij, 16) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IDIV_SIGNED (y, x, 16) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RDIV || GxB_NO_INT16 || GxB_NO_RDIV_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__rdiv_int16) ( 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__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rdiv_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rdiv_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__rdiv_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__rdiv_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rdiv_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IDIV_SIGNED (bij, x, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rdiv_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IDIV_SIGNED (y, aij, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_SIGNED (aij, x, 16) ; \ } GrB_Info GB (_bind1st_tran__rdiv_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_SIGNED (y, aij, 16) ; \ } GrB_Info GB (_bind2nd_tran__rdiv_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
matrix_csr.h
#ifndef XGBOOST_UTILS_MATRIX_CSR_H_ #define XGBOOST_UTILS_MATRIX_CSR_H_ /*! * \file matrix_csr.h * \brief this file defines some easy to use STL based class for in memory sparse CSR matrix * \author Tianqi Chen */ #include <vector> #include <utility> #include <algorithm> #include "./io.h" #include "./utils.h" #include "./omp.h" namespace xgboost { namespace utils { /*! * \brief a class used to help construct CSR format matrix, * can be used to convert row major CSR to column major CSR * \tparam IndexType type of index used to store the index position, usually unsigned or size_t * \tparam whether enabling the usage of aclist, this option must be enabled manually */ template<typename IndexType, bool UseAcList = false, typename SizeType = size_t> struct SparseCSRMBuilder { private: /*! \brief dummy variable used in the indicator matrix construction */ std::vector<size_t> dummy_aclist; /*! \brief pointer to each of the row */ std::vector<SizeType> &rptr; /*! \brief index of nonzero entries in each row */ std::vector<IndexType> &findex; /*! \brief a list of active rows, used when many rows are empty */ std::vector<size_t> &aclist; public: SparseCSRMBuilder(std::vector<SizeType> &p_rptr, std::vector<IndexType> &p_findex) :rptr(p_rptr), findex(p_findex), aclist(dummy_aclist) { Assert(!UseAcList, "enabling bug"); } /*! \brief use with caution! rptr must be cleaned before use */ SparseCSRMBuilder(std::vector<SizeType> &p_rptr, std::vector<IndexType> &p_findex, std::vector<size_t> &p_aclist) :rptr(p_rptr), findex(p_findex), aclist(p_aclist) { Assert(UseAcList, "must manually enable the option use aclist"); } public: /*! * \brief step 1: initialize the number of rows in the data, not necessary exact * \nrows number of rows in the matrix, can be smaller than expected */ inline void InitBudget(size_t nrows = 0) { if (!UseAcList) { rptr.clear(); rptr.resize(nrows + 1, 0); } else { Assert(nrows + 1 == rptr.size(), "rptr must be initialized already"); this->Cleanup(); } } /*! * \brief step 2: add budget to each rows, this function is called when aclist is used * \param row_id the id of the row * \param nelem number of element budget add to this row */ inline void AddBudget(size_t row_id, SizeType nelem = 1) { if (rptr.size() < row_id + 2) { rptr.resize(row_id + 2, 0); } if (UseAcList) { if (rptr[row_id + 1] == 0) aclist.push_back(row_id); } rptr[row_id + 1] += nelem; } /*! \brief step 3: initialize the necessary storage */ inline void InitStorage(void) { // initialize rptr to be beginning of each segment size_t start = 0; if (!UseAcList) { for (size_t i = 1; i < rptr.size(); i++) { size_t rlen = rptr[i]; rptr[i] = start; start += rlen; } } else { // case with active list std::sort(aclist.begin(), aclist.end()); for (size_t i = 0; i < aclist.size(); i++) { size_t ridx = aclist[i]; size_t rlen = rptr[ridx + 1]; rptr[ridx + 1] = start; // set previous rptr to right position if previous feature is not active if (i == 0 || ridx != aclist[i - 1] + 1) rptr[ridx] = start; start += rlen; } } findex.resize(start); } /*! * \brief step 4: * used in indicator matrix construction, add new * element to each row, the number of calls shall be exactly same as add_budget */ inline void PushElem(size_t row_id, IndexType col_id) { SizeType &rp = rptr[row_id + 1]; findex[rp++] = col_id; } /*! * \brief step 5: only needed when aclist is used * clean up the rptr for next usage */ inline void Cleanup(void) { Assert(UseAcList, "this function can only be called use AcList"); for (size_t i = 0; i < aclist.size(); i++) { const size_t ridx = aclist[i]; rptr[ridx] = 0; rptr[ridx + 1] = 0; } aclist.clear(); } }; /*! * \brief a class used to help construct CSR format matrix file * \tparam IndexType type of index used to store the index position * \tparam SizeType type of size used in row pointer */ template<typename IndexType, typename SizeType = size_t> struct SparseCSRFileBuilder { public: explicit SparseCSRFileBuilder(utils::ISeekStream *fo, size_t buffer_size) : fo(fo), buffer_size(buffer_size) { } /*! * \brief step 1: initialize the number of rows in the data, not necessary exact * \nrows number of rows in the matrix, can be smaller than expected */ inline void InitBudget(size_t nrows = 0) { rptr.clear(); rptr.resize(nrows + 1, 0); } /*! * \brief step 2: add budget to each rows * \param row_id the id of the row * \param nelem number of element budget add to this row */ inline void AddBudget(size_t row_id, SizeType nelem = 1) { if (rptr.size() < row_id + 2) { rptr.resize(row_id + 2, 0); } rptr[row_id + 1] += nelem; } /*! \brief step 3: initialize the necessary storage */ inline void InitStorage(void) { SizeType nelem = 0; for (size_t i = 1; i < rptr.size(); i++) { nelem += rptr[i]; rptr[i] = nelem; } begin_data = static_cast<SizeType>(fo->Tell()) + sizeof(SizeType); SizeType begin_meta = begin_data + nelem * sizeof(IndexType); fo->Write(&begin_meta, sizeof(begin_meta)); fo->Seek(begin_meta); fo->Write(rptr); // setup buffer space buffer_rptr.resize(rptr.size()); buffer_temp.reserve(buffer_size); buffer_data.resize(buffer_size); saved_offset = rptr; saved_offset.resize(rptr.size() - 1); this->ClearBuffer(); } /*! \brief step 4: push element into buffer */ inline void PushElem(SizeType row_id, IndexType col_id) { if (buffer_temp.size() == buffer_size) { this->WriteBuffer(); this->ClearBuffer(); } buffer_rptr[row_id + 1] += 1; buffer_temp.push_back(std::make_pair(row_id, col_id)); } /*! \brief finalize the construction */ inline void Finalize(void) { this->WriteBuffer(); for (size_t i = 0; i < saved_offset.size(); ++i) { utils::Assert(saved_offset[i] == rptr[i+1], "some block not write out"); } } /*! \brief content must be in wb+ */ template<typename Comparator> inline void SortRows(Comparator comp, size_t step) { for (size_t i = 0; i < rptr.size() - 1; i += step) { bst_omp_uint begin = static_cast<bst_omp_uint>(i); bst_omp_uint end = static_cast<bst_omp_uint>(std::min(rptr.size() - 1, i + step)); if (rptr[end] != rptr[begin]) { fo->Seek(begin_data + rptr[begin] * sizeof(IndexType)); buffer_data.resize(rptr[end] - rptr[begin]); fo->Read(BeginPtr(buffer_data), (rptr[end] - rptr[begin]) * sizeof(IndexType)); // do parallel sorting #pragma omp parallel for schedule(static) for (bst_omp_uint j = begin; j < end; ++j) { std::sort(&buffer_data[0] + rptr[j] - rptr[begin], &buffer_data[0] + rptr[j+1] - rptr[begin], comp); } fo->Seek(begin_data + rptr[begin] * sizeof(IndexType)); fo->Write(BeginPtr(buffer_data), (rptr[end] - rptr[begin]) * sizeof(IndexType)); } } } protected: inline void WriteBuffer(void) { SizeType start = 0; for (size_t i = 1; i < buffer_rptr.size(); ++i) { size_t rlen = buffer_rptr[i]; buffer_rptr[i] = start; start += rlen; } for (size_t i = 0; i < buffer_temp.size(); ++i) { SizeType &rp = buffer_rptr[buffer_temp[i].first + 1]; buffer_data[rp++] = buffer_temp[i].second; } // write out for (size_t i = 0; i < buffer_rptr.size() - 1; ++i) { size_t nelem = buffer_rptr[i+1] - buffer_rptr[i]; if (nelem != 0) { utils::Assert(saved_offset[i] + nelem <= rptr[i+1], "data exceed bound"); fo->Seek(saved_offset[i] * sizeof(IndexType) + begin_data); fo->Write(&buffer_data[0] + buffer_rptr[i], nelem * sizeof(IndexType)); saved_offset[i] += nelem; } } } inline void ClearBuffer(void) { buffer_temp.clear(); std::fill(buffer_rptr.begin(), buffer_rptr.end(), 0); } private: /*! \brief output file pointer the data */ utils::ISeekStream *fo; /*! \brief pointer to each of the row */ std::vector<SizeType> rptr; /*! \brief saved top space of each item */ std::vector<SizeType> saved_offset; /*! \brief beginning position of data */ size_t begin_data; // ----- the following are buffer space /*! \brief maximum size of content buffer*/ size_t buffer_size; /*! \brief store the data content */ std::vector< std::pair<SizeType, IndexType> > buffer_temp; /*! \brief saved top space of each item */ std::vector<SizeType> buffer_rptr; /*! \brief saved top space of each item */ std::vector<IndexType> buffer_data; }; } // namespace utils } // namespace xgboost #endif
GB_unop__identity_int8_uint8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_int8_uint8 // op(A') function: GB_unop_tran__identity_int8_uint8 // C type: int8_t // A type: uint8_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int8_uint8 ( int8_t *Cx, // Cx and Ax may be aliased const uint8_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++) { uint8_t aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_int8_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
BKTree.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SPTAG_COMMON_BKTREE_H_ #define _SPTAG_COMMON_BKTREE_H_ #include <iostream> #include <stack> #include <string> #include <vector> #include "../VectorIndex.h" #include "CommonUtils.h" #include "QueryResultSet.h" #include "WorkSpace.h" #pragma warning(disable:4996) // 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. namespace SPTAG { namespace COMMON { // node type for storing BKT struct BKTNode { int centerid; int childStart; int childEnd; BKTNode(int cid = -1) : centerid(cid), childStart(-1), childEnd(-1) {} }; template <typename T> struct KmeansArgs { int _K; int _D; int _T; T* centers; int* counts; float* newCenters; int* newCounts; char* label; int* clusterIdx; float* clusterDist; T* newTCenters; KmeansArgs(int k, int dim, int datasize, int threadnum) : _K(k), _D(dim), _T(threadnum) { centers = new T[k * dim]; counts = new int[k]; newCenters = new float[threadnum * k * dim]; newCounts = new int[threadnum * k]; label = new char[datasize]; clusterIdx = new int[threadnum * k]; clusterDist = new float[threadnum * k]; newTCenters = new T[k * dim]; } ~KmeansArgs() { delete[] centers; delete[] counts; delete[] newCenters; delete[] newCounts; delete[] label; delete[] clusterIdx; delete[] clusterDist; delete[] newTCenters; } inline void ClearCounts() { memset(newCounts, 0, sizeof(int) * _T * _K); } inline void ClearCenters() { memset(newCenters, 0, sizeof(float) * _T * _K * _D); } inline void ClearDists(float dist) { for (int i = 0; i < _T * _K; i++) { clusterIdx[i] = -1; clusterDist[i] = dist; } } void Shuffle(std::vector<int>& indices, int first, int last) { int* pos = new int[_K]; pos[0] = first; for (int k = 1; k < _K; k++) pos[k] = pos[k - 1] + newCounts[k - 1]; for (int k = 0; k < _K; k++) { if (newCounts[k] == 0) continue; int i = pos[k]; while (newCounts[k] > 0) { int swapid = pos[(int)(label[i])] + newCounts[(int)(label[i])] - 1; newCounts[(int)(label[i])]--; std::swap(indices[i], indices[swapid]); std::swap(label[i], label[swapid]); } while (indices[i] != clusterIdx[k]) i++; std::swap(indices[i], indices[pos[k] + counts[k] - 1]); } delete[] pos; } }; class BKTree { public: BKTree(): m_iTreeNumber(1), m_iBKTKmeansK(32), m_iBKTLeafSize(8), m_iSamples(1000) {} BKTree(BKTree& other): m_iTreeNumber(other.m_iTreeNumber), m_iBKTKmeansK(other.m_iBKTKmeansK), m_iBKTLeafSize(other.m_iBKTLeafSize), m_iSamples(other.m_iSamples) {} ~BKTree() {} inline const BKTNode& operator[](int index) const { return m_pTreeRoots[index]; } inline BKTNode& operator[](int index) { return m_pTreeRoots[index]; } inline int size() const { return (int)m_pTreeRoots.size(); } inline const std::unordered_map<int, int>& GetSampleMap() const { return m_pSampleCenterMap; } template <typename T> void BuildTrees(VectorIndex* index, std::vector<int>* indices = nullptr) { struct BKTStackItem { int index, first, last; BKTStackItem(int index_, int first_, int last_) : index(index_), first(first_), last(last_) {} }; std::stack<BKTStackItem> ss; std::vector<int> localindices; if (indices == nullptr) { localindices.resize(index->GetNumSamples()); for (int i = 0; i < index->GetNumSamples(); i++) localindices[i] = i; } else { localindices.assign(indices->begin(), indices->end()); } KmeansArgs<T> args(m_iBKTKmeansK, index->GetFeatureDim(), (int)localindices.size(), omp_get_num_threads()); m_pSampleCenterMap.clear(); for (char i = 0; i < m_iTreeNumber; i++) { std::random_shuffle(localindices.begin(), localindices.end()); m_pTreeStart.push_back((int)m_pTreeRoots.size()); m_pTreeRoots.push_back(BKTNode((int)localindices.size())); std::cout << "Start to build BKTree " << i + 1 << std::endl; ss.push(BKTStackItem(m_pTreeStart[i], 0, (int)localindices.size())); while (!ss.empty()) { BKTStackItem item = ss.top(); ss.pop(); int newBKTid = (int)m_pTreeRoots.size(); m_pTreeRoots[item.index].childStart = newBKTid; if (item.last - item.first <= m_iBKTLeafSize) { for (int j = item.first; j < item.last; j++) { m_pTreeRoots.push_back(BKTNode(localindices[j])); } } else { // clustering the data into BKTKmeansK clusters int numClusters = KmeansClustering(index, localindices, item.first, item.last, args); if (numClusters <= 1) { int end = min(item.last + 1, (int)localindices.size()); std::sort(localindices.begin() + item.first, localindices.begin() + end); m_pTreeRoots[item.index].centerid = localindices[item.first]; m_pTreeRoots[item.index].childStart = -m_pTreeRoots[item.index].childStart; for (int j = item.first + 1; j < end; j++) { m_pTreeRoots.push_back(BKTNode(localindices[j])); m_pSampleCenterMap[localindices[j]] = m_pTreeRoots[item.index].centerid; } m_pSampleCenterMap[-1 - m_pTreeRoots[item.index].centerid] = item.index; } else { for (int k = 0; k < m_iBKTKmeansK; k++) { if (args.counts[k] == 0) continue; m_pTreeRoots.push_back(BKTNode(localindices[item.first + args.counts[k] - 1])); if (args.counts[k] > 1) ss.push(BKTStackItem(newBKTid++, item.first, item.first + args.counts[k] - 1)); item.first += args.counts[k]; } } } m_pTreeRoots[item.index].childEnd = (int)m_pTreeRoots.size(); } std::cout << i + 1 << " BKTree built, " << m_pTreeRoots.size() - m_pTreeStart[i] << " " << localindices.size() << std::endl; } } bool SaveTrees(std::string sTreeFileName) const { std::cout << "Save BKT to " << sTreeFileName << std::endl; FILE *fp = fopen(sTreeFileName.c_str(), "wb"); if (fp == NULL) return false; fwrite(&m_iTreeNumber, sizeof(int), 1, fp); fwrite(m_pTreeStart.data(), sizeof(int), m_iTreeNumber, fp); int treeNodeSize = (int)m_pTreeRoots.size(); fwrite(&treeNodeSize, sizeof(int), 1, fp); fwrite(m_pTreeRoots.data(), sizeof(BKTNode), treeNodeSize, fp); fclose(fp); std::cout << "Save BKT (" << m_iTreeNumber << "," << treeNodeSize << ") Finish!" << std::endl; return true; } bool LoadTrees(char* pBKTMemFile) { m_iTreeNumber = *((int*)pBKTMemFile); pBKTMemFile += sizeof(int); m_pTreeStart.resize(m_iTreeNumber); memcpy(m_pTreeStart.data(), pBKTMemFile, sizeof(int) * m_iTreeNumber); pBKTMemFile += sizeof(int)*m_iTreeNumber; int treeNodeSize = *((int*)pBKTMemFile); pBKTMemFile += sizeof(int); m_pTreeRoots.resize(treeNodeSize); memcpy(m_pTreeRoots.data(), pBKTMemFile, sizeof(BKTNode) * treeNodeSize); return true; } bool LoadTrees(std::string sTreeFileName) { std::cout << "Load BKT From " << sTreeFileName << std::endl; FILE *fp = fopen(sTreeFileName.c_str(), "rb"); if (fp == NULL) return false; fread(&m_iTreeNumber, sizeof(int), 1, fp); m_pTreeStart.resize(m_iTreeNumber); fread(m_pTreeStart.data(), sizeof(int), m_iTreeNumber, fp); int treeNodeSize; fread(&treeNodeSize, sizeof(int), 1, fp); m_pTreeRoots.resize(treeNodeSize); fread(m_pTreeRoots.data(), sizeof(BKTNode), treeNodeSize, fp); fclose(fp); std::cout << "Load BKT (" << m_iTreeNumber << "," << treeNodeSize << ") Finish!" << std::endl; return true; } template <typename T> void InitSearchTrees(const VectorIndex* p_index, const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space) const { for (char i = 0; i < m_iTreeNumber; i++) { const BKTNode& node = m_pTreeRoots[m_pTreeStart[i]]; if (node.childStart < 0) { p_space.m_SPTQueue.insert(COMMON::HeapCell(m_pTreeStart[i], p_index->ComputeDistance((const void*)p_query.GetTarget(), p_index->GetSample(node.centerid)))); } else { for (int begin = node.childStart; begin < node.childEnd; begin++) { int index = m_pTreeRoots[begin].centerid; p_space.m_SPTQueue.insert(COMMON::HeapCell(begin, p_index->ComputeDistance((const void*)p_query.GetTarget(), p_index->GetSample(index)))); } } } } template <typename T> void SearchTrees(const VectorIndex* p_index, const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space, const int p_limits) const { do { COMMON::HeapCell bcell = p_space.m_SPTQueue.pop(); const BKTNode& tnode = m_pTreeRoots[bcell.node]; if (tnode.childStart < 0) { if (!p_space.CheckAndSet(tnode.centerid)) { p_space.m_iNumberOfCheckedLeaves++; p_space.m_NGQueue.insert(COMMON::HeapCell(tnode.centerid, bcell.distance)); } if (p_space.m_iNumberOfCheckedLeaves >= p_limits) break; } else { if (!p_space.CheckAndSet(tnode.centerid)) { p_space.m_NGQueue.insert(COMMON::HeapCell(tnode.centerid, bcell.distance)); } for (int begin = tnode.childStart; begin < tnode.childEnd; begin++) { int index = m_pTreeRoots[begin].centerid; p_space.m_SPTQueue.insert(COMMON::HeapCell(begin, p_index->ComputeDistance((const void*)p_query.GetTarget(), p_index->GetSample(index)))); } } } while (!p_space.m_SPTQueue.empty()); } private: template <typename T> float KmeansAssign(VectorIndex* p_index, std::vector<int>& indices, const int first, const int last, KmeansArgs<T>& args, const bool updateCenters) const { float currDist = 0; int threads = omp_get_num_threads(); float lambda = (updateCenters) ? COMMON::Utils::GetBase<T>() * COMMON::Utils::GetBase<T>() / (100.0f * (last - first)) : 0.0f; int subsize = (last - first - 1) / threads + 1; #pragma omp parallel for for (int tid = 0; tid < threads; tid++) { int istart = first + tid * subsize; int iend = min(first + (tid + 1) * subsize, last); int *inewCounts = args.newCounts + tid * m_iBKTKmeansK; float *inewCenters = args.newCenters + tid * m_iBKTKmeansK * p_index->GetFeatureDim(); int * iclusterIdx = args.clusterIdx + tid * m_iBKTKmeansK; float * iclusterDist = args.clusterDist + tid * m_iBKTKmeansK; float idist = 0; for (int i = istart; i < iend; i++) { int clusterid = 0; float smallestDist = MaxDist; for (int k = 0; k < m_iBKTKmeansK; k++) { float dist = p_index->ComputeDistance(p_index->GetSample(indices[i]), (const void*)(args.centers + k*p_index->GetFeatureDim())) + lambda*args.counts[k]; if (dist > -MaxDist && dist < smallestDist) { clusterid = k; smallestDist = dist; } } args.label[i] = clusterid; inewCounts[clusterid]++; idist += smallestDist; if (updateCenters) { const T* v = (const T*)p_index->GetSample(indices[i]); float* center = inewCenters + clusterid*p_index->GetFeatureDim(); for (int j = 0; j < p_index->GetFeatureDim(); j++) center[j] += v[j]; if (smallestDist > iclusterDist[clusterid]) { iclusterDist[clusterid] = smallestDist; iclusterIdx[clusterid] = indices[i]; } } else { if (smallestDist <= iclusterDist[clusterid]) { iclusterDist[clusterid] = smallestDist; iclusterIdx[clusterid] = indices[i]; } } } COMMON::Utils::atomic_float_add(&currDist, idist); } for (int i = 1; i < threads; i++) { for (int k = 0; k < m_iBKTKmeansK; k++) args.newCounts[k] += args.newCounts[i*m_iBKTKmeansK + k]; } if (updateCenters) { for (int i = 1; i < threads; i++) { float* currCenter = args.newCenters + i*m_iBKTKmeansK*p_index->GetFeatureDim(); for (int j = 0; j < m_iBKTKmeansK * p_index->GetFeatureDim(); j++) args.newCenters[j] += currCenter[j]; } int maxcluster = 0; for (int k = 1; k < m_iBKTKmeansK; k++) if (args.newCounts[maxcluster] < args.newCounts[k]) maxcluster = k; int maxid = maxcluster; for (int tid = 1; tid < threads; tid++) { if (args.clusterDist[maxid] < args.clusterDist[tid * m_iBKTKmeansK + maxcluster]) maxid = tid * m_iBKTKmeansK + maxcluster; } if (args.clusterIdx[maxid] < 0 || args.clusterIdx[maxid] >= p_index->GetNumSamples()) std::cout << "first:" << first << " last:" << last << " maxcluster:" << maxcluster << "(" << args.newCounts[maxcluster] << ") Error maxid:" << maxid << " dist:" << args.clusterDist[maxid] << std::endl; maxid = args.clusterIdx[maxid]; for (int k = 0; k < m_iBKTKmeansK; k++) { T* TCenter = args.newTCenters + k * p_index->GetFeatureDim(); if (args.newCounts[k] == 0) { //int nextid = Utils::rand_int(last, first); //while (args.label[nextid] != maxcluster) nextid = Utils::rand_int(last, first); int nextid = maxid; std::memcpy(TCenter, p_index->GetSample(nextid), sizeof(T)*p_index->GetFeatureDim()); } else { float* currCenters = args.newCenters + k * p_index->GetFeatureDim(); for (int j = 0; j < p_index->GetFeatureDim(); j++) currCenters[j] /= args.newCounts[k]; if (p_index->GetDistCalcMethod() == DistCalcMethod::Cosine) { COMMON::Utils::Normalize(currCenters, p_index->GetFeatureDim(), COMMON::Utils::GetBase<T>()); } for (int j = 0; j < p_index->GetFeatureDim(); j++) TCenter[j] = (T)(currCenters[j]); } } } else { for (int i = 1; i < threads; i++) { for (int k = 0; k < m_iBKTKmeansK; k++) { if (args.clusterIdx[i*m_iBKTKmeansK + k] != -1 && args.clusterDist[i*m_iBKTKmeansK + k] <= args.clusterDist[k]) { args.clusterDist[k] = args.clusterDist[i*m_iBKTKmeansK + k]; args.clusterIdx[k] = args.clusterIdx[i*m_iBKTKmeansK + k]; } } } } return currDist; } template <typename T> int KmeansClustering(VectorIndex* p_index, std::vector<int>& indices, const int first, const int last, KmeansArgs<T>& args) const { int iterLimit = 100; int batchEnd = min(first + m_iSamples, last); float currDiff, currDist, minClusterDist = MaxDist; for (int numKmeans = 0; numKmeans < 3; numKmeans++) { for (int k = 0; k < m_iBKTKmeansK; k++) { int randid = COMMON::Utils::rand_int(last, first); std::memcpy(args.centers + k*p_index->GetFeatureDim(), p_index->GetSample(indices[randid]), sizeof(T)*p_index->GetFeatureDim()); } args.ClearCounts(); currDist = KmeansAssign(p_index, indices, first, batchEnd, args, false); if (currDist < minClusterDist) { minClusterDist = currDist; memcpy(args.newTCenters, args.centers, sizeof(T)*m_iBKTKmeansK*p_index->GetFeatureDim()); memcpy(args.counts, args.newCounts, sizeof(int) * m_iBKTKmeansK); } } minClusterDist = MaxDist; int noImprovement = 0; for (int iter = 0; iter < iterLimit; iter++) { std::memcpy(args.centers, args.newTCenters, sizeof(T)*m_iBKTKmeansK*p_index->GetFeatureDim()); std::random_shuffle(indices.begin() + first, indices.begin() + last); args.ClearCenters(); args.ClearCounts(); args.ClearDists(-MaxDist); currDist = KmeansAssign(p_index, indices, first, batchEnd, args, true); memcpy(args.counts, args.newCounts, sizeof(int)*m_iBKTKmeansK); currDiff = 0; for (int k = 0; k < m_iBKTKmeansK; k++) { currDiff += p_index->ComputeDistance((const void*)(args.centers + k*p_index->GetFeatureDim()), (const void*)(args.newTCenters + k*p_index->GetFeatureDim())); } if (currDist < minClusterDist) { noImprovement = 0; minClusterDist = currDist; } else { noImprovement++; } if (currDiff < 1e-3 || noImprovement >= 5) break; } args.ClearCounts(); args.ClearDists(MaxDist); currDist = KmeansAssign(p_index, indices, first, last, args, false); memcpy(args.counts, args.newCounts, sizeof(int)*m_iBKTKmeansK); int numClusters = 0; for (int i = 0; i < m_iBKTKmeansK; i++) if (args.counts[i] > 0) numClusters++; if (numClusters <= 1) { //if (last - first > 1) std::cout << "large cluster:" << last - first << " dist:" << currDist << std::endl; return numClusters; } args.Shuffle(indices, first, last); return numClusters; } private: std::vector<int> m_pTreeStart; std::vector<BKTNode> m_pTreeRoots; std::unordered_map<int, int> m_pSampleCenterMap; public: int m_iTreeNumber, m_iBKTKmeansK, m_iBKTLeafSize, m_iSamples; }; } } #endif
DMD5_fmt_plug.c
/* * DMD5_fmt.c * * DIGEST-MD5 authentication module for Solar Designer's John the Ripper * Uses Solar Designer's MD5 implementation. * * This software is Copyright 2006, regenrecht@o2.pl, and * Copyright 2011, 2013 magnum, and it is hereby released to the general * public under the following terms: Redistribution and use in source and * binary forms, with or without modification, are permitted. * * Input format: * $DIGEST-MD5$ username $ realm $ nonce $ digest_uri $ cnonce $ nc $ qop $ response [ $ authzid ] * * Just base64-decode the blob you see when sniffing, to get all data needed for above. * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_DMD5; #elif FMT_REGISTERS_H john_register_one(&fmt_DMD5); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #define OMP_SCALE 1024 #endif #include "arch.h" #include "misc.h" #include "md5.h" #include "common.h" #include "formats.h" #include "memdbg.h" #define FORMAT_LABEL "dmd5" #define FORMAT_NAME "DIGEST-MD5 C/R" #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MD5_HEX_SIZE (2 * BINARY_SIZE) #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(cur_salt) #define SALT_ALIGN 1 #define DSIZE (128 - sizeof(int)) #define CIPHERTEXT_LENGTH (DSIZE * 4) #define PLAINTEXT_LENGTH 32 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static const char itoa16_shr_04[] = "0000000000000000" "1111111111111111" "2222222222222222" "3333333333333333" "4444444444444444" "5555555555555555" "6666666666666666" "7777777777777777" "8888888888888888" "9999999999999999" "aaaaaaaaaaaaaaaa" "bbbbbbbbbbbbbbbb" "cccccccccccccccc" "dddddddddddddddd" "eeeeeeeeeeeeeeee" "ffffffffffffffff"; static const char itoa16_and_0f[] = "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef"; static struct { unsigned char login_id[DSIZE]; // username:realm unsigned int login_id_len; unsigned char nonces[DSIZE]; // :nonce:cnonce[:authzid] unsigned int nonces_len; unsigned char prehash_KD[DSIZE]; // :nonce:nc:cnonce:qop:hex_A2_hash unsigned int prehash_KD_len; } cur_salt; static ARCH_WORD_32 (*crypt_key)[BINARY_SIZE/4]; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static struct fmt_tests tests[] = { {"$DIGEST-MD5$s3443$pjwstk$00$ldap/10.253.34.43$0734d94ad9abd5bd7fc5e7e77bcf49a8$00000001$auth-int$dd98347e6da3efd6c4ff2263a729ef77", "test"}, {NULL} }; static void init(struct fmt_main *self) { #ifdef _OPENMP int n = omp_get_max_threads(); self->params.min_keys_per_crypt *= n; self->params.max_keys_per_crypt *= (n * OMP_SCALE); #endif saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_SIMD); crypt_key = mem_calloc_tiny(sizeof(*crypt_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *data = ciphertext + 12; if (strncmp(ciphertext, "$DIGEST-MD5$", 12) != 0) return 0; if (strlen(ciphertext) > CIPHERTEXT_LENGTH) return 0; if (!(p = strchr(data, '$')) || (int)(p-data) >= 64) // username return 0; data = p + 1; // realm if (!(p = strchr(data, '$')) || (int)(p-data) >= 64) return 0; data = p + 1; // nonce if (!(p = strchr(data, '$')) || (int)(p-data) >= 64) return 0; data = p + 1; // digest_uri if (!(p = strchr(data, '$')) || (int)(p-data) >= DSIZE) return 0; data = p + 1; // cnonce if (!(p = strchr(data, '$')) || (int)(p-data) > MD5_HEX_SIZE) return 0; data = p + 1; // nc if (!(p = strchr(data, '$')) || (int)(p-data) >= 9) return 0; data = p + 1; // qop if (strncmp(data, "auth", 4) && strncmp(data, "auth-int", 8) && strncmp(data, "auth-conf", 9)) return 0; if (!(p = strchr(data, '$')) || (int)(p-data) >= 9) return 0; data = p + 1; // authzid, optional if ((p = strchr(data, '$'))) { if ((int)(p-data) > MD5_HEX_SIZE || strlen(&p[1]) >= 8) return 0; } else if (strlen(data) > MD5_HEX_SIZE) return 0; return 1; } static void *binary(char *ciphertext) { static ARCH_WORD_32 out[BINARY_SIZE/4]; char response[MD5_HEX_SIZE + 1]; unsigned int i; char *p, *data = ciphertext + 12; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); if (p && (p - data + 1) < sizeof(response)) strnzcpy(response, data, p - data + 1); else strnzcpy(response, data, sizeof(response)); for (i = 0; i < BINARY_SIZE; ++i) ((unsigned char*)out)[i] = (atoi16[ARCH_INDEX(response[i*2])] << 4) + atoi16[ARCH_INDEX(response[i*2+1])]; return (void*)out; } static void *salt(char *ciphertext) { char username[64]; char realm[64]; char nonce[64]; char digest_uri[DSIZE]; char cnonce[MD5_HEX_SIZE + 1]; char nc[9]; char qop[9]; char authzid[8]; unsigned char *ptr_src, *ptr_dst, v, i; char *ccopy = strdup(ciphertext); char *p, *data = ccopy + 12; MD5_CTX ctx; char A2[DSIZE]; unsigned char hash[BINARY_SIZE]; unsigned char hex_hash[2*MD5_HEX_SIZE]; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(username, data, sizeof(username)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(realm, data, sizeof(realm)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(nonce, data, sizeof(nonce)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(digest_uri, data, sizeof(digest_uri)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(cnonce, data, sizeof(cnonce)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(nc, data, sizeof(nc)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(qop, data, sizeof(qop)); data = p + 1; if ((p = strchr(data, '$'))) { *p = 0; data = p + 1; if (*data) strnzcpy(authzid, data, sizeof(authzid)); else *authzid = 0; } else { *authzid = 0; } if (!strcmp(qop, "auth")) snprintf((char*)A2, sizeof(A2), "AUTHENTICATE:%s", digest_uri); else if (!strcmp(qop, "auth-int") || !strcmp(qop, "auth-conf")) snprintf((char*)A2, sizeof(A2), "AUTHENTICATE:%s:00000000000000000000000000000000", digest_uri); MD5_Init(&ctx); MD5_Update(&ctx, A2, strlen((char*)A2)); MD5_Final(hash, &ctx); ptr_src = hash; ptr_dst = hex_hash; for (i = 0; i < BINARY_SIZE; ++i) { v = *ptr_src++; *ptr_dst++ = itoa16_shr_04[ARCH_INDEX(v)]; *ptr_dst++ = itoa16_and_0f[ARCH_INDEX(v)]; } *ptr_dst = 0; snprintf((char*)cur_salt.prehash_KD, sizeof(cur_salt.prehash_KD), ":%s:%s:%s:%s:%s", nonce, nc, cnonce, qop, hex_hash); cur_salt.prehash_KD_len = strlen((char*)cur_salt.prehash_KD); if (authzid[0]) snprintf((char*)cur_salt.nonces, sizeof(cur_salt.nonces), ":%s:%s:%s", nonce, cnonce, authzid); else snprintf((char*)cur_salt.nonces, sizeof(cur_salt.nonces), ":%s:%s", nonce, cnonce); cur_salt.nonces_len = strlen((char*)cur_salt.nonces); snprintf((char*)cur_salt.login_id, sizeof(cur_salt.login_id), "%s:%s:", username, realm); cur_salt.login_id_len = strlen((char*)cur_salt.login_id); MEM_FREE(ccopy); return (void*)&cur_salt; } static void set_salt(void *salt) { memcpy(&cur_salt, salt, sizeof(cur_salt)); } static void set_key(char *key, int index) { strnzcpyn(saved_key[index], key, PLAINTEXT_LENGTH + 1); } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { unsigned char hash[16]; unsigned char hex_hash[MD5_HEX_SIZE]; unsigned char *ptr_src, *ptr_dst; MD5_CTX ctx; int i; MD5_Init(&ctx); // "username:realm" MD5_Update(&ctx, cur_salt.login_id, cur_salt.login_id_len); // "password" MD5_Update(&ctx, saved_key[index], strlen(saved_key[index])); MD5_Final(hash, &ctx); MD5_Init(&ctx); // previous result MD5_Update(&ctx, hash, BINARY_SIZE); // ":nonce:cnonce[:authzid]" MD5_Update(&ctx, cur_salt.nonces, cur_salt.nonces_len); MD5_Final(hash, &ctx); // hexify ptr_src = hash; ptr_dst = hex_hash; for (i = 0; i < BINARY_SIZE; ++i) { unsigned char v = *ptr_src++; *ptr_dst++ = itoa16_shr_04[ARCH_INDEX(v)]; *ptr_dst++ = itoa16_and_0f[ARCH_INDEX(v)]; } MD5_Init(&ctx); // previous result, in hex MD5_Update(&ctx, hex_hash, MD5_HEX_SIZE); // ":nonce:nc:cnonce:qop:hex_A2_hash MD5_Update(&ctx, cur_salt.prehash_KD, cur_salt.prehash_KD_len); MD5_Final((unsigned char*)crypt_key[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { #if defined(_OPENMP) || (MAX_KEYS_PER_CRYPT > 1) int index; ARCH_WORD_32 b = ((ARCH_WORD_32*)binary)[0]; for (index = 0; index < count; index++) if (crypt_key[index][0] == b) return 1; return 0; #else return ((ARCH_WORD_32*)binary)[0] == crypt_key[0][0]; #endif } 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 int get_hash_0(int index) { return crypt_key[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_key[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_key[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_key[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_key[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_key[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_key[index][0] & 0x7ffffff; } struct fmt_main fmt_DMD5 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, binary, salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
HDF5SubdomainDumper.h
// // HDF5SubdomainDumper.h // Cubism // // Created by Fabian Wermelinger 2018-08-03 // Copyright 2018 ETH Zurich. All rights reserved. // #ifndef HDF5SUBDOMAINDUMPER_H_3C2DKYV4 #define HDF5SUBDOMAINDUMPER_H_3C2DKYV4 #include <cassert> #include <iostream> #include <vector> #include <string> #include <sstream> #include "HDF5Dumper.h" CUBISM_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // helpers namespace SubdomainTypes { template <typename TGrid> class Subdomain { public: template <typename TSubdomain> static std::vector<TSubdomain> getEntities(ArgumentParser& parser, TGrid& grid) { typedef typename TGrid::BlockType B; // Concept: // 1.) Extract bounding box data from parser input subdomains // 2.) Compute global bounding box for each subdomain // defines the number of subdomains in the config file: // nsubdomains 1 # defines one subdomain const size_t nSubdomains = parser("nsubdomains").asInt(0); std::vector<TSubdomain> subdomains; for (size_t i = 0; i < nSubdomains; ++i) { // 1.) const size_t id = i+1; std::ostringstream identifier; identifier << "subdomain" << id; parser.set_strict_mode(); // each defined subdomain requires an origin and an extent: // subdomain1_origin 0 1.0 2 # requires 3 coordinates, separated by white space (no newlines!) // subdomain1_extent 1 1 1 # if subdomain exceeds simulation domain, it will be clipped. const std::string input_origin = parser(identifier.str()+"_origin").asString(); const std::string input_extent = parser(identifier.str()+"_extent").asString(); parser.unset_strict_mode(); std::vector<double> new_origin(0); { std::istringstream iss(input_origin); for (int coord = 0; coord < 3; ++coord) { assert(!iss.eof()); double val; iss >> val; new_origin.push_back(val); } } std::vector<double> new_extent(0); { std::istringstream iss(input_extent); for (int coord = 0; coord < 3; ++coord) { assert(!iss.eof()); double val; iss >> val; new_extent.push_back(val); } } // 2.) int idx_start[3]; int idx_end[3]; const double* h[3]; double sub_start[3]; double sub_end[3]; for (int coord = 0; coord < 3; ++coord) { const MeshMap<B>& mmap = grid.getMeshMap(coord); const double c_start = mmap.start(); const double c_end = mmap.end(); // check and reset if domain violation. assert(new_origin[coord] < c_end); assert(new_extent[coord] > 0); if (new_origin[coord] < c_start) new_origin[coord] = c_start; // set to domain start if (new_origin[coord]+new_extent[coord] > c_end) new_extent[coord] = c_end - new_origin[coord]; // clip to domain end // compute bounding box const unsigned int ncells = mmap.ncells(); const double lower_bound = new_origin[coord]; double c_vertex = c_start; for (unsigned int cell = 0; cell < ncells; ++cell) { c_vertex += mmap.cell_width(cell); if (lower_bound < c_vertex) { idx_start[coord] = cell; h[coord] = mmap.data_grid_spacing() + cell; sub_start[coord] = c_vertex - mmap.cell_width(cell); break; } } const double upper_bound = lower_bound + new_extent[coord]; c_vertex = c_end; for (int cell = ncells-1; cell >= 0; --cell) { c_vertex -= mmap.cell_width(cell); if (upper_bound > c_vertex) { idx_end[coord] = cell; sub_end[coord] = c_vertex + mmap.cell_width(cell); break; } } } subdomains.emplace_back(&grid, id, sub_start, sub_end, h, idx_start, idx_end); } return subdomains; } public: typedef TGrid GridType; // bb_start: cell index within which the bounding box start (lower left) lies // bb_end: cell index within which the bounding box end (upper right) lies Subdomain(TGrid* grid, const int id, const double start[3], const double end[3], const double* h[3], const int bb_start[3]=0, const int bb_end[3]=0) : m_grid(grid), m_id(id), m_bbox_start{bb_start[0], bb_start[1], bb_start[2]}, m_bbox_end{bb_end[0], bb_end[1], bb_end[2]}, m_subcount{0}, m_subdim{bb_end[0]-bb_start[0]+1, bb_end[1]-bb_start[1]+1, bb_end[2]-bb_start[2]+1}, m_valid(false), m_grid_spacing{h[0], h[1], h[2]}, m_start{start[0], start[1], start[2]}, m_end{end[0], end[1], end[2]} { assert(m_grid != NULL); typedef typename TGrid::BlockType TBlock; // process span std::vector<BlockInfo> infos_all = grid->getBlocksInfo(); const BlockInfo info_first = infos_all.front(); const BlockInfo info_last = infos_all.back(); const int process_start[3] = { static_cast<int>(info_first.index[0] * TBlock::sizeX), static_cast<int>(info_first.index[1] * TBlock::sizeY), static_cast<int>(info_first.index[2] * TBlock::sizeZ) }; const int process_end[3] = { static_cast<int>((info_last.index[0] + 1) * TBlock::sizeX - 1), static_cast<int>((info_last.index[1] + 1) * TBlock::sizeY - 1), static_cast<int>((info_last.index[2] + 1) * TBlock::sizeZ - 1) }; bool b_intersect[3] = { false, false, false }; for (size_t i = 0; i < 3; ++i) { // case 1: subdomain is fully contained in this process // dimension if (process_start[i] <= m_bbox_start[i] && m_bbox_end[i] <= process_end[i]) { b_intersect[i] = true; continue; } // case 2: subdomain is partially contained in this process // dimension (distributed) if (process_start[i] <= m_bbox_start[i] && m_bbox_start[i] <= process_end[i] && m_bbox_end[i] > process_end[i]) { m_bbox_end[i] = process_end[i]; b_intersect[i] = true; } else if (m_bbox_start[i] < process_start[i] && process_end[i] < m_bbox_end[i]) { m_bbox_start[i] = process_start[i]; m_bbox_end[i] = process_end[i]; b_intersect[i] = true; } else if (m_bbox_start[i] < process_start[i] && process_start[i] <= m_bbox_end[i] && m_bbox_end[i] <= process_end[i]) { m_bbox_start[i] = process_start[i]; b_intersect[i] = true; } } m_valid = true; m_max_size = 1; for (size_t i = 0; i < 3; ++i) { m_subcount[i] = m_bbox_end[i] - m_bbox_start[i] + 1; m_max_size *= static_cast<unsigned long>(m_subcount[i]); m_valid = m_valid && b_intersect[i]; } // see which blocks are needed if (m_valid) { for (size_t i = 0; i < infos_all.size(); ++i) { const BlockInfo info = infos_all[i]; const int block_start[3] = { static_cast<int>(info.index[0] * TBlock::sizeX), static_cast<int>(info.index[1] * TBlock::sizeY), static_cast<int>(info.index[2] * TBlock::sizeZ) }; const int block_end[3] = { static_cast<int>(block_start[0] + TBlock::sizeX - 1), static_cast<int>(block_start[1] + TBlock::sizeY - 1), static_cast<int>(block_start[2] + TBlock::sizeZ - 1) }; const bool b_need_X = ((block_start[0] <= m_bbox_end[0]) && (block_end[0] >= m_bbox_start[0])); const bool b_need_Y = ((block_start[1] <= m_bbox_end[1]) && (block_end[1] >= m_bbox_start[1])); const bool b_need_Z = ((block_start[2] <= m_bbox_end[2]) && (block_end[2] >= m_bbox_start[2])); if (b_need_X && b_need_Y && b_need_Z) m_intersecting_blocks.push_back( info ); } } } Subdomain(const Subdomain& c) = default; virtual ~Subdomain() = default; inline int id() const { return m_id; } inline const int (&bbox_start() const)[3] { return m_bbox_start; } inline const int (&bbox_end() const)[3] { return m_bbox_end; } inline const int (&count() const)[3] { return m_subcount; } inline const int (&dim() const)[3] { return m_subdim; } inline int dim(const size_t i) const { assert(i<3); return m_subdim[i]; } inline const double (&start() const)[3] { return m_start; } inline double start(const size_t i) const { assert(i<3); return m_start[i]; } inline const double (&end() const)[3] { return m_end; } inline double end(const size_t i) const { assert(i<3); return m_end[i]; } inline const double* grid_spacing(const size_t i) const { assert(i<3); return m_grid_spacing[i]; } inline unsigned long max_size() const { return m_max_size; } inline bool valid() const { return m_valid; } inline const std::vector<BlockInfo>& getBlocksInfo() const { return m_intersecting_blocks; } inline TGrid* getGrid() const { return m_grid; } inline std::string name() const { std::ostringstream out; out << "subdomain" << m_id; return out.str(); } virtual void show(const std::string prefix="") const { std::cout << prefix << "subdomain" << m_id << ":" << std::endl; std::cout << prefix << "ID = " << m_id << std::endl; std::cout << prefix << "START = (" << m_start[0] << ", " << m_start[1] << ", " << m_start[2] << ")" << std::endl; std::cout << prefix << "END = (" << m_end[0] << ", " << m_end[1] << ", " << m_end[2] << ")" << std::endl; std::cout << prefix << "BBOX_START = (" << m_bbox_start[0] << ", " << m_bbox_start[1] << ", " << m_bbox_start[2] << ")" << std::endl; std::cout << prefix << "BBOX_END = (" << m_bbox_end[0] << ", " << m_bbox_end[1] << ", " << m_bbox_end[2] << ")" << std::endl; std::cout << prefix << "DIM = (" << m_subdim[0] << ", " << m_subdim[1] << ", " << m_subdim[2] << ")" << std::endl; std::cout << prefix << "SUBDIM = (" << m_subcount[0] << ", " << m_subcount[1] << ", " << m_subcount[2] << ")" << std::endl; std::cout << prefix << "MAXSIZE = " << m_max_size << std::endl; std::cout << prefix << "VALID = " << m_valid << std::endl; std::cout << prefix << "NUMBER OF BLOCKS = " << m_intersecting_blocks.size() << std::endl; } protected: TGrid * m_grid; const int m_id; int m_bbox_start[3]; // local start indices of bounding box int m_bbox_end[3]; // local end indices of bounding box int m_subcount[3]; // number of elements in local subdomain int m_subdim[3]; // number of elements in global subdomain unsigned long m_max_size; bool m_valid; const double* m_grid_spacing[3]; double m_start[3]; // lower left coordinates of smallest subdomain that contains the specified origin in config file double m_end[3]; // upper right coordinates of smallest subdomain that contains the specified extent in config file std::vector<BlockInfo> m_intersecting_blocks; }; } /////////////////////////////////////////////////////////////////////////////// // Dumpers // // The following requirements for the data TStreamer are required: // TStreamer::NCHANNELS : Number of data elements (1=Scalar, 3=Vector, 9=Tensor) // TStreamer::operate : Data access methods for read and write // TStreamer::getAttributeName : Attribute name of the date ("Scalar", "Vector", "Tensor") template<typename TStreamer, typename hdf5Real, typename TSubdomain> void DumpSubdomainHDF5(const TSubdomain& subdomain, const typename TSubdomain::GridType::Real t, const std::string &fileroot, // Filename w/o folder or extension. const std::string &dirname = ".", const bool bXMF = true) { #ifdef CUBISM_USE_HDF typedef typename TSubdomain::GridType::BlockType B; std::string filename_h5 = fileroot + ".h5"; std::string fullpath_h5 = dirname + "/" + filename_h5; std::string fullpath_xmf = dirname + "/" + fileroot + ".xmf"; herr_t status; hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id; /////////////////////////////////////////////////////////////////////////// // startup file H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); file_id = H5Fcreate(fullpath_h5.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, fapl_id); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); /////////////////////////////////////////////////////////////////////////// // write mesh std::vector<int> mesh_dims; std::vector<std::string> dset_name; dset_name.push_back("/vx"); dset_name.push_back("/vy"); dset_name.push_back("/vz"); for (size_t i = 0; i < 3; ++i) { const int nCells = subdomain.dim(i); const double* const h = subdomain.grid_spacing(i); std::vector<double> vertices(nCells+1, subdomain.start(i)); mesh_dims.push_back(vertices.size()); for (int j = 0; j < nCells; ++j) vertices[j+1] = vertices[j] + h[j];; hsize_t dim[1] = {vertices.size()}; fspace_id = H5Screate_simple(1, dim, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif status = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, vertices.data()); status = H5Sclose(fspace_id); status = H5Dclose(dataset_id); } /////////////////////////////////////////////////////////////////////////// // write data std::vector<BlockInfo> infos_sub = subdomain.getBlocksInfo(); static const unsigned int NCHANNELS = TStreamer::NCHANNELS; const unsigned int NX = subdomain.count()[0]; const unsigned int NY = subdomain.count()[1]; const unsigned int NZ = subdomain.count()[2]; std::cout << "Allocating " << (subdomain.max_size() * NCHANNELS * sizeof(hdf5Real))/(1024.*1024.) << " MB of HDF5 subdomain data" << std::endl; hdf5Real * array_all = NULL; hsize_t count[4] = { NZ, NY, NX, NCHANNELS }; hsize_t dims[4] = { NZ, NY, NX, NCHANNELS }; hsize_t offset[4] = {0, 0, 0, 0}; if (subdomain.valid()) { array_all = new hdf5Real[NX * NY * NZ * NCHANNELS]; const int bbox_start[3] = { subdomain.bbox_start()[0], subdomain.bbox_start()[1], subdomain.bbox_start()[2] }; const int bbox_end[3] = { subdomain.bbox_end()[0], subdomain.bbox_end()[1], subdomain.bbox_end()[2] }; #pragma omp parallel for for(int i=0; i<(int)infos_sub.size(); i++) { BlockInfo& info = infos_sub[i]; const B& b = *(B*)info.ptrBlock; const int idx[3] = { info.index[0], info.index[1], info.index[2] }; for(int iz=0; iz<static_cast<int>(B::sizeZ); iz++) for(int iy=0; iy<static_cast<int>(B::sizeY); iy++) for(int ix=0; ix<static_cast<int>(B::sizeX); ix++) { int gx = idx[0]*B::sizeX + ix; int gy = idx[1]*B::sizeY + iy; int gz = idx[2]*B::sizeZ + iz; const bool b_containedX = (bbox_start[0] <= gx) && (gx <= bbox_end[0]); const bool b_containedY = (bbox_start[1] <= gy) && (gy <= bbox_end[1]); const bool b_containedZ = (bbox_start[2] <= gz) && (gz <= bbox_end[2]); if (!(b_containedX && b_containedY && b_containedZ)) continue; hdf5Real output[NCHANNELS]; for(unsigned int j=0; j<NCHANNELS; ++j) output[j] = 0; TStreamer::operate(b, ix, iy, iz, (hdf5Real*)output); gx -= bbox_start[0]; // shift to process local gy -= bbox_start[1]; // shift to process local gz -= bbox_start[2]; // shift to process local hdf5Real * const ptr = array_all + NCHANNELS*(gx + NX * (gy + NY * gz)); for(unsigned int j=0; j<NCHANNELS; ++j) ptr[j] = output[j]; } } } fapl_id = H5Pcreate(H5P_DATASET_XFER); fspace_id = H5Screate_simple(4, dims, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif fspace_id = H5Dget_space(dataset_id); H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); mspace_id = H5Screate_simple(4, count, NULL); if (!subdomain.valid()) { H5Sselect_none(fspace_id); H5Sselect_none(mspace_id); } status = H5Dwrite(dataset_id, get_hdf5_type<hdf5Real>(), mspace_id, fspace_id, fapl_id, array_all); if (status < 0) H5Eprint1(stdout); status = H5Sclose(mspace_id); if(status<0) H5Eprint1(stdout); status = H5Sclose(fspace_id); if(status<0) H5Eprint1(stdout); status = H5Dclose(dataset_id); if(status<0) H5Eprint1(stdout); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); status = H5Fclose(file_id); if(status<0) H5Eprint1(stdout); H5close(); if (subdomain.valid()) delete [] array_all; if (bXMF) { FILE *xmf = 0; xmf = fopen(fullpath_xmf.c_str(), "w"); fprintf(xmf, "<?xml version=\"1.0\" ?>\n"); fprintf(xmf, "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"); fprintf(xmf, "<Xdmf Version=\"2.0\">\n"); fprintf(xmf, " <Domain>\n"); fprintf(xmf, " <Grid GridType=\"Uniform\">\n"); fprintf(xmf, " <Time Value=\"%e\"/>\n\n", t); fprintf(xmf, " <Topology TopologyType=\"3DRectMesh\" Dimensions=\"%d %d %d\"/>\n\n", mesh_dims[2], mesh_dims[1], mesh_dims[0]); fprintf(xmf, " <Geometry GeometryType=\"VxVyVz\">\n"); fprintf(xmf, " <DataItem Name=\"mesh_vx\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[0]); fprintf(xmf, " %s:/vx\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vy\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[1]); fprintf(xmf, " %s:/vy\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vz\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[2]); fprintf(xmf, " %s:/vz\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Geometry>\n\n"); fprintf(xmf, " <Attribute Name=\"data\" AttributeType=\"%s\" Center=\"Cell\">\n", TStreamer::getAttributeName()); fprintf(xmf, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" Precision=\"%d\" Format=\"HDF\">\n", (int)dims[0], (int)dims[1], (int)dims[2], (int)dims[3], (int)sizeof(hdf5Real)); fprintf(xmf, " %s:/data\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Attribute>\n"); fprintf(xmf, " </Grid>\n"); fprintf(xmf, " </Domain>\n"); fprintf(xmf, "</Xdmf>\n"); fclose(xmf); } #else #warning USE OF HDF WAS DISABLED AT COMPILE TIME #endif } CUBISM_NAMESPACE_END #endif /* HDF5SUBDOMAINDUMPER_H_3C2DKYV4 */
convolution_1x1_pack8_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2020 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 conv1x1s1_sgemm_pack8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; const int size = w * h; Mat bottom_im2col = bottom_blob; bottom_im2col.w = size; bottom_im2col.h = 1; im2col_sgemm_pack8_fp16sa_neon(bottom_im2col, top_blob, kernel, _bias, opt); } static void conv1x1s2_pack8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = (w - 2 * outw + w) * 8; Mat bottom_blob_shrinked; bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < channels; p++) { const __fp16* r0 = bottom_blob.channel(p); __fp16* outptr = bottom_blob_shrinked.channel(p); for (int i = 0; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { float16x8_t _v0 = vld1q_f16(r0); float16x8_t _v1 = vld1q_f16(r0 + 16); float16x8_t _v2 = vld1q_f16(r0 + 32); float16x8_t _v3 = vld1q_f16(r0 + 48); vst1q_f16(outptr, _v0); vst1q_f16(outptr + 8, _v1); vst1q_f16(outptr + 16, _v2); vst1q_f16(outptr + 24, _v3); r0 += 64; outptr += 32; } for (; j + 1 < outw; j += 2) { float16x8_t _v0 = vld1q_f16(r0); float16x8_t _v1 = vld1q_f16(r0 + 16); vst1q_f16(outptr, _v0); vst1q_f16(outptr + 8, _v1); r0 += 32; outptr += 16; } for (; j < outw; j++) { float16x8_t _v = vld1q_f16(r0); vst1q_f16(outptr, _v); r0 += 16; outptr += 8; } r0 += tailstep; } } conv1x1s1_sgemm_pack8_fp16sa_neon(bottom_blob_shrinked, top_blob, kernel, _bias, opt); }
bubble.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> void bubble_sort(int *, unsigned long,int); void imprimir_vetor(int *, unsigned long); void verify(int *, unsigned long ); int main(int argc, char *argv[]) { struct timeval timevalA; struct timeval timevalB; int *vetor = NULL; unsigned long tam, i = 0; unsigned int numThread; if (argc != 3) { printf("%s elementos e numero de threads\n", argv[0]); exit(EXIT_FAILURE); } tam = atoi(argv[1]); numThread = atoi(argv[2]); if (!(vetor = (int *) malloc(sizeof(int) * tam))) { printf("Erro ao alocar memória\n"); exit(EXIT_FAILURE); } double sum = 0.0; srand(time(NULL)); for (int j = 0; j < 10; j++) { for (i = 0; i < tam; i++) { *(vetor + i) = random() % 10000; } gettimeofday(&timevalA, NULL); bubble_sort(vetor, tam,numThread); gettimeofday(&timevalB, NULL); double t = timevalB.tv_sec - timevalA.tv_sec + (timevalB.tv_usec - timevalA.tv_usec) / (double) 1000000; sum += t; printf("%lf\n", t); verify(vetor,tam); } printf("#\t%lf\t%u\t%lu\n", sum/10.0, numThread, tam); free(vetor); return EXIT_SUCCESS; } void bubble_sort(int *vetor, unsigned long tam, int numThread) { unsigned long i, j; int aux,start; for (i = tam; i > 0; i--) { start = i % 2; #pragma omp parallel for schedule(static) num_threads(numThread) shared(i,vetor,start,tam) private(aux,j) for (j = start; j < tam - 1; j+=2){ if (vetor[j] > vetor[j + 1]) { aux = vetor[j]; vetor[j] = vetor[j + 1]; vetor[j + 1] = aux; } } } } void imprimir_vetor(int *vetor, unsigned long tam) { unsigned long i; for (i = 0; i < tam; i++) { printf("%d\t", vetor[i]); } printf("\n"); } void verify(int *vetor, unsigned long tam){ for (int i = 0; i < tam - 1; i++) { if (vetor[i] > vetor[i+1]) { printf("TA ERRADO MANO\n"); break; } } }
DRB076-flush-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This benchmark is extracted from flush_nolist.1c of OpenMP Application Programming Interface Examples Version 4.5.0 . We privatize variable i to fix data races in the original example. Once i is privatized, flush is no longer needed. */ #include<stdio.h> #include<assert.h> void f1(int *q) { *q = 1; } int main() { int i=0, sum=0; #pragma omp parallel reduction(+:sum) num_threads(10) private(i) { f1(&i); sum+= i; } assert (sum==10); printf("sum=%d\n", sum); return 0; }
Parallelizer.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_PARALLELIZER_H #define EIGEN_PARALLELIZER_H namespace Eigen { namespace internal { /** \internal */ inline void manage_multi_threading(Action action, int *v) { static EIGEN_UNUSED int m_maxThreads = -1; if (action == SetAction) { eigen_internal_assert(v != 0); m_maxThreads = *v; } else if (action == GetAction) { eigen_internal_assert(v != 0); #ifdef EIGEN_HAS_OPENMP if (m_maxThreads > 0) *v = m_maxThreads; else *v = omp_get_max_threads(); #else *v = 1; #endif } else { eigen_internal_assert(false); } } } // namespace internal /** Must be call first when calling Eigen from multiple threads */ inline void initParallel() { int nbt; internal::manage_multi_threading(GetAction, &nbt); std::ptrdiff_t l1, l2; internal::manage_caching_sizes(GetAction, &l1, &l2); } /** \returns the max number of threads reserved for Eigen * \sa setNbThreads */ inline int nbThreads() { int ret; internal::manage_multi_threading(GetAction, &ret); return ret; } /** Sets the max number of threads reserved for Eigen * \sa nbThreads */ inline void setNbThreads(int v) { internal::manage_multi_threading(SetAction, &v); } namespace internal { template <typename Index> struct GemmParallelInfo { GemmParallelInfo() : sync(-1), users(0), rhs_start(0), rhs_length(0) {} int volatile sync; int volatile users; Index rhs_start; Index rhs_length; }; template <bool Condition, typename Functor, typename Index> void parallelize_gemm(const Functor &func, Index rows, Index cols, bool transpose) { // TODO when EIGEN_USE_BLAS is defined, // we should still enable OMP for other scalar types #if !(defined(EIGEN_HAS_OPENMP)) || defined(EIGEN_USE_BLAS) // FIXME the transpose variable is only needed to properly split // the matrix product when multithreading is enabled. This is a temporary // fix to support row-major destination matrices. This whole // parallelizer mechanism has to be redisigned anyway. EIGEN_UNUSED_VARIABLE(transpose); func(0, rows, 0, cols); #else // Dynamically check whether we should enable or disable OpenMP. // The conditions are: // - the max number of threads we can create is greater than 1 // - we are not already in a parallel code // - the sizes are large enough // 1- are we already in a parallel session? // FIXME omp_get_num_threads()>1 only works for openmp, what if the user // does not use openmp? if ((!Condition) || (omp_get_num_threads() > 1)) return func(0, rows, 0, cols); Index size = transpose ? cols : rows; // 2- compute the maximal number of threads from the size of the product: // FIXME this has to be fine tuned Index max_threads = std::max<Index>(1, size / 32); // 3 - compute the number of threads we are going to use Index threads = std::min<Index>(nbThreads(), max_threads); if (threads == 1) return func(0, rows, 0, cols); Eigen::initParallel(); func.initParallelSession(); if (transpose) std::swap(rows, cols); Index blockCols = (cols / threads) & ~Index(0x3); Index blockRows = (rows / threads) & ~Index(0x7); GemmParallelInfo<Index> *info = new GemmParallelInfo<Index>[threads]; #pragma omp parallel for schedule(static, 1) num_threads(threads) for (Index i = 0; i < threads; ++i) { Index r0 = i * blockRows; Index actualBlockRows = (i + 1 == threads) ? rows - r0 : blockRows; Index c0 = i * blockCols; Index actualBlockCols = (i + 1 == threads) ? cols - c0 : blockCols; info[i].rhs_start = c0; info[i].rhs_length = actualBlockCols; if (transpose) func(0, cols, r0, actualBlockRows, info); else func(r0, actualBlockRows, 0, cols, info); } delete[] info; #endif } } // end namespace internal } // end namespace Eigen #endif // EIGEN_PARALLELIZER_H
core_dgemm.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_zgemm.c, normal z -> d, Fri Sep 28 17:38:18 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" #include <omp.h> /***************************************************************************//** * * @ingroup core_gemm * * Performs one of the matrix-matrix operations * * \f[ C = \alpha [op( A )\times op( B )] + \beta C, \f] * * where op( X ) is one of: * \f[ op( X ) = X, \f] * \f[ op( X ) = X^T, \f] * \f[ op( X ) = X^T, \f] * * alpha and beta are scalars, and A, B and C are matrices, with op( A ) * an m-by-k matrix, op( B ) a k-by-n matrix and C an m-by-n matrix. * ******************************************************************************* * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] transb * - PlasmaNoTrans: B is not transposed, * - PlasmaTrans: B is transposed, * - PlasmaConjTrans: B is conjugate transposed. * * @param[in] m * The number of rows of the matrix op( A ) and of the matrix C. * m >= 0. * * @param[in] n * The number of columns of the matrix op( B ) and of the matrix C. * n >= 0. * * @param[in] k * The number of columns of the matrix op( A ) and the number of rows * of the matrix op( B ). k >= 0. * * @param[in] alpha * The scalar alpha. * * @param[in] A * An lda-by-ka matrix, where ka is k when transa = PlasmaNoTrans, * and is m otherwise. * * @param[in] lda * The leading dimension of the array A. * When transa = PlasmaNoTrans, lda >= max(1,m), * otherwise, lda >= max(1,k). * * @param[in] B * An ldb-by-kb matrix, where kb is n when transb = PlasmaNoTrans, * and is k otherwise. * * @param[in] ldb * The leading dimension of the array B. * When transb = PlasmaNoTrans, ldb >= max(1,k), * otherwise, ldb >= max(1,n). * * @param[in] beta * The scalar beta. * * @param[in,out] C * An ldc-by-n matrix. On exit, the array is overwritten by the m-by-n * matrix ( alpha*op( A )*op( B ) + beta*C ). * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1,m). * ******************************************************************************/ __attribute__((weak)) void plasma_core_dgemm(plasma_enum_t transa, plasma_enum_t transb, int m, int n, int k, double alpha, const double *A, int lda, const double *B, int ldb, double beta, double *C, int ldc) { cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transa, (CBLAS_TRANSPOSE)transb, m, n, k, (alpha), A, lda, B, ldb, (beta), C, ldc); } /******************************************************************************/ void plasma_core_omp_dgemm( plasma_enum_t transa, plasma_enum_t transb, int m, 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; if (transa == PlasmaNoTrans) ak = k; else ak = m; int bk; if (transb == PlasmaNoTrans) bk = n; else bk = k; if (sequence->status == PlasmaSuccess) { int transa_ = transa, transb_ = transb; int size_A = lda*ak, size_B = ldb*bk,size_C =ldc*n; #pragma omp target nowait \ depend(in:A[0:lda*ak]) \ depend(in:B[0:ldb*bk]) \ depend(inout:C[0:ldc*n]) \ firstprivate(m,n,k,alpha,beta,lda,ak) \ firstprivate(ldb,bk,ldc,transa_,transb_) \ map(to:A[0:size_A],B[0:size_B]) \ map(tofrom:C[0:size_C]) { int block_size = 4, size_matrix = lda; int m_new = m/block_size; int n_new = n/block_size; int k_new = k/block_size; int zbeta; #pragma omp parallel #pragma omp single { for (int m_ = 0; m_ < m_new; m_++){ for (int n_ = 0; n_ < n_new; n_++) { for (int k_ = 0; k_ < k_new; k_++) { int lda_ = m_ * block_size + k_ * block_size; int ldb_ = k_ * block_size + n_ * block_size; int ldc_ = m_ * block_size + n_ * block_size; #pragma omp task \ depend(inout:C[ldc_]) { double A_new [block_size*block_size],B_new[block_size*block_size],C_new[block_size*block_size]; int i_a = m_, j_a=k_; int i_b = k_, j_b=n_; int i_c = m_, j_c=n_; int insert = 0; for(int l=0;l<block_size;l++) { int before_a = i_a*block_size+j_a*lda*block_size + l*size_matrix; int before_b = i_b*block_size+j_b*lda*block_size + l*size_matrix; int before_c = i_c*block_size+j_c*lda*block_size + l*size_matrix; for (int i = 0; i < block_size; i++) { A_new[insert] = A[before_a]; B_new[insert] = B[before_b]; C_new[insert] = C[before_c]; insert += 1; before_a += 1; before_b += 1; before_c += 1; } } double zbeta = k_== 0 ? beta : 1.0; plasma_core_dgemm(transa_, transb_, block_size, block_size, block_size, alpha, (const double *) A_new, block_size, (const double *) B_new, block_size, zbeta, (double *) C_new, block_size); insert = 0; for(int l=0;l<block_size;l++) { int before_c = i_c*block_size+j_c*lda*block_size + l*size_matrix; for (int i = 0; i < block_size; i++) { C[before_c]=C_new[insert]; insert += 1; before_c += 1; } } } } } } } } } }
Vector.h
/* * Vector.h * * Created on: 12.03.2014 * Author: Michael Wegner (michael.wegner@student.kit.edu) */ #ifndef VECTOR_H_ #define VECTOR_H_ #include <vector> #include "../Globals.h" namespace NetworKit { // forward declaration of Matrix class class Matrix; /** * @ingroup algebraic * The Vector class represents a basic vector with double coefficients. */ class Vector { private: std::vector<double> values; bool transposed; public: /** Default constructor */ Vector(); /** * Constructs the Vector with @a dimension elements with value @a initialValue. * @param dimension The dimension of this vector. * @param initialValue All coefficients will be initialized to @a initialValue. * @param transpose Indicates whether this vector is transposed (row vector) or not (column vector). */ Vector(const count dimension, const double initialValue = 0, const bool transpose = false); /** * Constructs the Vector with the contents of @a values. * @param values The values of this Vector. * @param transpose Indicates whether this vector is transposed (row vector) or not (column vector). */ Vector(const std::vector<double> &values, const bool transpose = false); /** * Constructs the Vector from the contents of the initializer list @a list. * @param list The initializer list. */ Vector(const std::initializer_list<double> &list); /** Copy constructor */ Vector(const Vector &other); /** * @return dimension of vector */ inline count getDimension() const { return values.size(); } /** * A transposed vector is a row vector. * @return True, if this vector is transposed, otherwise false. */ bool isTransposed() const; /** * @return Transposed copy of this vector. */ Vector transpose() const; /** * Calculates and returns the Euclidean length of this vector * @return The Euclidean length of this vector. */ double length() const; /** * Returns a reference to the element at index @a idx without checking the range of this vector. * @param idx The index of the element. * @return Reference to the element at index @a idx. */ inline double& operator[](const index idx) { return values[idx]; } /** * Returns a constant reference to the element at index @a idx without checking the range of this vector. * @a idx The index of the element. * @return Constant reference to the element at index @a idx. */ inline const double& operator[](const index idx) const { return values[idx]; } /** * Returns a reference to the element at index @a idx. If @a idx is not a valid index an exception is thrown. * @param idx The index of the element. * @return Reference to the element at index @a idx. */ double &at(const index idx) { if (idx >= values.size()) { throw std::runtime_error("index out of range"); } else { return values[idx]; } } /** * Returns a constant reference to the element at index @a idx. If @a idx is not a valid index an exception is thrown. * @param idx The index of the element. * @return Reference to the element at index @a idx. */ const double &at(const index idx) const { if (idx >= values.size()) { throw std::runtime_error("index out of range"); } else { return values[idx]; } } /** * Compares this vector and @a other element-wise. * @return True, if this vector is element-wise equal to @a other, otherwise false. */ bool operator==(const Vector &other) const; /** * Compares this vector and @a other element-wise. * @return True, if this vector is element-wise unequal to @a other, otherwise false. */ bool operator!=(const Vector &other) const; /** * Computes the outer product of @a v1 and @a v2. * @param v1 First Vector. * @param v2 Second Vector. * @return The resulting matrix from the outer product. */ static Matrix outerProduct(const Vector &v1, const Vector &v2); /** * Computes the inner product (dot product) of the vectors @a v1 and @a v2. * @return The result of the inner product. */ static double innerProduct(const Vector &v1, const Vector &v2); /** * Computes the inner product (dot product) of this vector and @a other. * @return The result of the inner product. */ double operator*(const Vector &other) const; /** * Multiplies this vector with @a matrix and returns the result. * @return The result of multiplying this vector with @a matrix. */ Vector operator*(const Matrix &matrix) const; /** * Multiplies this vector with a scalar specified in @a scalar and returns the result in a new vector. * @return The result of multiplying this vector with @a scalar. */ Vector operator*(const double &scalar) const; /** * Multiplies this vector with a scalar specified in @a scalar. * @return Reference to this vector. */ Vector& operator*=(const double &scalar); /** * Divides this vector by a divisor specified in @a divisor and returns the result in a new vector. * @return The result of dividing this vector by @a divisor. */ Vector operator/(const double &divisor) const; /** * Divides this vector by a divisor specified in @a divisor. * @return Reference to this vector. */ Vector& operator/=(const double &divisor); /** * Adds this vector to @a other and returns the result. * Note that the dimensions of the vectors have to be the same. * @return The sum of this vector and @a other. */ Vector operator+(const Vector &other) const; /** * Adds @a other to this vector. * Note that the dimensions of the vectors have to be the same. * @return Reference to this vector. */ Vector& operator+=(const Vector &other); /** * Subtracts @a other from this vector and returns the result. * Note that the dimensions of the vectors have to be the same. * @return The difference of this vector and @a other. * */ Vector operator-(const Vector &other) const; /** * Subtracts @a other from this vector. * Note that the dimensions of the vectors have to be the same. * @return Reference to this vector. */ Vector& operator-=(const Vector &other); /** * Iterate over all elements of the vector and call handler (lambda closure). */ template<typename L> void forElements(L handle); /** * Iterate over all elements of the vector and call handler (lambda closure). */ template<typename L> void forElements(L handle) const; /** * Iterate in parallel over all elements of the vector and call handler (lambda closure). * */ template<typename L> void parallelForElements(L handle); /** * Iterate in parallel over all elements of the vector and call handler (lambda closure). */ template<typename L> void parallelForElements(L handle) const; }; } /* namespace NetworKit */ /** * Multiplies the vector @a v with a scalar specified in @a scalar and returns the result. * @return The result of multiplying this vector with @a scalar. */ inline NetworKit::Vector operator*(const double &scalar, const NetworKit::Vector &v) { return v.operator*(scalar); } template<typename L> inline void NetworKit::Vector::forElements(L handle) { for (uint64_t i = 0; i < getDimension(); i++) { handle(values[i]); } } template<typename L> inline void NetworKit::Vector::forElements(L handle) const { for (uint64_t i = 0; i < getDimension(); i++) { handle(values[i]); } } template<typename L> inline void NetworKit::Vector::parallelForElements(L handle) { #pragma omp parallel for for (uint64_t i = 0; i < getDimension(); i++) { handle(i, values[i]); } } template<typename L> inline void NetworKit::Vector::parallelForElements(L handle) const { #pragma omp parallel for for (uint64_t i = 0; i < getDimension(); i++) { handle(i, values[i]); } } #endif /* VECTOR_H_ */
GB_unop__identity_int8_int32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int8_int32) // op(A') function: GB (_unop_tran__identity_int8_int32) // C type: int8_t // A type: int32_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_t) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int8_int32) ( int8_t *Cx, // Cx and Ax may be aliased const int32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (int32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int32_t aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int8_int32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__ne_fp64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__ne_fp64) // A.*B function (eWiseMult): GB (_AemultB_08__ne_fp64) // A.*B function (eWiseMult): GB (_AemultB_02__ne_fp64) // A.*B function (eWiseMult): GB (_AemultB_04__ne_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_fp64) // A*D function (colscale): GB (_AxD__ne_fp64) // D*A function (rowscale): GB (_DxB__ne_fp64) // C+=B function (dense accum): GB (_Cdense_accumB__ne_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__ne_fp64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_fp64) // C=scalar+B GB (_bind1st__ne_fp64) // C=scalar+B' GB (_bind1st_tran__ne_fp64) // C=A+scalar GB (_bind2nd__ne_fp64) // C=A'+scalar GB (_bind2nd_tran__ne_fp64) // C type: bool // A type: double // A pattern? 0 // B type: double // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ double aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ double bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_NE || GxB_NO_FP64 || GxB_NO_NE_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__ne_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__ne_fp64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ne_fp64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type double double bwork = (*((double *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__ne_fp64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ne_fp64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ne_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__ne_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__ne_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__ne_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__ne_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__ne_fp64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; double bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ne_fp64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__ne_fp64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__ne_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
Homography.h
#pragma once #include "saiga/vision/VisionTypes.h" #include "saiga/vision/util/Ransac.h" #include <array> // This code here is inspired (and partially copied) from Colmap. // https://github.com/colmap/colmap namespace Saiga { /** * Calculates a 3x3 homography matrix H so that * targetPoints[i] = H * sourcePoints[i] * This mapping is in 2d projective space -> H is up to a scale */ SAIGA_VISION_API Mat3 homography(ArrayView<const Vec2> points1, ArrayView<const Vec2> points2); /** * The transformation error for a corresponding point pair. */ inline double homographyResidual(const Vec2& p1, const Vec2& p2, const Mat3& H) { Vec3 p = H * p1.homogeneous(); double invz = 1.0 / p(2); Vec2 res(p2(0) - p(0) * invz, p2(1) - p(1) * invz); return res.squaredNorm(); } #if 0 // solves H = aK * [R|t] for [R|t] CameraExtrinsics getExtrinsicsFromHomography(const CameraIntrinsics& camera, const mat3d_t& H); // solves H = a[R|t] for [R|t] CameraExtrinsics getExtrinsicsFromHomography(const mat3d_t& H); mat3d_t homographyRANSAC(const std::vector<vec2d_t>& sourcePoints, const std::vector<vec2d_t>& targetPoints, std::vector<int>& outInliers, int numIterations = 1000, double inlierThreshold = 5, int numSamples = 4); #endif class SAIGA_VISION_API HomographyRansac : public RansacBase<HomographyRansac, Mat3, 4> { using Base = RansacBase<HomographyRansac, Mat3, 4>; using Model = Mat3; public: HomographyRansac(const RansacParameters& params) : Base(params) {} int solve(ArrayView<const Vec2> _points1, ArrayView<const Vec2> _points2, Mat3& bestH) { points1 = _points1; points2 = _points2; int idx; #pragma omp parallel num_threads(params.threads) { idx = compute(points1.size()); } bestH = models[idx]; return numInliers[idx]; } bool computeModel(const Subset& set, Model& model) { std::array<Vec2, 4> p1; std::array<Vec2, 4> p2; for (auto i : Range(0, (int)set.size())) { p1[i] = points1[set[i]]; p2[i] = points2[set[i]]; } model = homography(p1, p2); return true; } double computeResidual(const Model& model, int i) { return homographyResidual(points1[i], points2[i], model); } ArrayView<const Vec2> points1; ArrayView<const Vec2> points2; }; } // namespace Saiga
conv7x7s2_pack1to4_neon.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 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. #include "option.h" #include "mat.h" namespace ncnn{ static void conv7x7s2_pack1to4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out0 = top_blob.channel(p); float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f); out0.fill(_bias0); for (int q=0; q<inch; q++) { float* outptr0 = out0.row(0); const Mat img0 = bottom_blob.channel(q); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); const float* r3 = img0.row(3); const float* r4 = img0.row(4); const float* r5 = img0.row(5); const float* r6 = img0.row(6); const float* kptr = (const float*)kernel.channel(p).row(q); int i = 0; for (; i < outh; i++) { int j = 0; #if __aarch64__ for (; j+7<outw; j+=8) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%0], #64 \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"// r0 "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "prfm pldl1keep, [%0, #512] \n" "ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%0] \n" "fmla v20.4s, v24.4s, v2.s[0] \n" "fmla v21.4s, v24.4s, v2.s[2] \n" "fmla v22.4s, v24.4s, v3.s[0] \n" "fmla v23.4s, v24.4s, v3.s[2] \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v4.4s, v5.4s}, [%1] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v20.4s, v25.4s, v2.s[1] \n" "fmla v21.4s, v25.4s, v2.s[3] \n" "fmla v22.4s, v25.4s, v3.s[1] \n" "fmla v23.4s, v25.4s, v3.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "fmla v20.4s, v26.4s, v2.s[2] \n" "fmla v21.4s, v26.4s, v3.s[0] \n" "fmla v22.4s, v26.4s, v3.s[2] \n" "fmla v23.4s, v26.4s, v4.s[0] \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v20.4s, v27.4s, v2.s[3] \n" "fmla v21.4s, v27.4s, v3.s[1] \n" "fmla v22.4s, v27.4s, v3.s[3] \n" "fmla v23.4s, v27.4s, v4.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "fmla v20.4s, v28.4s, v3.s[0] \n" "fmla v21.4s, v28.4s, v3.s[2] \n" "fmla v22.4s, v28.4s, v4.s[0] \n" "fmla v23.4s, v28.4s, v4.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v20.4s, v29.4s, v3.s[1] \n" "fmla v21.4s, v29.4s, v3.s[3] \n" "fmla v22.4s, v29.4s, v4.s[1] \n" "fmla v23.4s, v29.4s, v4.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%2], #64 \n"// r1 "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "fmla v20.4s, v30.4s, v3.s[2] \n" "fmla v21.4s, v30.4s, v4.s[0] \n" "fmla v22.4s, v30.4s, v4.s[2] \n" "fmla v23.4s, v30.4s, v5.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v16.4s, v24.4s, v6.s[0] \n" "fmla v17.4s, v24.4s, v6.s[2] \n" "fmla v18.4s, v24.4s, v7.s[0] \n" "fmla v19.4s, v24.4s, v7.s[2] \n" "fmla v20.4s, v24.4s, v8.s[0] \n" "fmla v21.4s, v24.4s, v8.s[2] \n" "fmla v22.4s, v24.4s, v9.s[0] \n" "fmla v23.4s, v24.4s, v9.s[2] \n" "fmla v16.4s, v25.4s, v6.s[1] \n" "fmla v17.4s, v25.4s, v6.s[3] \n" "fmla v18.4s, v25.4s, v7.s[1] \n" "fmla v19.4s, v25.4s, v7.s[3] \n" "fmla v20.4s, v25.4s, v8.s[1] \n" "fmla v21.4s, v25.4s, v8.s[3] \n" "fmla v22.4s, v25.4s, v9.s[1] \n" "fmla v23.4s, v25.4s, v9.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v6.s[2] \n" "fmla v17.4s, v26.4s, v7.s[0] \n" "fmla v18.4s, v26.4s, v7.s[2] \n" "fmla v19.4s, v26.4s, v8.s[0] \n" "fmla v20.4s, v26.4s, v8.s[2] \n" "fmla v21.4s, v26.4s, v9.s[0] \n" "fmla v22.4s, v26.4s, v9.s[2] \n" "fmla v23.4s, v26.4s, v10.s[0] \n" "fmla v16.4s, v27.4s, v6.s[3] \n" "fmla v17.4s, v27.4s, v7.s[1] \n" "fmla v18.4s, v27.4s, v7.s[3] \n" "fmla v19.4s, v27.4s, v8.s[1] \n" "fmla v20.4s, v27.4s, v8.s[3] \n" "fmla v21.4s, v27.4s, v9.s[1] \n" "fmla v22.4s, v27.4s, v9.s[3] \n" "fmla v23.4s, v27.4s, v10.s[1] \n" "fmla v16.4s, v28.4s, v7.s[0] \n" "fmla v17.4s, v28.4s, v7.s[2] \n" "fmla v18.4s, v28.4s, v8.s[0] \n" "fmla v19.4s, v28.4s, v8.s[2] \n" "fmla v20.4s, v28.4s, v9.s[0] \n" "fmla v21.4s, v28.4s, v9.s[2] \n" "fmla v22.4s, v28.4s, v10.s[0] \n" "fmla v23.4s, v28.4s, v10.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v7.s[1] \n" "fmla v17.4s, v29.4s, v7.s[3] \n" "fmla v18.4s, v29.4s, v8.s[1] \n" "fmla v19.4s, v29.4s, v8.s[3] \n" "fmla v20.4s, v29.4s, v9.s[1] \n" "fmla v21.4s, v29.4s, v9.s[3] \n" "fmla v22.4s, v29.4s, v10.s[1] \n" "fmla v23.4s, v29.4s, v10.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r2 "fmla v16.4s, v30.4s, v7.s[2] \n" "fmla v17.4s, v30.4s, v8.s[0] \n" "fmla v18.4s, v30.4s, v8.s[2] \n" "fmla v19.4s, v30.4s, v9.s[0] \n" "fmla v20.4s, v30.4s, v9.s[2] \n" "fmla v21.4s, v30.4s, v10.s[0] \n" "fmla v22.4s, v30.4s, v10.s[2] \n" "fmla v23.4s, v30.4s, v11.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v4.4s, v5.4s}, [%3] \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "fmla v20.4s, v24.4s, v2.s[0] \n" "fmla v21.4s, v24.4s, v2.s[2] \n" "fmla v22.4s, v24.4s, v3.s[0] \n" "fmla v23.4s, v24.4s, v3.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v20.4s, v25.4s, v2.s[1] \n" "fmla v21.4s, v25.4s, v2.s[3] \n" "fmla v22.4s, v25.4s, v3.s[1] \n" "fmla v23.4s, v25.4s, v3.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "fmla v20.4s, v26.4s, v2.s[2] \n" "fmla v21.4s, v26.4s, v3.s[0] \n" "fmla v22.4s, v26.4s, v3.s[2] \n" "fmla v23.4s, v26.4s, v4.s[0] \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v20.4s, v27.4s, v2.s[3] \n" "fmla v21.4s, v27.4s, v3.s[1] \n" "fmla v22.4s, v27.4s, v3.s[3] \n" "fmla v23.4s, v27.4s, v4.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "fmla v20.4s, v28.4s, v3.s[0] \n" "fmla v21.4s, v28.4s, v3.s[2] \n" "fmla v22.4s, v28.4s, v4.s[0] \n" "fmla v23.4s, v28.4s, v4.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v20.4s, v29.4s, v3.s[1] \n" "fmla v21.4s, v29.4s, v3.s[3] \n" "fmla v22.4s, v29.4s, v4.s[1] \n" "fmla v23.4s, v29.4s, v4.s[3] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%4], #64 \n"// r3 "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "fmla v20.4s, v30.4s, v3.s[2] \n" "fmla v21.4s, v30.4s, v4.s[0] \n" "fmla v22.4s, v30.4s, v4.s[2] \n" "fmla v23.4s, v30.4s, v5.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v10.4s, v11.4s}, [%4] \n" "fmla v16.4s, v24.4s, v6.s[0] \n" "fmla v17.4s, v24.4s, v6.s[2] \n" "fmla v18.4s, v24.4s, v7.s[0] \n" "fmla v19.4s, v24.4s, v7.s[2] \n" "fmla v20.4s, v24.4s, v8.s[0] \n" "fmla v21.4s, v24.4s, v8.s[2] \n" "fmla v22.4s, v24.4s, v9.s[0] \n" "fmla v23.4s, v24.4s, v9.s[2] \n" "fmla v16.4s, v25.4s, v6.s[1] \n" "fmla v17.4s, v25.4s, v6.s[3] \n" "fmla v18.4s, v25.4s, v7.s[1] \n" "fmla v19.4s, v25.4s, v7.s[3] \n" "fmla v20.4s, v25.4s, v8.s[1] \n" "fmla v21.4s, v25.4s, v8.s[3] \n" "fmla v22.4s, v25.4s, v9.s[1] \n" "fmla v23.4s, v25.4s, v9.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v6.s[2] \n" "fmla v17.4s, v26.4s, v7.s[0] \n" "fmla v18.4s, v26.4s, v7.s[2] \n" "fmla v19.4s, v26.4s, v8.s[0] \n" "fmla v20.4s, v26.4s, v8.s[2] \n" "fmla v21.4s, v26.4s, v9.s[0] \n" "fmla v22.4s, v26.4s, v9.s[2] \n" "fmla v23.4s, v26.4s, v10.s[0] \n" "fmla v16.4s, v27.4s, v6.s[3] \n" "fmla v17.4s, v27.4s, v7.s[1] \n" "fmla v18.4s, v27.4s, v7.s[3] \n" "fmla v19.4s, v27.4s, v8.s[1] \n" "fmla v20.4s, v27.4s, v8.s[3] \n" "fmla v21.4s, v27.4s, v9.s[1] \n" "fmla v22.4s, v27.4s, v9.s[3] \n" "fmla v23.4s, v27.4s, v10.s[1] \n" "fmla v16.4s, v28.4s, v7.s[0] \n" "fmla v17.4s, v28.4s, v7.s[2] \n" "fmla v18.4s, v28.4s, v8.s[0] \n" "fmla v19.4s, v28.4s, v8.s[2] \n" "fmla v20.4s, v28.4s, v9.s[0] \n" "fmla v21.4s, v28.4s, v9.s[2] \n" "fmla v22.4s, v28.4s, v10.s[0] \n" "fmla v23.4s, v28.4s, v10.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v7.s[1] \n" "fmla v17.4s, v29.4s, v7.s[3] \n" "fmla v18.4s, v29.4s, v8.s[1] \n" "fmla v19.4s, v29.4s, v8.s[3] \n" "fmla v20.4s, v29.4s, v9.s[1] \n" "fmla v21.4s, v29.4s, v9.s[3] \n" "fmla v22.4s, v29.4s, v10.s[1] \n" "fmla v23.4s, v29.4s, v10.s[3] \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"// r4 "fmla v16.4s, v30.4s, v7.s[2] \n" "fmla v17.4s, v30.4s, v8.s[0] \n" "fmla v18.4s, v30.4s, v8.s[2] \n" "fmla v19.4s, v30.4s, v9.s[0] \n" "fmla v20.4s, v30.4s, v9.s[2] \n" "fmla v21.4s, v30.4s, v10.s[0] \n" "fmla v22.4s, v30.4s, v10.s[2] \n" "fmla v23.4s, v30.4s, v11.s[0] \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v4.4s, v5.4s}, [%5] \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "fmla v20.4s, v24.4s, v2.s[0] \n" "fmla v21.4s, v24.4s, v2.s[2] \n" "fmla v22.4s, v24.4s, v3.s[0] \n" "fmla v23.4s, v24.4s, v3.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v20.4s, v25.4s, v2.s[1] \n" "fmla v21.4s, v25.4s, v2.s[3] \n" "fmla v22.4s, v25.4s, v3.s[1] \n" "fmla v23.4s, v25.4s, v3.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "fmla v20.4s, v26.4s, v2.s[2] \n" "fmla v21.4s, v26.4s, v3.s[0] \n" "fmla v22.4s, v26.4s, v3.s[2] \n" "fmla v23.4s, v26.4s, v4.s[0] \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v20.4s, v27.4s, v2.s[3] \n" "fmla v21.4s, v27.4s, v3.s[1] \n" "fmla v22.4s, v27.4s, v3.s[3] \n" "fmla v23.4s, v27.4s, v4.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "fmla v20.4s, v28.4s, v3.s[0] \n" "fmla v21.4s, v28.4s, v3.s[2] \n" "fmla v22.4s, v28.4s, v4.s[0] \n" "fmla v23.4s, v28.4s, v4.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v20.4s, v29.4s, v3.s[1] \n" "fmla v21.4s, v29.4s, v3.s[3] \n" "fmla v22.4s, v29.4s, v4.s[1] \n" "fmla v23.4s, v29.4s, v4.s[3] \n" "prfm pldl1keep, [%6, #512] \n" "ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%6], #64 \n"// r5 "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "fmla v20.4s, v30.4s, v3.s[2] \n" "fmla v21.4s, v30.4s, v4.s[0] \n" "fmla v22.4s, v30.4s, v4.s[2] \n" "fmla v23.4s, v30.4s, v5.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v10.4s, v11.4s}, [%6] \n" "fmla v16.4s, v24.4s, v6.s[0] \n" "fmla v17.4s, v24.4s, v6.s[2] \n" "fmla v18.4s, v24.4s, v7.s[0] \n" "fmla v19.4s, v24.4s, v7.s[2] \n" "fmla v20.4s, v24.4s, v8.s[0] \n" "fmla v21.4s, v24.4s, v8.s[2] \n" "fmla v22.4s, v24.4s, v9.s[0] \n" "fmla v23.4s, v24.4s, v9.s[2] \n" "fmla v16.4s, v25.4s, v6.s[1] \n" "fmla v17.4s, v25.4s, v6.s[3] \n" "fmla v18.4s, v25.4s, v7.s[1] \n" "fmla v19.4s, v25.4s, v7.s[3] \n" "fmla v20.4s, v25.4s, v8.s[1] \n" "fmla v21.4s, v25.4s, v8.s[3] \n" "fmla v22.4s, v25.4s, v9.s[1] \n" "fmla v23.4s, v25.4s, v9.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v6.s[2] \n" "fmla v17.4s, v26.4s, v7.s[0] \n" "fmla v18.4s, v26.4s, v7.s[2] \n" "fmla v19.4s, v26.4s, v8.s[0] \n" "fmla v20.4s, v26.4s, v8.s[2] \n" "fmla v21.4s, v26.4s, v9.s[0] \n" "fmla v22.4s, v26.4s, v9.s[2] \n" "fmla v23.4s, v26.4s, v10.s[0] \n" "fmla v16.4s, v27.4s, v6.s[3] \n" "fmla v17.4s, v27.4s, v7.s[1] \n" "fmla v18.4s, v27.4s, v7.s[3] \n" "fmla v19.4s, v27.4s, v8.s[1] \n" "fmla v20.4s, v27.4s, v8.s[3] \n" "fmla v21.4s, v27.4s, v9.s[1] \n" "fmla v22.4s, v27.4s, v9.s[3] \n" "fmla v23.4s, v27.4s, v10.s[1] \n" "fmla v16.4s, v28.4s, v7.s[0] \n" "fmla v17.4s, v28.4s, v7.s[2] \n" "fmla v18.4s, v28.4s, v8.s[0] \n" "fmla v19.4s, v28.4s, v8.s[2] \n" "fmla v20.4s, v28.4s, v9.s[0] \n" "fmla v21.4s, v28.4s, v9.s[2] \n" "fmla v22.4s, v28.4s, v10.s[0] \n" "fmla v23.4s, v28.4s, v10.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v7.s[1] \n" "fmla v17.4s, v29.4s, v7.s[3] \n" "fmla v18.4s, v29.4s, v8.s[1] \n" "fmla v19.4s, v29.4s, v8.s[3] \n" "fmla v20.4s, v29.4s, v9.s[1] \n" "fmla v21.4s, v29.4s, v9.s[3] \n" "fmla v22.4s, v29.4s, v10.s[1] \n" "fmla v23.4s, v29.4s, v10.s[3] \n" "prfm pldl1keep, [%7, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%7], #64 \n"// r6 "fmla v16.4s, v30.4s, v7.s[2] \n" "fmla v17.4s, v30.4s, v8.s[0] \n" "fmla v18.4s, v30.4s, v8.s[2] \n" "fmla v19.4s, v30.4s, v9.s[0] \n" "fmla v20.4s, v30.4s, v9.s[2] \n" "fmla v21.4s, v30.4s, v10.s[0] \n" "fmla v22.4s, v30.4s, v10.s[2] \n" "fmla v23.4s, v30.4s, v11.s[0] \n" "prfm pldl1keep, [%7, #256] \n" "ld1 {v4.4s, v5.4s}, [%7] \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "fmla v20.4s, v24.4s, v2.s[0] \n" "fmla v21.4s, v24.4s, v2.s[2] \n" "fmla v22.4s, v24.4s, v3.s[0] \n" "fmla v23.4s, v24.4s, v3.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v20.4s, v25.4s, v2.s[1] \n" "fmla v21.4s, v25.4s, v2.s[3] \n" "fmla v22.4s, v25.4s, v3.s[1] \n" "fmla v23.4s, v25.4s, v3.s[3] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "fmla v20.4s, v26.4s, v2.s[2] \n" "fmla v21.4s, v26.4s, v3.s[0] \n" "fmla v22.4s, v26.4s, v3.s[2] \n" "fmla v23.4s, v26.4s, v4.s[0] \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v20.4s, v27.4s, v2.s[3] \n" "fmla v21.4s, v27.4s, v3.s[1] \n" "fmla v22.4s, v27.4s, v3.s[3] \n" "fmla v23.4s, v27.4s, v4.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "fmla v20.4s, v28.4s, v3.s[0] \n" "fmla v21.4s, v28.4s, v3.s[2] \n" "fmla v22.4s, v28.4s, v4.s[0] \n" "fmla v23.4s, v28.4s, v4.s[2] \n" "sub %0, %0, #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v20.4s, v29.4s, v3.s[1] \n" "fmla v21.4s, v29.4s, v3.s[3] \n" "fmla v22.4s, v29.4s, v4.s[1] \n" "fmla v23.4s, v29.4s, v4.s[3] \n" "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "fmla v20.4s, v30.4s, v3.s[2] \n" "fmla v21.4s, v30.4s, v4.s[0] \n" "fmla v22.4s, v30.4s, v4.s[2] \n" "fmla v23.4s, v30.4s, v5.s[0] \n" "sub %8, %8, #784 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%0], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v24", "v25", "v26", "v27", "v28", "v29", "v30" ); } #endif // __aarch64__ for (; j+3<outw; j+=4) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%0] \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1] \n"// r0 "add %1, %1, #32 \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2] \n"// r1 "add %2, %2, #32 \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v24.4s, v4.s[2] \n" "fmla v18.4s, v24.4s, v5.s[0] \n" "fmla v19.4s, v24.4s, v5.s[2] \n" "fmla v16.4s, v25.4s, v4.s[1] \n" "fmla v17.4s, v25.4s, v4.s[3] \n" "fmla v18.4s, v25.4s, v5.s[1] \n" "fmla v19.4s, v25.4s, v5.s[3] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "fmla v17.4s, v26.4s, v5.s[0] \n" "fmla v18.4s, v26.4s, v5.s[2] \n" "fmla v19.4s, v26.4s, v6.s[0] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3] \n"// r2 "add %3, %3, #32 \n" "fmla v16.4s, v27.4s, v4.s[3] \n" "fmla v17.4s, v27.4s, v5.s[1] \n" "fmla v18.4s, v27.4s, v5.s[3] \n" "fmla v19.4s, v27.4s, v6.s[1] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "fmla v17.4s, v28.4s, v5.s[2] \n" "fmla v18.4s, v28.4s, v6.s[0] \n" "fmla v19.4s, v28.4s, v6.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v5.s[1] \n" "fmla v17.4s, v29.4s, v5.s[3] \n" "fmla v18.4s, v29.4s, v6.s[1] \n" "fmla v19.4s, v29.4s, v6.s[3] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "fmla v17.4s, v30.4s, v6.s[0] \n" "fmla v18.4s, v30.4s, v6.s[2] \n" "fmla v19.4s, v30.4s, v7.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4] \n"// r3 "add %4, %4, #32 \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v24.4s, v4.s[2] \n" "fmla v18.4s, v24.4s, v5.s[0] \n" "fmla v19.4s, v24.4s, v5.s[2] \n" "fmla v16.4s, v25.4s, v4.s[1] \n" "fmla v17.4s, v25.4s, v4.s[3] \n" "fmla v18.4s, v25.4s, v5.s[1] \n" "fmla v19.4s, v25.4s, v5.s[3] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "fmla v17.4s, v26.4s, v5.s[0] \n" "fmla v18.4s, v26.4s, v5.s[2] \n" "fmla v19.4s, v26.4s, v6.s[0] \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5] \n"// r4 "add %5, %5, #32 \n" "fmla v16.4s, v27.4s, v4.s[3] \n" "fmla v17.4s, v27.4s, v5.s[1] \n" "fmla v18.4s, v27.4s, v5.s[3] \n" "fmla v19.4s, v27.4s, v6.s[1] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "fmla v17.4s, v28.4s, v5.s[2] \n" "fmla v18.4s, v28.4s, v6.s[0] \n" "fmla v19.4s, v28.4s, v6.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v5.s[1] \n" "fmla v17.4s, v29.4s, v5.s[3] \n" "fmla v18.4s, v29.4s, v6.s[1] \n" "fmla v19.4s, v29.4s, v6.s[3] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "fmla v17.4s, v30.4s, v6.s[0] \n" "fmla v18.4s, v30.4s, v6.s[2] \n" "fmla v19.4s, v30.4s, v7.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "prfm pldl1keep, [%6, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6] \n"// r5 "add %6, %6, #32 \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v24.4s, v4.s[2] \n" "fmla v18.4s, v24.4s, v5.s[0] \n" "fmla v19.4s, v24.4s, v5.s[2] \n" "fmla v16.4s, v25.4s, v4.s[1] \n" "fmla v17.4s, v25.4s, v4.s[3] \n" "fmla v18.4s, v25.4s, v5.s[1] \n" "fmla v19.4s, v25.4s, v5.s[3] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "fmla v17.4s, v26.4s, v5.s[0] \n" "fmla v18.4s, v26.4s, v5.s[2] \n" "fmla v19.4s, v26.4s, v6.s[0] \n" "prfm pldl1keep, [%7, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%7] \n"// r6 "add %7, %7, #32 \n" "fmla v16.4s, v27.4s, v4.s[3] \n" "fmla v17.4s, v27.4s, v5.s[1] \n" "fmla v18.4s, v27.4s, v5.s[3] \n" "fmla v19.4s, v27.4s, v6.s[1] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "fmla v17.4s, v28.4s, v5.s[2] \n" "fmla v18.4s, v28.4s, v6.s[0] \n" "fmla v19.4s, v28.4s, v6.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v5.s[1] \n" "fmla v17.4s, v29.4s, v5.s[3] \n" "fmla v18.4s, v29.4s, v6.s[1] \n" "fmla v19.4s, v29.4s, v6.s[3] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "fmla v17.4s, v30.4s, v6.s[0] \n" "fmla v18.4s, v30.4s, v6.s[2] \n" "fmla v19.4s, v30.4s, v7.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v0.s[0] \n" "fmla v17.4s, v24.4s, v0.s[2] \n" "fmla v18.4s, v24.4s, v1.s[0] \n" "fmla v19.4s, v24.4s, v1.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v25.4s, v1.s[1] \n" "fmla v19.4s, v25.4s, v1.s[3] \n" "fmla v16.4s, v26.4s, v0.s[2] \n" "fmla v17.4s, v26.4s, v1.s[0] \n" "fmla v18.4s, v26.4s, v1.s[2] \n" "fmla v19.4s, v26.4s, v2.s[0] \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v27.4s, v1.s[3] \n" "fmla v19.4s, v27.4s, v2.s[1] \n" "fmla v16.4s, v28.4s, v1.s[0] \n" "fmla v17.4s, v28.4s, v1.s[2] \n" "fmla v18.4s, v28.4s, v2.s[0] \n" "fmla v19.4s, v28.4s, v2.s[2] \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v29.4s, v2.s[1] \n" "fmla v19.4s, v29.4s, v2.s[3] \n" "fmla v16.4s, v30.4s, v1.s[2] \n" "fmla v17.4s, v30.4s, v2.s[0] \n" "fmla v18.4s, v30.4s, v2.s[2] \n" "fmla v19.4s, v30.4s, v3.s[0] \n" "sub %8, %8, #784 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v24", "v25", "v26", "v27", "v28", "v29", "v30" ); #else // __aarch64__ asm volatile( "pld [%0, #512] \n" "vldm %0, {d24-d31} \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1]! \n"// r0 "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%1, #192] \n" "vld1.f32 {d4-d6}, [%1] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "pld [%2, #256] \n" "vld1.f32 {d0-d3}, [%2]! \n"// r1 "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%2, #192] \n" "vld1.f32 {d4-d6}, [%2] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3]! \n"// r2 "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%3, #192] \n" "vld1.f32 {d4-d6}, [%3] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "pld [%4, #256] \n" "vld1.f32 {d0-d3}, [%4]! \n"// r3 "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%4, #192] \n" "vld1.f32 {d4-d6}, [%4] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "pld [%5, #256] \n" "vld1.f32 {d0-d3}, [%5]! \n"// r4 "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%5, #192] \n" "vld1.f32 {d4-d6}, [%5] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "pld [%6, #256] \n" "vld1.f32 {d0-d3}, [%6]! \n"// r5 "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%6, #192] \n" "vld1.f32 {d4-d6}, [%6] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "pld [%7, #256] \n" "vld1.f32 {d0-d3}, [%7]! \n"// r6 "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q5, d2[0] \n" "vmla.f32 q15, q5, d3[0] \n" "pld [%7, #192] \n" "vld1.f32 {d4-d6}, [%7] \n" "vmla.f32 q12, q6, d0[1] \n" "vmla.f32 q13, q6, d1[1] \n" "vmla.f32 q14, q6, d2[1] \n" "vmla.f32 q15, q6, d3[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q7, d3[0] \n" "vmla.f32 q15, q7, d4[0] \n" "vmla.f32 q12, q8, d1[1] \n" "vmla.f32 q13, q8, d2[1] \n" "vmla.f32 q14, q8, d3[1] \n" "vmla.f32 q15, q8, d4[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q9, d4[0] \n" "vmla.f32 q15, q9, d5[0] \n" "vmla.f32 q12, q10, d2[1] \n" "vmla.f32 q13, q10, d3[1] \n" "vmla.f32 q14, q10, d4[1] \n" "vmla.f32 q15, q10, d5[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d4[0] \n" "vmla.f32 q14, q11, d5[0] \n" "vmla.f32 q15, q11, d6[0] \n" "sub %8, %8, #784 \n" "vstm %0!, {d24-d31} \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ } for (; j+1<outw; j+=2) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v16.4s, v17.4s}, [%0] \n" "prfm pldl1keep, [%1, #384] \n" "ld1 {v0.4s, v1.4s, v2.4s}, [%1] \n"// r0 "add %1, %1, #16 \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmul v18.4s, v24.4s, v0.s[0] \n" "fmul v19.4s, v24.4s, v0.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v26.4s, v0.s[2] \n" "fmla v19.4s, v26.4s, v1.s[0] \n" "prfm pldl1keep, [%2, #384] \n" "ld1 {v4.4s, v5.4s, v6.4s}, [%2] \n"// r1 "add %2, %2, #16 \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v28.4s, v1.s[0] \n" "fmla v19.4s, v28.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v30.4s, v1.s[2] \n" "fmla v19.4s, v30.4s, v2.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v24.4s, v4.s[2] \n" "fmla v18.4s, v25.4s, v4.s[1] \n" "fmla v19.4s, v25.4s, v4.s[3] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "fmla v17.4s, v26.4s, v5.s[0] \n" "prfm pldl1keep, [%3, #384] \n" "ld1 {v0.4s, v1.4s, v2.4s}, [%3] \n"// r2 "add %3, %3, #16 \n" "fmla v18.4s, v27.4s, v4.s[3] \n" "fmla v19.4s, v27.4s, v5.s[1] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "fmla v17.4s, v28.4s, v5.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v18.4s, v29.4s, v5.s[1] \n" "fmla v19.4s, v29.4s, v5.s[3] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "fmla v17.4s, v30.4s, v6.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v18.4s, v24.4s, v0.s[0] \n" "fmla v19.4s, v24.4s, v0.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v26.4s, v0.s[2] \n" "fmla v19.4s, v26.4s, v1.s[0] \n" "prfm pldl1keep, [%4, #384] \n" "ld1 {v4.4s, v5.4s, v6.4s}, [%4] \n"// r3 "add %4, %4, #16 \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v28.4s, v1.s[0] \n" "fmla v19.4s, v28.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v30.4s, v1.s[2] \n" "fmla v19.4s, v30.4s, v2.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v24.4s, v4.s[2] \n" "fmla v18.4s, v25.4s, v4.s[1] \n" "fmla v19.4s, v25.4s, v4.s[3] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "fmla v17.4s, v26.4s, v5.s[0] \n" "prfm pldl1keep, [%5, #384] \n" "ld1 {v0.4s, v1.4s, v2.4s}, [%5] \n"// r4 "add %5, %5, #16 \n" "fmla v18.4s, v27.4s, v4.s[3] \n" "fmla v19.4s, v27.4s, v5.s[1] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "fmla v17.4s, v28.4s, v5.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v18.4s, v29.4s, v5.s[1] \n" "fmla v19.4s, v29.4s, v5.s[3] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "fmla v17.4s, v30.4s, v6.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v18.4s, v24.4s, v0.s[0] \n" "fmla v19.4s, v24.4s, v0.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v26.4s, v0.s[2] \n" "fmla v19.4s, v26.4s, v1.s[0] \n" "prfm pldl1keep, [%6, #384] \n" "ld1 {v4.4s, v5.4s, v6.4s}, [%6] \n"// r5 "add %6, %6, #16 \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v28.4s, v1.s[0] \n" "fmla v19.4s, v28.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v30.4s, v1.s[2] \n" "fmla v19.4s, v30.4s, v2.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v24.4s, v4.s[2] \n" "fmla v18.4s, v25.4s, v4.s[1] \n" "fmla v19.4s, v25.4s, v4.s[3] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "fmla v17.4s, v26.4s, v5.s[0] \n" "prfm pldl1keep, [%7, #384] \n" "ld1 {v0.4s, v1.4s, v2.4s}, [%7] \n"// r6 "add %7, %7, #16 \n" "fmla v18.4s, v27.4s, v4.s[3] \n" "fmla v19.4s, v27.4s, v5.s[1] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "fmla v17.4s, v28.4s, v5.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v18.4s, v29.4s, v5.s[1] \n" "fmla v19.4s, v29.4s, v5.s[3] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "fmla v17.4s, v30.4s, v6.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v18.4s, v24.4s, v0.s[0] \n" "fmla v19.4s, v24.4s, v0.s[2] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v25.4s, v0.s[3] \n" "fmla v18.4s, v26.4s, v0.s[2] \n" "fmla v19.4s, v26.4s, v1.s[0] \n" "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v27.4s, v1.s[1] \n" "fmla v18.4s, v28.4s, v1.s[0] \n" "fmla v19.4s, v28.4s, v1.s[2] \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v29.4s, v1.s[3] \n" "fmla v18.4s, v30.4s, v1.s[2] \n" "fmla v19.4s, v30.4s, v2.s[0] \n" "fadd v16.4s, v16.4s, v18.4s \n" "fadd v17.4s, v17.4s, v19.4s \n" "sub %8, %8, #784 \n" "st1 {v16.4s, v17.4s}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "v0", "v1", "v2", "v4", "v5", "v6", "v16", "v17", "v18", "v19", "v24", "v25", "v26", "v27", "v28", "v29", "v30" ); #else // __aarch64__ asm volatile( "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128] \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1]! \n"// r0 "vld1.f32 {d8[0]}, [%1] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmul.f32 q12, q5, d0[0] \n" "vmul.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q6, d0[1] \n" "vmla.f32 q15, q6, d1[1] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2]! \n"// r1 "vld1.f32 {d9[0]}, [%2] \n" "vmla.f32 q14, q8, d1[1] \n" "vmla.f32 q15, q8, d2[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q14, q10, d2[1] \n" "vmla.f32 q15, q10, d3[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d8[0] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q14, q5, d4[0] \n" "vmla.f32 q15, q5, d5[0] \n" "vmla.f32 q12, q6, d4[1] \n" "vmla.f32 q13, q6, d5[1] \n" "vmla.f32 q14, q7, d5[0] \n" "vmla.f32 q15, q7, d6[0] \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3]! \n"// r2 "vld1.f32 {d8[0]}, [%3] \n" "vmla.f32 q12, q8, d5[1] \n" "vmla.f32 q13, q8, d6[1] \n" "vmla.f32 q14, q9, d6[0] \n" "vmla.f32 q15, q9, d7[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d6[1] \n" "vmla.f32 q13, q10, d7[1] \n" "vmla.f32 q14, q11, d7[0] \n" "vmla.f32 q15, q11, d9[0] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q6, d0[1] \n" "vmla.f32 q15, q6, d1[1] \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4]! \n"// r3 "vld1.f32 {d9[0]}, [%4] \n" "vmla.f32 q14, q8, d1[1] \n" "vmla.f32 q15, q8, d2[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q14, q10, d2[1] \n" "vmla.f32 q15, q10, d3[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d8[0] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q14, q5, d4[0] \n" "vmla.f32 q15, q5, d5[0] \n" "vmla.f32 q12, q6, d4[1] \n" "vmla.f32 q13, q6, d5[1] \n" "vmla.f32 q14, q7, d5[0] \n" "vmla.f32 q15, q7, d6[0] \n" "pld [%5, #256] \n" "vld1.f32 {d0-d3}, [%5]! \n"// r4 "vld1.f32 {d8[0]}, [%5] \n" "vmla.f32 q12, q8, d5[1] \n" "vmla.f32 q13, q8, d6[1] \n" "vmla.f32 q14, q9, d6[0] \n" "vmla.f32 q15, q9, d7[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d6[1] \n" "vmla.f32 q13, q10, d7[1] \n" "vmla.f32 q14, q11, d7[0] \n" "vmla.f32 q15, q11, d9[0] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q6, d0[1] \n" "vmla.f32 q15, q6, d1[1] \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "pld [%6, #256] \n" "vld1.f32 {d4-d7}, [%6]! \n"// r5 "vld1.f32 {d9[0]}, [%6] \n" "vmla.f32 q14, q8, d1[1] \n" "vmla.f32 q15, q8, d2[1] \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q14, q10, d2[1] \n" "vmla.f32 q15, q10, d3[1] \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d8[0] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q14, q5, d4[0] \n" "vmla.f32 q15, q5, d5[0] \n" "vmla.f32 q12, q6, d4[1] \n" "vmla.f32 q13, q6, d5[1] \n" "vmla.f32 q14, q7, d5[0] \n" "vmla.f32 q15, q7, d6[0] \n" "pld [%7, #256] \n" "vld1.f32 {d0-d3}, [%7]! \n"// r6 "vld1.f32 {d8[0]}, [%7] \n" "vmla.f32 q12, q8, d5[1] \n" "vmla.f32 q13, q8, d6[1] \n" "vmla.f32 q14, q9, d6[0] \n" "vmla.f32 q15, q9, d7[0] \n" "pld [%8, #512] \n" "vldm %8!, {d10-d17} \n" "vmla.f32 q12, q10, d6[1] \n" "vmla.f32 q13, q10, d7[1] \n" "vmla.f32 q14, q11, d7[0] \n" "vmla.f32 q15, q11, d9[0] \n" "pld [%8, #384] \n" "vldm %8!, {d18-d23} \n" "vmla.f32 q12, q5, d0[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q6, d0[1] \n" "vmla.f32 q15, q6, d1[1] \n" "sub %1, %1, #16 \n" "sub %2, %2, #16 \n" "vmla.f32 q12, q7, d1[0] \n" "vmla.f32 q13, q7, d2[0] \n" "vmla.f32 q14, q8, d1[1] \n" "vmla.f32 q15, q8, d2[1] \n" "sub %8, %8, #784 \n" "vmla.f32 q12, q9, d2[0] \n" "vmla.f32 q13, q9, d3[0] \n" "vmla.f32 q14, q10, d2[1] \n" "vmla.f32 q15, q10, d3[1] \n" "sub %3, %3, #16 \n" "sub %4, %4, #16 \n" "vmla.f32 q12, q11, d3[0] \n" "vmla.f32 q13, q11, d8[0] \n" "sub %5, %5, #16 \n" "sub %6, %6, #16 \n" "vadd.f32 q14, q14, q12 \n" "vadd.f32 q15, q15, q13 \n" "sub %7, %7, #16 \n" "vst1.f32 {d28-d31}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ } for (; j<outw; j++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n"// r0 "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmul v17.4s, v24.4s, v0.s[0] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmul v18.4s, v25.4s, v0.s[1] \n" "fmul v19.4s, v26.4s, v0.s[2] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v4.4s, v5.4s}, [%2] \n"// r1 "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v28.4s, v1.s[0] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v18.4s, v29.4s, v1.s[1] \n" "fmla v19.4s, v30.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v25.4s, v4.s[1] \n" "fmla v18.4s, v26.4s, v4.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v0.4s, v1.4s}, [%3] \n"// r2 "fmla v19.4s, v27.4s, v4.s[3] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v17.4s, v29.4s, v5.s[1] \n" "fmla v18.4s, v30.4s, v5.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v19.4s, v24.4s, v0.s[0] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v26.4s, v0.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v4.4s, v5.4s}, [%4] \n"// r3 "fmla v18.4s, v27.4s, v0.s[3] \n" "fmla v19.4s, v28.4s, v1.s[0] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v30.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v18.4s, v24.4s, v4.s[0] \n" "fmla v19.4s, v25.4s, v4.s[1] \n" "fmla v16.4s, v26.4s, v4.s[2] \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v0.4s, v1.4s}, [%5] \n"// r4 "fmla v17.4s, v27.4s, v4.s[3] \n" "fmla v18.4s, v28.4s, v5.s[0] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v19.4s, v29.4s, v5.s[1] \n" "fmla v16.4s, v30.4s, v5.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v17.4s, v24.4s, v0.s[0] \n" "fmla v18.4s, v25.4s, v0.s[1] \n" "fmla v19.4s, v26.4s, v0.s[2] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v4.4s, v5.4s}, [%6] \n"// r5 "fmla v16.4s, v27.4s, v0.s[3] \n" "fmla v17.4s, v28.4s, v1.s[0] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v18.4s, v29.4s, v1.s[1] \n" "fmla v19.4s, v30.4s, v1.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v16.4s, v24.4s, v4.s[0] \n" "fmla v17.4s, v25.4s, v4.s[1] \n" "fmla v18.4s, v26.4s, v4.s[2] \n" "prfm pldl1keep, [%7, #256] \n" "ld1 {v0.4s, v1.4s}, [%7] \n"// r6 "fmla v19.4s, v27.4s, v4.s[3] \n" "fmla v16.4s, v28.4s, v5.s[0] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%8], #64 \n" "fmla v17.4s, v29.4s, v5.s[1] \n" "fmla v18.4s, v30.4s, v5.s[2] \n" "prfm pldl1keep, [%8, #384] \n" "ld1 {v28.4s, v29.4s, v30.4s}, [%8], #48 \n" "fmla v19.4s, v24.4s, v0.s[0] \n" "fmla v16.4s, v25.4s, v0.s[1] \n" "fmla v17.4s, v26.4s, v0.s[2] \n" "add %1, %1, #8 \n" "add %2, %2, #8 \n" "fmla v18.4s, v27.4s, v0.s[3] \n" "fmla v19.4s, v28.4s, v1.s[0] \n" "fmla v16.4s, v29.4s, v1.s[1] \n" "fmla v17.4s, v30.4s, v1.s[2] \n" "add %3, %3, #8 \n" "add %4, %4, #8 \n" "fadd v18.4s, v18.4s, v19.4s \n" "add %5, %5, #8 \n" "fadd v16.4s, v16.4s, v17.4s \n" "add %6, %6, #8 \n" "add %7, %7, #8 \n" "fadd v16.4s, v16.4s, v18.4s \n" "sub %8, %8, #784 \n" "st1 {v16.4s}, [%0], #16 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "v0", "v1", "v4", "v5", "v16", "v17", "v18", "v19", "v24", "v25", "v26", "v27", "v28", "v29", "v30" ); #else // __aarch64__ asm volatile( "pld [%0, #128] \n" "vld1.f32 {d8-d9}, [%0 :128] \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n"// r0 "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmul.f32 q5, q8, d0[0] \n" "vmul.f32 q6, q9, d0[1] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmul.f32 q7, q10, d1[0] \n" "vmla.f32 q4, q11, d1[1] \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2] \n"// r1 "vmla.f32 q5, q12, d2[0] \n" "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmla.f32 q6, q13, d2[1] \n" "vmla.f32 q7, q14, d3[0] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmla.f32 q4, q8, d4[0] \n" "vmla.f32 q5, q9, d4[1] \n" "vmla.f32 q6, q10, d5[0] \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3] \n"// r2 "vmla.f32 q7, q11, d5[1] \n" "vmla.f32 q4, q12, d6[0] \n" "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmla.f32 q5, q13, d6[1] \n" "vmla.f32 q6, q14, d7[0] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmla.f32 q7, q8, d0[0] \n" "vmla.f32 q4, q9, d0[1] \n" "vmla.f32 q5, q10, d1[0] \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4] \n"// r3 "vmla.f32 q6, q11, d1[1] \n" "vmla.f32 q7, q12, d2[0] \n" "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmla.f32 q4, q13, d2[1] \n" "vmla.f32 q5, q14, d3[0] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmla.f32 q6, q8, d4[0] \n" "vmla.f32 q7, q9, d4[1] \n" "vmla.f32 q4, q10, d5[0] \n" "pld [%5, #256] \n" "vld1.f32 {d0-d3}, [%5] \n"// r4 "vmla.f32 q5, q11, d5[1] \n" "vmla.f32 q6, q12, d6[0] \n" "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmla.f32 q7, q13, d6[1] \n" "vmla.f32 q4, q14, d7[0] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmla.f32 q5, q8, d0[0] \n" "vmla.f32 q6, q9, d0[1] \n" "vmla.f32 q7, q10, d1[0] \n" "pld [%6, #256] \n" "vld1.f32 {d4-d7}, [%6] \n"// r5 "vmla.f32 q4, q11, d1[1] \n" "vmla.f32 q5, q12, d2[0] \n" "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmla.f32 q6, q13, d2[1] \n" "vmla.f32 q7, q14, d3[0] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmla.f32 q4, q8, d4[0] \n" "vmla.f32 q5, q9, d4[1] \n" "vmla.f32 q6, q10, d5[0] \n" "pld [%7, #256] \n" "vld1.f32 {d0-d3}, [%7] \n"// r6 "vmla.f32 q7, q11, d5[1] \n" "vmla.f32 q4, q12, d6[0] \n" "pld [%8, #512] \n" "vldm %8!, {d16-d23} \n" "vmla.f32 q5, q13, d6[1] \n" "vmla.f32 q6, q14, d7[0] \n" "pld [%8, #384] \n" "vldm %8!, {d24-d29} \n" "vmla.f32 q7, q8, d0[0] \n" "vmla.f32 q4, q9, d0[1] \n" "add %1, %1, #8 \n" "add %2, %2, #8 \n" "vmla.f32 q5, q10, d1[0] \n" "vmla.f32 q6, q11, d1[1] \n" "sub %8, %8, #784 \n" "vmla.f32 q7, q12, d2[0] \n" "vmla.f32 q4, q13, d2[1] \n" "vmla.f32 q5, q14, d3[0] \n" "add %3, %3, #8 \n" "add %4, %4, #8 \n" "vadd.f32 q6, q6, q7 \n" "add %5, %5, #8 \n" "vadd.f32 q4, q4, q5 \n" "add %6, %6, #8 \n" "vadd.f32 q4, q4, q6 \n" "add %7, %7, #8 \n" "vst1.f32 {d8-d9}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(r4), // %5 "=r"(r5), // %6 "=r"(r6), // %7 "=r"(kptr) // %8 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(r4), "6"(r5), "7"(r6), "8"(kptr) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14" ); #endif // __aarch64__ } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; r4 += tailstep; r5 += tailstep; r6 += tailstep; } } } } }
mcrat.c
/* # Program to run a Monte Carlo radiation transfer through the 2D # simulations of GRB jets. # # Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State # ver 0.1 July 8, 2015 # ver 1.1 July 20, 2015: added record of number of scatterings, included # all terms in weight. Should now give correct light curves. # ver 1.2 July 21, 2015: added parameter file to keep track of input # params of each simulation # ver 2.0 July 22, 2015: corrected the problem that arises when there is # no scattering in the time span of one frame. Fixed output arrays dimension. # ver 2.1 July 25, 2015: fixed bug that did not make the number of # scattering grow with the number of photons. # ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to # speed things up. Gained about factor 2 # ver 3.1 July 29, 2015: added radial spread of photon injection points # ver 3.2 July 31, 2015: added Gamma to the weight of photons!!! # ver 4.0 Aug 5, 2015: try to speed up by inverting cycle # ver 4.1 Aug 8, 2015: add spherical test as an option # ver 4.2 Aug 9, 2015: saving files appending rather than re-writing # ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature # ver 4.4 Aug 13, 2015: added cylindrical test # ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test # ver 4.6 Aug 21, 2015: corrected mean free path for large radii # ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings # ver 5.1 Aug 25, 2015: cleaned-up coding # ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections * * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path so you just need to supply the sub directory of MC_XXX as a command line argument * version 7.0 used OpenMP to parallelize the code by angle and the function findminmfp() version 8.0 added 3D capabilities for RIKEN hydro data and 2D capablities for RIKEN 2D hydro data and made it more efficient with grid selection to speed it up * Version 9.0 late 2017 included full Klein Nishina Cross Section and polarization with stokes parameters * Version 9.1 late 2018 including cyclosynchrotron absorption and emission */ #include "mcrat.h" int main(int argc, char **argv) { //compile each time a macro is changed, have to supply the subfolder within the MC_PATH directory as a command line argument to the C program eg. MCRAT 1/ // Define variables char hydro_prefix[STR_BUFFER]=""; char mc_file[STR_BUFFER]="" ; char spect;//type of spectrum char restrt;//restart or not double fps, fps_modified, theta_jmin, theta_jmax,hydro_domain_y, hydro_domain_x ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians, max y value in hydro domain double inj_radius_small, inj_radius_large, ph_weight_suggest=1e50, ph_weight_small, ph_weight_large, *inj_radius_input=NULL, ph_weight_default=1e50;//radius at chich photons are injected into sim int frm0,last_frm, frm2_small, frm2_large, j=0, min_photons, max_photons, frm0_small, frm0_large, *frm2_input=NULL, *frm0_input=NULL ;//frame starting from, last frame of sim, frame of last injection int dim_switch=0; int find_nearest_grid_switch=0; int increment_inj=1, increment_scatt=1; //increments for injection loop and scattering loop, outer and inner loops respectively, the increment can change for RIKEN 3D hydro files double inj_radius; int frm2,save_chkpt_success=0; char mc_filename[STR_BUFFER]=""; char mc_filename_2[STR_BUFFER]=""; char mc_operation[STR_BUFFER]=""; char mc_dir[STR_BUFFER]="" ; int file_count = 0; DIR * dirp; struct dirent * entry; struct stat st = {0}; double theta_jmin_thread=0, theta_jmax_thread=0; char hydro_file[STR_BUFFER]=""; char log_file[STR_BUFFER]=""; FILE *fPtr=NULL; //pointer to log file for each thread double *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL; double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files double *phiPtr=NULL, *velzPtr=NULL, *zPtr=NULL, *all_time_steps=NULL ; int num_ph=0, scatt_cyclosynch_num_ph=0, num_null_ph=0, array_num=0, ph_scatt_index=0, num_photons_find_new_element=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter double dt_max=0, thescatt=0, accum_time=0; double gamma_infinity=0, time_now=0, time_step=0, avg_scatt=0,avg_r=0; //gamma_infinity not used? double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0, ph_vzPtr=0;// *ph_cosanglePtr=NULL ; double min_r=0, max_r=0, min_theta=0, max_theta=0, nu_c_scatt=0, n_comptonized=0; int frame=0, scatt_frame=0, frame_scatt_cnt=0, frame_abs_cnt=0, scatt_framestart=0, framestart=0; struct photon *phPtr=NULL; //pointer to array of photons struct hydro_dataframe hydrodata; //pointer to array of hydro data int angle_count=0, num_cyclosynch_ph_emit=0; int num_angles=0, old_num_angle_procs=0; //old_num_angle_procs is to hold the old number of procs in each angle when cont sims, if restarting sims this gets set to angle_procs int *frame_array=NULL, *proc_frame_array=NULL, *element_num=NULL, *sorted_indexes=NULL, proc_frame_size=0; double *thread_theta=NULL; //saves ranges of thetas for each thread to go through double delta_theta=1, num_theta_bins=0; double test_cyclosynch_inj_radius=0; int myid, numprocs, angle_procs, angle_id, procs_per_angle; int temporary[3]={0}, tempo=0; //new OpenMPI stuff MPI_Init(NULL,NULL); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); //new muliple threads injecting and propagating photons const gsl_rng_type *rng_t; gsl_rng *rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; rng = gsl_rng_alloc (rng_t); //initalize random number generator to seed the others with random numbers //want to break up simulation by angle and injection frame & have each thread save data in its own folder //have each thread check if its directory is made and if its restarting (delete evrything) or if its continuing with a previous simulation //the angle and the injection frames will be the names of mc_dir, therefore read mc.par first in MC_XXX directory hydroDataFrameInitialize(&hydrodata); readMcPar(&hydrodata, &theta_jmin, &theta_jmax, &num_theta_bins, &inj_radius_input, &frm0_input , &frm2_input, &min_photons, &max_photons, &spect, &restrt); //thetas that comes out is in degrees, need to free input frame and injection radius pointers fps=hydrodata.fps;//save this incase we need modifications to fps later on in hydro sim last_frm=hydrodata.last_frame; //printf("%c\n", restrt); //divide up angles and frame injections among threads DONT WANT NUMBER OF THREADS TO BE ODD //assign ranges to array that hold them //leave angles in degrees here num_angles= (int) num_theta_bins; delta_theta=((theta_jmax-theta_jmin)/num_theta_bins); thread_theta=malloc( num_angles *sizeof(double) ); *(thread_theta+0)=theta_jmin;//*(180/M_PI); //printf("%e\n", *(thread_theta+0)); for (j=1;j<(num_angles); j++) { *(thread_theta+j)=*(thread_theta+(j-1))+delta_theta; //printf("%e\n", *(thread_theta+j)); } //make comm without the procs that deal with angle //comm for angles procs_per_angle= numprocs/num_angles; //printf("%d\n", procs_per_angle); MPI_Comm angle_comm; if (restrt==INITALIZE) //uncomment this when I run MCRAT for sims that didnt originally save angle_procs { MPI_Comm_split(MPI_COMM_WORLD, myid/procs_per_angle , myid, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); //printf("WORLD RANK/SIZE: %d/%d \t ROW RANK/SIZE: %d/%d\n", myid, numprocs, angle_id, angle_procs); theta_jmin_thread= (*(thread_theta+ (myid/procs_per_angle))) *(M_PI/180); theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180)); snprintf(mc_dir,sizeof(mc_dir),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this old_num_angle_procs=angle_procs; inj_radius= (*(inj_radius_input+(myid/procs_per_angle))); frm2=(*(frm2_input+(myid/procs_per_angle))); frm0=(*(frm0_input+(myid/procs_per_angle))); ph_weight_suggest=ph_weight_default; } else { MPI_Group sub_world_group; MPI_Comm sub_world_comm; int incl_procs[procs_per_angle*num_angles], count, sub_world_id; int total_num_to_restart=0; int color=1; int *all_cont_process_idPtr=NULL, *each_num_to_restart_per_anglePtr=NULL, *tmp=NULL; //for restart='c' case if the number of processes isnt a multiple of procs_per_angle*num_angles make a comm out of those that are in order to analyze files and count number of processes for each angle range need to con't count=0; for (j=0;j<numprocs;j++) { if (j<procs_per_angle*num_angles) { incl_procs[count]=j; count++; } } if (myid<procs_per_angle*num_angles) { int myid_2=0; // Get the group of processes in MPI_COMM_WORLD and make a sub group to go through checkpoint files MPI_Group world_group; MPI_Comm root_angle_comm; MPI_Comm_group(MPI_COMM_WORLD, &world_group); MPI_Group_incl(world_group, procs_per_angle*num_angles, incl_procs, &sub_world_group); MPI_Comm_create_group(MPI_COMM_WORLD, sub_world_group, 0, &sub_world_comm); MPI_Comm_rank(sub_world_comm, &myid_2); MPI_Comm_split(sub_world_comm, myid_2/procs_per_angle , myid_2, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); //create group of all the processes that have angle_id==0 if (angle_id==0) { color=0; //set different color for root processes in each group of angle_comm } MPI_Comm_split(sub_world_comm, color , myid_2, &root_angle_comm); //create comm to exchange info about number of processes to restart for each angle range printf("WORLD RANK/SIZE: %d/%d \t ROW RANK/SIZE: %d/%d\n", myid, numprocs, angle_id, angle_procs); theta_jmin_thread= (*(thread_theta+ (myid_2/procs_per_angle))) *(M_PI/180); theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180)); snprintf(mc_dir,sizeof(mc_dir),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this //call the function to count the num of processes for each angle range that need to be con't int count_cont_procs=0, total_cont_procs_angle=0, global_cont_procs=0; int *cont_proc_idsPtr=NULL, *total_cont_procs_angle_Ptr=NULL, *displPtr=NULL; //becomes the size of the number of old procceses int *cont_proc_ids_anglePtr=NULL; old_num_angle_procs=getOrigNumProcesses(&count_cont_procs, &cont_proc_idsPtr, mc_dir, angle_id, angle_procs, last_frm); //count_cont_procs=1;//just for testing purposes if (old_num_angle_procs==-1) { printf("MCRAT wasnt able to get a value of old_num_angle_procs to continue the simulation. Now exiting to prevent data corruption.\n" ); MPI_Abort(MPI_COMM_WORLD, 1); } total_cont_procs_angle_Ptr=malloc(angle_procs*sizeof(int)); displPtr=malloc(angle_procs*sizeof(int)); MPI_Gather(&count_cont_procs,1,MPI_INT, total_cont_procs_angle_Ptr, 1, MPI_INT, 0,angle_comm );//hold the number of elements that each process will send the root process MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); //if (angle_id==0) //{ // printf("Angle_procs: %d 1st gather: %d, %d, %d\n", angle_procs, *(total_cont_procs_angle_Ptr), *(total_cont_procs_angle_Ptr+1), *(total_cont_procs_angle_Ptr+2)); //} MPI_Reduce(&count_cont_procs, &total_cont_procs_angle, 1, MPI_INT, MPI_SUM, 0, angle_comm); //for each angle sum the number of procs to continue and pass it to the root for angle_comm cont_proc_ids_anglePtr=malloc(total_cont_procs_angle*sizeof(int)); //each root proc in angle comm has to hold the id's of the old set of processes to cont *(displPtr+0)=0; if (angle_id==0) { for (j=1;j<angle_procs;j++) { *(displPtr+j)=(*(displPtr+j-1))+(*(total_cont_procs_angle_Ptr+j-1 )); //set the displacement for each proces to put its vector of pprocess IDs that need to be continued printf("Displacement: %d\n", *(displPtr+j)); } } MPI_Gatherv(cont_proc_idsPtr,count_cont_procs,MPI_INT, cont_proc_ids_anglePtr, total_cont_procs_angle_Ptr, displPtr , MPI_INT, 0,angle_comm ); //send the vectors with the ids of the old processes that need to be cont to root in angle_comm MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (angle_id==0) { printf("Total Cont Procs: %d\n", total_cont_procs_angle); for (j=0;j<total_cont_procs_angle;j++) { { printf("Number: %d ID: %d\n",j, *(cont_proc_ids_anglePtr+j)); } } } //each root for angle_comm has the number of processes each angle range needs to restart and the array of what the IDs of those processes used to be //now have to combine all that info for rank 0 in MPI_COMM_WORLD and then end it to all processes in MPI_COMM_WORLD { free(displPtr); displPtr=NULL; //initalize variables to hold all data each_num_to_restart_per_anglePtr=malloc(num_angles*sizeof(int)); displPtr=malloc(num_angles*sizeof(int)); *(displPtr+0)=0; } MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (angle_id==0) { //this is the part where all the root processes of angle_comm transfer thier info to the root proc of MPI_WORLD MPI_Reduce(&total_cont_procs_angle, &total_num_to_restart, 1, MPI_INT, MPI_SUM, 0, root_angle_comm); //for each angle sum the number of procs to continue and pass it to the root for MPI_COMM_WORLD MPI_Gather(&total_cont_procs_angle,1,MPI_INT, each_num_to_restart_per_anglePtr, 1, MPI_INT, 0,root_angle_comm );//hold the number of elements that each process sent the root for MPI_COMM_WORLD if (myid==0) { for (j=1;j<num_angles;j++) { *(displPtr+j)=(*(displPtr+j-1))+(*(each_num_to_restart_per_anglePtr+j-1 )); //set the displacement for each proces to put its vector of pprocess IDs that need to be continued } } all_cont_process_idPtr=malloc(total_num_to_restart*sizeof(int)); MPI_Gatherv(cont_proc_ids_anglePtr, total_cont_procs_angle, MPI_INT, all_cont_process_idPtr, each_num_to_restart_per_anglePtr, displPtr, MPI_INT, 0, root_angle_comm); } MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (myid==0) { printf("Global Cont Procs: %d\n", total_num_to_restart); for (j=0;j<total_num_to_restart;j++) { { printf("Global ID: %d\n", *(all_cont_process_idPtr+j)); } } } //destroy the old comms MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); //destroy current angle comm and recreate a new one MPI_Comm_free(&root_angle_comm); MPI_Comm_free(&angle_comm); MPI_Comm_free(&sub_world_comm); MPI_Group_free(&sub_world_group); MPI_Group_free(&world_group); free(cont_proc_idsPtr); free(cont_proc_ids_anglePtr); free(total_cont_procs_angle_Ptr); free(displPtr); //free(each_num_to_restart_per_anglePtr); //free(all_cont_process_idPtr); } //send all of myid==0 data to all processes in MPI_COMM_WORLD MPI_Bcast( &total_num_to_restart, 1, MPI_INT, 0, MPI_COMM_WORLD ); if (total_num_to_restart>0) { if (myid != 0 ) { printf("Proc %d: The total number of processes that still have work to do is: %d\n", myid, total_num_to_restart); //allocate data of appropriate size for all processes to hold the data from MPI_Bcast tmp=realloc(all_cont_process_idPtr,total_num_to_restart *sizeof(int)); if (tmp!=NULL) { all_cont_process_idPtr=tmp; } else { printf("Error with reserving space to hold data about restarting process ID's\n"); } //free(tmp); printf("Proc: %d, Num_angles: %d\n", myid, num_angles); tmp=realloc(each_num_to_restart_per_anglePtr, num_angles*sizeof(int)); if (tmp!=NULL) { each_num_to_restart_per_anglePtr=tmp; } else { printf("Error with reserving space to hold data about restarting process numbers for each angle range\n"); } //free(tmp); } MPI_Barrier(MPI_COMM_WORLD); MPI_Bcast( all_cont_process_idPtr, total_num_to_restart, MPI_INT, 0, MPI_COMM_WORLD ); MPI_Bcast( each_num_to_restart_per_anglePtr, num_angles, MPI_INT, 0, MPI_COMM_WORLD ); MPI_Bcast( &old_num_angle_procs, 1, MPI_INT, 0, MPI_COMM_WORLD ); MPI_Barrier(MPI_COMM_WORLD); //if (myid==numprocs-1) //{ // printf("Number of processes: %d\n", old_num_angle_procs); //printf("restarting process numbers for each angle range: %d, %d, %d\n", *(each_num_to_restart_per_anglePtr), *(each_num_to_restart_per_anglePtr+1), *(each_num_to_restart_per_anglePtr+2)); //} //assign proper number of processes to each angle range to con't sims and then reset angle_id to original value from when simulation was first started color=0; //by default all processes have this value count=0; for (j=0;j<num_angles;j++) { if (myid>=count && myid<count+(*(each_num_to_restart_per_anglePtr+j)) ) { color=j; } count+=(*(each_num_to_restart_per_anglePtr+j)); printf("Myid: %d, Color: %d, Count %d, Num To Start Per Angle: %d\n", myid, color, count, (*(each_num_to_restart_per_anglePtr+j))); } if (count!=numprocs) { //if the number of processes needed to continue the simulation is different from the number of processes in the mpiexec call exit printf("The simulation needs %d processes to properly continue. The number of processes initialized was %d.\nThe program is now exiting to prevent data corruption\n.", count, numprocs); exit(2); } MPI_Comm_split(MPI_COMM_WORLD, color , myid, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); //printf("WORLD RANK/SIZE: %d/%d \t ROW RANK/SIZE: %d/%d\n", myid, numprocs, angle_id, angle_procs); angle_procs=old_num_angle_procs; //reset the angle for each process theta_jmin_thread= (*(thread_theta+ color)) *(M_PI/180); theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180)); inj_radius= (*(inj_radius_input+color)); frm2=(*(frm2_input+color)); frm0=(*(frm0_input+color)); ph_weight_suggest=ph_weight_default; //reset the angle_id for each process count=0; for (j=0;j<color;j++) { count+=(*(each_num_to_restart_per_anglePtr+j)); } angle_id=(*(all_cont_process_idPtr+count+angle_id)); snprintf(mc_dir,sizeof(mc_dir),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this } else { //if there are no more processes to continue just break up processes normally so they read in checkpoint files of completed processes and jump to merging files MPI_Comm_split(MPI_COMM_WORLD, myid/procs_per_angle , myid, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); } free(all_cont_process_idPtr); free(each_num_to_restart_per_anglePtr); } MPI_Barrier(MPI_COMM_WORLD); free(inj_radius_input); free(frm0_input);free(frm2_input); free(thread_theta); //free input arrays sonce we hav determined which of the values in the arrays are applicable for this process //make vector to hold the frames we are injecting in, vector should have (frm2-frm0)/angle_procs slots, if fps is const //angle_procs=1;//just for testing purposes proc_frame_size=ceil((frm2-frm0)/ (float) angle_procs); frame_array=malloc(((frm2-frm0)+1)*sizeof(int)); for (j=0;j<((frm2-frm0)+1); j++) { *(frame_array+j)=frm0+j ; //printf("proc: %d frame: %d\n", angle_id, *(frame_array+j)); } //set this now incase there is no checkpoint file, then this wont be overwritten and the corretc values will be passed even if the user decides to restart framestart=(*(frame_array +(angle_id*proc_frame_size))); scatt_framestart=framestart; if (angle_id != (angle_procs-1)) { frm2=(*(frame_array +((angle_id*proc_frame_size) + proc_frame_size-1) )); //section off blocks of the frame_array to give to each angle_id } else { frm2=(*(frame_array + (frm2-frm0) )); //if angle_id is last give it the last set, even if its uneven } if (restrt==CONTINUE) { printf(">> MCRaT: Reading checkpoint\n"); //#pragma omp critical scatt_cyclosynch_num_ph=readCheckpoint(mc_dir, &phPtr, &frm2, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now, angle_id, &angle_procs); /* for (i=0;i<num_ph;i++) { printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(phPtr+i)->p0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt ); } */ if (restrt==CONTINUE) { printf(">> Rank %d: Starting from photons injected at frame: %d out of %d\n", angle_id,framestart, frm2); printf(">> Rank %d with angles %0.1lf-%0.1lf: Continuing scattering %d photons from frame: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,num_ph, scatt_framestart); printf(">> Rank %d with angles %0.1lf-%0.1lf: The time now is: %e\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,time_now); } else { printf(">> Rank %d with angles %0.1lf-%0.1lf: Continuing simulation by injecting photons at frame: %d out of %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,framestart, frm2); //starting with new photon injection is same as restarting sim } } else if ((stat(mc_dir, &st) == -1) && (restrt==INITALIZE)) { mkdir(mc_dir, 0777); //make the directory with full permissions } else { if (angle_id==0) { printf(">> proc %d with angles %0.1lf-%0.1lf: Cleaning directory \n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); dirp = opendir(mc_dir); while ((entry = readdir(dirp)) != NULL) { if (entry->d_type == DT_REG) { /* If the entry is a regular file */ file_count++; //count how many files are in dorectory } } printf("File count %d\n", file_count); //file_count=0; if (file_count>0) { snprintf(mc_operation,sizeof(mc_operation),"%s%s%s","exec rm ", mc_dir,"mc_proc_*"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(mc_operation),"%s%s%s","exec rm ", mc_dir,"mcdata_PW_*"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(mc_operation),"%s%s%s","exec rm ", mc_dir,"mcdata_PW*"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(mc_operation),"%s%s%s","exec rm ", mc_dir,"mc_chkpt_*.dat"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(mc_operation),"%s%s%s","exec rm ", mc_dir,"mc_output_*.log"); //prepares string to remove *.log in mc_dir system(mc_operation); } } } #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE if (framestart>=3000) { //increment_inj=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 //fps_modified=1; //therefore dt between files become 1 second hydrodata.increment_inj_frame=10; hydrodata.fps=1; } #else { //increment_inj=1; //fps_modified=fps; hydrodata.increment_inj_frame=1; hydrodata.fps=fps; //this is already set in readMcPar function but may need to be modified } #endif dt_max=1.0/hydrodata.fps; MPI_Barrier(angle_comm); snprintf(log_file,sizeof(log_file),"%s%s%d%s",mc_dir,"mc_output_", angle_id,".log" ); printf("%s\n",log_file); fPtr=fopen(log_file, "a"); printf( "Im Proc %d with angles %0.1lf-%0.1lf proc_frame_size is %d Starting on Frame: %d Injecting until %d scatt_framestart: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, proc_frame_size, framestart, frm2, scatt_framestart); fprintf(fPtr, "Im Proc %d with angles %0.1lf-%0.1lf Starting on Frame: %d scatt_framestart: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, framestart, scatt_framestart); fflush(fPtr); free(frame_array); frame_array=NULL; //for a checkpoint implementation, start from the last saved "frame" value and go to the saved "frm2" value for (frame=framestart;frame<=frm2;frame=frame+hydrodata.increment_inj_frame) { hydrodata.inj_frame_number=frame; #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE if (frame>=3000) { hydrodata.increment_inj_frame=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 hydrodata.fps=1; //therefore dt between files become 1 second } #else { hydrodata.increment_inj_frame=1; hydrodata.fps=fps; } #endif if (restrt==INITALIZE) { time_now=frame/hydrodata.fps; //for a checkpoint implmentation, load the saved "time_now" value when reading the ckeckpoint file otherwise calculate it normally } printHydroGeometry(fPtr); fprintf(fPtr,">> Im Proc: %d with angles %0.1lf - %0.1lf Working on Frame: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frame); fflush(fPtr); if (restrt==INITALIZE) { //can read FLASH 2D (no B field) and plutochombo and pluto dbl files in 2/2.5/3D with B field getHydroData(&hydrodata, frame, inj_radius, 1, min_r, max_r, min_theta, max_theta, fPtr); //determine where to place photons and how many should go in a given place //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data fprintf(fPtr,">> Proc: %d with angles %0.1lf-%0.1lf: Injecting photons\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); fflush(fPtr); photonInjection(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, theta_jmin_thread, theta_jmax_thread, &hydrodata,rng, fPtr ); //printf("This many Photons: %d\n",num_ph); //num_ph is one more photon than i actually have //for (i=0;i<num_ph;i++) // printf("%e,%e,%e \n",(phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2 ); } freeHydroDataFrame(&hydrodata);//free frame data here since we rewrite over pointers in next loop //scatter photons all the way thoughout the jet //for a checkpoint implmentation, start from the last saved "scatt_frame" value eh start_frame=frame or start_frame=cont_frame if (restrt==INITALIZE) { scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incremented by one the inner loop starts at that new value and not the one read by readCheckpoint() } num_null_ph=0; hydrodata.increment_scatt_frame=1; for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame=scatt_frame+hydrodata.increment_scatt_frame) { hydrodata.scatt_frame_number=scatt_frame; #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE if (scatt_frame>=3000) { hydrodata.increment_scatt_frame=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 hydrodata.fps=1; //therefore dt between files become 1 second } #else { hydrodata.increment_scatt_frame=1; hydrodata.fps=fps; } #endif dt_max=1.0/hydrodata.fps; //if working with RIKEN files and scatt_frame>=3000 dt is 1 second between each subsequent frame fprintf(fPtr,">>\n"); printHydroGeometry(fPtr); fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Working on photons injected at frame: %d out of %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,frame, frm2); #if SIMULATION_TYPE == SCIENCE fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Simulation type Science - Working on scattering photons in frame %d\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, scatt_frame); #elif SIMULATION_TYPE == SPHERICAL_OUTFLOW fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Simulation type Spherical Outflow - Working on scattering photons in frame %d\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, scatt_frame); #elif SIMULATION_TYPE == CYLINDRICAL_OUTFLOW fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Simulation type Cylindrical Outflow - Working on scattering photons in frame %d\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, scatt_frame); #elif SIMULATION_TYPE == STRUCTURED_SPHERICAL_OUTFLOW fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Simulation type Structured Spherical Outflow - Working on scattering photons in frame %d\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, scatt_frame); #endif //fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Opening file...\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); //fflush(fPtr); //set new seed to increase randomness? gsl_rng_set(rng, gsl_rng_get(rng)); //calc min and max positions of photons phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr); #if CYCLOSYNCHROTRON_SWITCH == ON if ((scatt_frame != scatt_framestart) || (restrt==CONTINUE)) //if ((scatt_frame == scatt_framestart) || (restrt==CONTINUE))//for testing { //NEED TO DETERMINE IF min_r or max_r is smaller/larger than the rmin/rmax in photonEmitCyclosynch to properly emit photons in the range that the process is interested in //printf("OLD: min_r %e max_r %e\n", min_r, max_r); test_cyclosynch_inj_radius=calcCyclosynchRLimits( scatt_frame, frame, hydrodata.fps, inj_radius, "min"); //printf("TEST MIN: %e\n", test); min_r=(min_r < test_cyclosynch_inj_radius) ? min_r : test_cyclosynch_inj_radius ; test_cyclosynch_inj_radius=calcCyclosynchRLimits( scatt_frame, frame, hydrodata.fps, inj_radius, "max"); //printf("TEST MAX: %e\n", test); max_r=(max_r > test_cyclosynch_inj_radius ) ? max_r : test_cyclosynch_inj_radius ; //printf("NEW: min_r %e max_r %e\n", min_r, max_r); } #endif getHydroData(&hydrodata, scatt_frame, inj_radius, 0, min_r, max_r, min_theta, max_theta, fPtr); //emit synchrotron photons here num_cyclosynch_ph_emit=0; //by default want to allocat ememory for time_steps and sorted indexes to scatter all_time_steps=malloc(num_ph*sizeof(double)); sorted_indexes=malloc(num_ph*sizeof(int)); #if CYCLOSYNCHROTRON_SWITCH == ON if ((scatt_frame != scatt_framestart) || (restrt==CONTINUE)) //remember to revert back to != //if ((scatt_frame == scatt_framestart) || (restrt==CONTINUE))//for testing { //if injecting synch photons, emit them if continuing simulation from a point where scatt_frame != scatt_framestart //if necessary, then add memory to then arrays allocated directly above fprintf(fPtr, "Emitting Cyclosynchrotron Photons in frame %d\n", scatt_frame); #if B_FIELD_CALC == INTERNAL_E fprintf(fPtr, "Calculating the magnetic field using internal energy and epsilon_B is set to %lf.\n", EPSILON_B); #elif B_FIELD_CALC == TOTAL_E //otherwise calculate B from the total energy fprintf(fPtr, "Calculating the magnetic field using the total energy and epsilon_B is set to %lf.\n", EPSILON_B); #else fprintf(fPtr, "Using the magnetic field from the hydro simulation.\n"); #endif //fprintf(fPtr, "HYDRO_B_SCALE %lf.\n", HYDRO_B_SCALE); phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt, &avg_r, fPtr); //for testing synch photons being emitted where 'i' photons are num_cyclosynch_ph_emit=photonEmitCyclosynch(&phPtr, &num_ph, &num_null_ph, &all_time_steps, &sorted_indexes, inj_radius, ph_weight_suggest, max_photons, theta_jmin_thread, theta_jmax_thread, &hydrodata, rng, 0, 0, fPtr); } #endif fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: propagating and scattering %d photons\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,num_ph-num_null_ph); fflush(fPtr); frame_scatt_cnt=0; frame_abs_cnt=0; find_nearest_grid_switch=1; // set to true so the function findNearestPropertiesAndMinMFP by default finds the index of the grid block closest to each photon since we just read in a file and the prior index is invalid num_photons_find_new_element=0; n_comptonized=0; while (time_now<((scatt_frame+hydrodata.increment_scatt_frame)/hydrodata.fps)) { //if simulation time is less than the simulation time of the next frame, keep scattering in this frame //for RIKEN hydro data, theres still 10 fps but after frame 3000, file increment is 10 not 1, therefore modify dt_max not fps //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path //and choose the photon with the smallest mfp and calculate the timestep num_photons_find_new_element+=findNearestPropertiesAndMinMFP(phPtr, num_ph, all_time_steps, sorted_indexes, &hydrodata, rng, find_nearest_grid_switch, fPtr); find_nearest_grid_switch=0; //set to zero (false) since we do not absolutely need to refind the index, this makes the function findNearestPropertiesAndMinMFP just check if the photon is w/in the given grid box still if (*(all_time_steps+(*(sorted_indexes+0)))<dt_max) { //scatter the photon //fprintf(fPtr, "Passed Parameters: %e, %e, %e\n", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr)); time_step=photonEvent( phPtr, num_ph, dt_max, all_time_steps, sorted_indexes, &hydrodata, &ph_scatt_index, &frame_scatt_cnt, &frame_abs_cnt, rng, fPtr ); time_now+=time_step; //see if the scattered phton was a seed photon, if so replenish the seed photon #if CYCLOSYNCHROTRON_SWITCH == ON if ((phPtr+ph_scatt_index)->type == CS_POOL_PHOTON) { n_comptonized+=(phPtr+ph_scatt_index)->weight; (phPtr+ph_scatt_index)->type = COMPTONIZED_PHOTON; //c for compton scattered synchrotron photon //fprintf(fPtr, "num_null_ph %d\n", num_null_ph); //printf("The previous scattered photon was a seed photon %c.\n", (phPtr+ph_scatt_index)->type); num_cyclosynch_ph_emit+=photonEmitCyclosynch(&phPtr, &num_ph, &num_null_ph, &all_time_steps, &sorted_indexes, inj_radius, ph_weight_suggest, max_photons, theta_jmin_thread, theta_jmax_thread, &hydrodata, rng, 1, ph_scatt_index, fPtr); //fprintf(fPtr, " num_photon: %d\n",num_ph ); //fflush(fPtr); scatt_cyclosynch_num_ph++;//keep track of the number of synch photons that have scattered for later in checking of we need to rebin them //fprintf(fPtr,"photonEmitCyclosynch: scatt_cyclosynch_num_ph Number: %d\n", scatt_cyclosynch_num_ph); //exit(0); } #endif if ((frame_scatt_cnt%1000 == 0) && (frame_scatt_cnt != 0)) //modified this so it doesn't print when all photons get absorbed at first and frame_scatt_cnt=0 { fprintf(fPtr,"Scattering Number: %d\n", frame_scatt_cnt); fprintf(fPtr,"The local temp is: %e K\n", *(hydrodata.temp + (phPtr+ph_scatt_index)->nearest_block_index) ); fprintf(fPtr,"Average photon energy is: %e ergs\n", averagePhotonEnergy(phPtr, num_ph)); //write function to average over the photons p0 can then do (1.6e-9) to get keV fprintf(fPtr,"The last time step was: %e.\nThe time now is: %e\n", time_step,time_now); //fprintf(fPtr,"Before Rebin: The average number of scatterings thus far is: %lf\nThe average position of photons is %e\n", avg_scatt, avg_r); fflush(fPtr); #if CYCLOSYNCHROTRON_SWITCH == ON if (scatt_cyclosynch_num_ph>max_photons) { //if the number of synch photons that have been scattered is too high rebin them //printf("num_cyclosynch_ph_emit: %d\n", num_cyclosynch_ph_emit); rebinCyclosynchCompPhotons(&phPtr, &num_ph, &num_null_ph, &num_cyclosynch_ph_emit, &scatt_cyclosynch_num_ph, &all_time_steps, &sorted_indexes, max_photons, theta_jmin_thread, theta_jmax_thread, rng, fPtr); //fprintf(fPtr, "rebinSynchCompPhotons: scatt_cyclosynch_num_ph: %d\n", scatt_cyclosynch_num_ph); //exit(0); } #endif } //exit(0); } else { time_now+=dt_max; //for each photon update its position based on its momentum updatePhotonPosition(phPtr, num_ph, dt_max, fPtr); } //printf("In main 2: %e, %d, %e, %e\n", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); } #if CYCLOSYNCHROTRON_SWITCH == ON if ((scatt_frame != scatt_framestart) || (restrt==CONTINUE)) //rememebr to change to != also at the other place in the code //if ((scatt_frame == scatt_framestart) || (restrt==CONTINUE)) //for testing { if (scatt_cyclosynch_num_ph>max_photons) { //rebin the photons to ensure that we have a constant amount here fprintf(fPtr, "Num_ph: %d\n", num_ph); /* fprintf(fPtr,"Before Rebin: The average number of scatterings thus far is: %lf\nThe average position of photons is %e\n", avg_scatt, avg_r); fflush(fPtr); */ rebinCyclosynchCompPhotons(&phPtr, &num_ph, &num_null_ph, &num_cyclosynch_ph_emit, &scatt_cyclosynch_num_ph, &all_time_steps, &sorted_indexes, max_photons, theta_jmin_thread, theta_jmax_thread, rng, fPtr); //exit(0); } //make sure the photons that shou;d be absorbed should be absorbed if we have actually emitted any synchrotron photons if (num_cyclosynch_ph_emit>0) { n_comptonized-=phAbsCyclosynch(&phPtr, &num_ph, &frame_abs_cnt, &scatt_cyclosynch_num_ph, &hydrodata, fPtr);//(&phPtr, &num_ph, &frame_abs_cnt, &scatt_cyclosynch_num_ph, tempPtr, densPtr, fPtr); } } #endif //get scattering statistics phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt, &avg_r, fPtr); fprintf(fPtr,"The number of scatterings in this frame is: %d\n", frame_scatt_cnt); #if CYCLOSYNCHROTRON_SWITCH == ON fprintf(fPtr,"The number of cyclosynchrotron photons absorbed in this frame is: %d\n", frame_abs_cnt); #endif fprintf(fPtr,"The last time step was: %e.\nThe time now is: %e\n", time_step,time_now); fprintf(fPtr,"MCRaT had to refind the position of photons %d times in this frame.\n", num_photons_find_new_element); fprintf(fPtr,"The maximum number of scatterings for a photon is: %d\nThe minimum number of scatterings for a photon is: %d\n", max_scatt, min_scatt); fprintf(fPtr,"The average number of scatterings thus far is: %lf\nThe average position of photons is %e\n", avg_scatt, avg_r); fflush(fPtr); fprintf(fPtr, ">> Proc %d with angles %0.1lf-%0.1lf: Making checkpoint file\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); fflush(fPtr); //fprintf(fPtr, " mc_dir: %s\nframe %d\nfrm2: %d\nscatt_frame: %d\n num_photon: %d\ntime_now: %e\nlast_frame: %d\n", mc_dir, frame, frm2, scatt_frame, num_ph, time_now, last_frm ); //fprintf(fPtr,"n_comptonized in this frame is: %e\n ", n_comptonized); //fflush(fPtr); save_chkpt_success=saveCheckpoint(mc_dir, frame, frm2, scatt_frame, num_ph, time_now, phPtr, last_frm, angle_id, old_num_angle_procs); if (save_chkpt_success==0) { //if we saved the checkpoint successfully also save the photons to the hdf5 file, else there may be something wrong with the file system printPhotons(phPtr, num_ph, frame_abs_cnt, num_cyclosynch_ph_emit, num_null_ph, scatt_cyclosynch_num_ph, scatt_frame , frame, last_frm, mc_dir, angle_id, fPtr); } else { fprintf(fPtr, "There is an issue with opening and saving the chkpt file therefore MCRaT is not saving data to the checkpoint or mc_proc files to prevent corruption of those data.\n"); printf("There is an issue with opening and saving the chkpt file therefore MCRaT is not saving data to the checkpoint or mc_proc files to prevent corruption of those data.\n"); fflush(fPtr); exit(1); } #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE { { free(zPtr);free(phiPtr);free(velzPtr); zPtr=NULL; phiPtr=NULL; velzPtr=NULL; } } #endif free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr); free(gammaPtr);free(dens_labPtr);free(tempPtr); xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL; szxPtr=NULL; szyPtr=NULL; tempPtr=NULL; free(all_time_steps); //malloc is called in for loop therefore free memory at th end of the loop all_time_steps=NULL; free(sorted_indexes); sorted_indexes=NULL; freeHydroDataFrame(&hydrodata); } restrt=INITALIZE;//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file scatt_cyclosynch_num_ph=0; //set this back equal to 0 for next batch of injected/emitted photons starting from nect injection frame num_null_ph=0; //set this back equal to 0 for next batch of injected/emitted photons starting from nect injection frame free(phPtr); phPtr=NULL; free(all_time_steps); all_time_steps=NULL; free(sorted_indexes); sorted_indexes=NULL; } save_chkpt_success=saveCheckpoint(mc_dir, frame, frm2, scatt_frame, 0, time_now, phPtr, last_frm, angle_id, old_num_angle_procs); //this is for processes using the old code that didnt restart efficiently fprintf(fPtr, "Process %d has completed the MC calculation.\n", angle_id); fflush(fPtr); //exit(0); MPI_Barrier(angle_comm); //merge files from each worker thread within a directory hydrodata.increment_scatt_frame=1; file_count=0; //count number of files for (i=frm0;i<=last_frm;i=i+hydrodata.increment_scatt_frame) { #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE if (i>=3000) { hydrodata.increment_scatt_frame=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } #endif file_count++; } //holds number of files for each process to merge MPI_Comm_size(angle_comm, &angle_procs); //to get the proper number of processes within the group MPI_Comm_rank(angle_comm, &angle_id); //reset the value of angle_id to what it should actualy be to properly distribute files to merge proc_frame_size=floor(file_count/ (float) angle_procs); frame_array=malloc(file_count*sizeof(int)); proc_frame_array=malloc(angle_procs*sizeof(int)); //sets index of each proceesed acquired value element_num=malloc(angle_procs*sizeof(int)); for (i=0;i<angle_procs;i++) { *(proc_frame_array+i)=i*proc_frame_size; *(element_num+i)=1; } //make vector with the files in order to pass them to each of the processes hydrodata.increment_scatt_frame=1; file_count=0; for (i=frm0;i<=last_frm;i=i+hydrodata.increment_scatt_frame) { #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE if (i>=3000) { hydrodata.increment_scatt_frame=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } #endif *(frame_array+file_count)=i ; file_count++; //printf("file_count: %d frame: %d\n", file_count-1, *(frame_array+file_count-1)); } //pass first frame number that each rpocess should start to merge, can calulate the file it should merge until MPI_Scatterv(frame_array, element_num, proc_frame_array, MPI_INT, &frm0, 1, MPI_INT, 0, angle_comm); //fprintf(fPtr, "Value: last_frm: ,%d\n", file_count); //fflush(fPtr); //make sure all files get merged by giving the rest to the last process if (angle_id==angle_procs-1) { proc_frame_size=file_count-proc_frame_size*(angle_procs-1); //for last process take over the remaining number of files } //calculate what the last file the preocess should merge up to i=0; last_frm=frm0; while(i<proc_frame_size) { #if SIM_SWITCH == RIKEN && DIMENSIONS == THREE if (last_frm>=3000) { hydrodata.increment_scatt_frame=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } #else { hydrodata.increment_scatt_frame=1; } #endif last_frm+=hydrodata.increment_scatt_frame; i++; } //fprintf(fPtr, ">> Proc %d with angles %0.1lf-%0.1lf: Merging Files from %d to %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm0, last_frm); fprintf(fPtr, ">> Proc %d with angles %0.1lf-%0.1lf: Merging Files from %d to %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm0, last_frm); fflush(fPtr); dirFileMerge(mc_dir, frm0, last_frm, old_num_angle_procs, angle_id, fPtr); fprintf(fPtr, "Process %d has completed merging files.\n", angle_id); fflush(fPtr); fclose(fPtr); gsl_rng_free (rng); free(frame_array); free(proc_frame_array); MPI_Finalize(); return 0; }
gramschmidt.c
/** * gramschmidt.c: This file was adapted from PolyBench/GPU 1.0 test * suite to run on GPU with OpenMP 4.0 pragmas and OpenCL driver. * * http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU * * Contacts: Marcio M Pereira <mpereira@ic.unicamp.br> * Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br> * Luís Felipe Mattos <ra107822@students.ic.unicamp.br> */ #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #ifdef _OPENMP #include <omp.h> #endif #include "BenchmarksUtil.h" #define BENCHMARK_NAME "GRAMSCHM" // define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 0.05 /* Problem size. */ #ifdef RUN_POLYBENCH_SIZE #define SIZE 2048 #elif RUN_TEST #define SIZE 1100 #elif RUN_BENCHMARK #define SIZE 9600 #else #define SIZE 1000 #endif /* Problem size */ #define M SIZE #define N SIZE /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void gramschmidt(DATA_TYPE *A, DATA_TYPE *R, DATA_TYPE *Q) { int i, j, k; DATA_TYPE nrm; for (k = 0; k < N; k++) { nrm = 0; for (i = 0; i < M; i++) { nrm += A[i * N + k] * A[i * N + k]; } R[k * N + k] = sqrt(nrm); for (i = 0; i < M; i++) { Q[i * N + k] = A[i * N + k] / R[k * N + k]; } for (j = k + 1; j < N; j++) { R[k * N + j] = 0; for (i = 0; i < M; i++) { R[k * N + j] += Q[i * N + k] * A[i * N + j]; } for (i = 0; i < M; i++) { A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j]; } } } } void gramschmidt_OMP(DATA_TYPE *A, DATA_TYPE *R, DATA_TYPE *Q) { int i, j, k; DATA_TYPE nrm; #pragma omp target data map(to: R[:M*N], Q[:M*N]) map(tofrom: A[:M*N]) device(DEVICE_ID) { for (k = 0; k < N; k++) { // CPU nrm = 0; #pragma omp target update from(A[:M*N]) for (i = 0; i < M; i++) { nrm += A[i * N + k] * A[i * N + k]; } R[k * N + k] = sqrt(nrm); for (i = 0; i < M; i++) { Q[i * N + k] = A[i * N + k] / R[k * N + k]; } #pragma omp target update to(Q[:M*N]) #pragma omp target teams distribute parallel for private(i) for (j = k + 1; j < N; j++) { R[k * N + j] = 0; for (i = 0; i < M; i++) { R[k * N + j] += Q[i * N + k] * A[i * N + j]; } for (i = 0; i < M; i++) { A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j]; } } } } } void init_array(DATA_TYPE *A, DATA_TYPE *A2) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { A[i * N + j] = ((DATA_TYPE)(i + 1) * (j + 1)) / (M + 1); A2[i * N + j] = A[i * N + j]; } } } int compareResults(DATA_TYPE *A, DATA_TYPE *A_outputFromGpu) { int i, j, fail; fail = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { if (percentDiff(A[i * N + j], A_outputFromGpu[i * N + j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; // printf("i: %d j: %d \n1: %f\n 2: %f\n", i, j, A[i*N + j], // A_outputFromGpu[i*N + j]); } } } // Print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f " "Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail); return fail; } int main(int argc, char *argv[]) { double t_start, t_end; int fail = 0; DATA_TYPE *A; DATA_TYPE *A_outputFromGpu; DATA_TYPE *R; DATA_TYPE *Q; A = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); A_outputFromGpu = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); R = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); Q = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); //fprintf(stdout, "<< Gram-Schmidt decomposition >>\n"); printBenchmarkInfo(BENCHMARK_NAME, SIZE); init_array(A, A_outputFromGpu); t_start = rtclock(); gramschmidt_OMP(A_outputFromGpu, R, Q); t_end = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start); #ifdef RUN_TEST t_start = rtclock(); gramschmidt(A, R, Q); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); fail = compareResults(A, A_outputFromGpu); #endif free(A); free(A_outputFromGpu); free(R); free(Q); return fail; }
Example_async_target.3.c
/* * @@name: async_target.3c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.5 */ #include <stdio.h> #define N 1000000 //N must be even void init(int n, float *v1, float *v2); int main(){ int i, n=N; int chunk=1000; float v1[N],v2[N],vxv[N]; init(n, v1,v2); #pragma omp parallel { #pragma omp master #pragma omp target teams distribute parallel for nowait \ map(to: v1[0:n/2]) \ map(to: v2[0:n/2]) \ map(from: vxv[0:n/2]) for(i=0; i<n/2; i++){ vxv[i] = v1[i]*v2[i]; } #pragma omp for schedule(dynamic,chunk) for(i=n/2; i<n; i++){ vxv[i] = v1[i]*v2[i]; } } printf(" vxv[0] vxv[n-1] %f %f\n", vxv[0], vxv[n-1]); return 0; }
mst.c
#include <stdlib.h> #include <stdio.h> #include <omp.h> #include <limits.h> #include "ompdist/vector.h" #include "ompdist/queues.h" #include "ompdist/graph.h" #include "ompdist/graph_gen.h" #include "ompdist/utils.h" #include "ompdist/msr.h" #include "config.h" typedef struct { int from; } message; typedef struct { int u; int v; int w; } edge; typedef struct { int fragment_id; int tmp_fragment_id; int received_first_message; edge* b; } payload; /** * initialize_graph: Initializes the graph. * * @g: the graph */ void initialize_graph(graph* g) { DEBUG("initializing the graph\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = malloc(sizeof(payload)); u->data = u_data; u_data->fragment_id = u->label; u_data->tmp_fragment_id = u->label; u_data->received_first_message = 0; u_data->b = NULL; } } /** * multiple_fragments - Checks if there are multiple fragments in the graph. * * @g: the graph * * Returns 1 if there are mutiple fragments. Returns 0 if there's just one * fragment (indicating that our algorithm has comepleted). */ int multiple_fragments(graph* g) { int multiple = 0; int last = -1; DEBUG("checking if there are multiple fragments\n"); for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; if (last == -1) last = u_data->fragment_id; else if (u_data->fragment_id != last) { multiple = 1; break; } } return multiple; } /** * change_fragment - Changes all the nodes in a fragment to another fragment. * * @g: the graph * @from: the source fragment ID * @to: the destination fragment ID */ void change_fragment(graph* g, int from, int to) { DEBUG("changing all nodes with fragment_id=%d to %d\n", from, to); for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; if (u_data->fragment_id == from) u_data->fragment_id = to; } } /** * find_blue_edges - Finds the blue edge of each fragment using flooding-echo. * * @g: the graph * @msgs: each node's messages * @tmp_msgs: temporary queuelist holder for each node's messages * @blues: queuelist of potential blue edges for each node */ void find_blue_edges(graph* g, queuelist* msgs, queuelist* tmp_msgs, queuelist* blues) { DEBUG("planting root messages\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; u_data->received_first_message = 0; /* Only roots find the blue edge */ if (u_data->fragment_id != u->label) continue; message m = {-1}; enqueue(msgs, u->label, &m); } int nodes_yet_to_recv = 1; DEBUG("accumulating blue edges\n"); while (nodes_yet_to_recv) { DEBUG("propagating the messages across the graph\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; if (u_data->received_first_message) continue; while (!is_ql_queue_empty(msgs, u->label)) { u_data->received_first_message = 1; message* m = dequeue(msgs, u->label); for (int j = 0; j < u->degree; j++) { node* v = *((node**) elem_at(&u->neighbors, j)); payload* v_data = v->data; /* Don't send the message back to the source */ if (v->label == m->from) continue; /** * If the neighbor is outside the fragment it's a potential * blue edge. Otherwise it's just a carrier for this message. */ if (v_data->fragment_id != u_data->fragment_id) { edge b = {u->label, v->label, g->adj_mat[u->label][v->label]}; enqueue(blues, u_data->fragment_id, &b); } else { message mx = {u->label}; enqueue(tmp_msgs, v->label, &mx); } } } } DEBUG("moving messages from tmp_msgs to msgs\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; while (!is_ql_queue_empty(tmp_msgs, u->label)) { message* m = dequeue(tmp_msgs, u->label); if (!u_data->received_first_message) enqueue(msgs, u->label, m); } } nodes_yet_to_recv = 0; DEBUG("checking if there are any more nodes left to process\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; if (!u_data->received_first_message) nodes_yet_to_recv = 1; } DEBUG("nodes_yet_to_recv = %d\n", nodes_yet_to_recv); } /** * Find the minimum blue edge of all potential blue edge candidates for * each fragment. The actual data still lives on in the `blues` queue and * it won't be lost till the next phase, at which point we don't need it * anyway since all bridges would have happened. */ DEBUG("finding the minimum of the accumulated blue edges\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; /* only roots find the blue edge */ if (u_data->fragment_id != u->label) continue; edge* min_edge = NULL; while (!is_ql_queue_empty(blues, u->label)) { edge* b = dequeue(blues, u->label); if (min_edge == NULL) { min_edge = b; continue; } /** * So this might look like some kind of weird logic, but there's a * reason why I'm doing this: say there are two different fragments * with blue edges into each other. If the two blue edges are the * same, it's perfectly fine -- it'll be resolved in the conflicting * blue edges scennario. However, if they're different, they'll * both be added to the MST when it should only be one of them. To * prevent this, we'll simply use the edge that has a smaller value * of (u*N + v). Note that both will have the exact same weight, * so it's fine whichever one we choose. */ int b_score = b->u*g->N + b->v; if (b->u > b->v) b_score = b->v*g->N + b->u; int min_score = min_edge->u*g->N + min_edge->v; if (min_edge->u > min_edge->v) min_score = min_edge->v*g->N + min_edge->u; if ((b->w < min_edge->w) || (b->w == min_edge->w && b_score < min_score)) min_edge = b; } node* future_leader = elem_at(&g->vertices, min_edge->u); payload* future_leader_data = future_leader->data; u_data->b = min_edge; future_leader_data->b = min_edge; } } /** * assign_tmp_fragments - Temporarily sets the fragment ID of each element in * a fragment to that of the element in the blue edge. * * @g: the graph */ void assign_tmp_fragments(graph* g) { DEBUG("setting tmp_fragment_id\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; node* leader = elem_at(&g->vertices, u_data->fragment_id); payload* leader_data = leader->data; u_data->tmp_fragment_id = leader_data->b->u; } DEBUG("setting temporary fragment_id\n"); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; u_data->fragment_id = u_data->tmp_fragment_id; } } /** * merge_fragments - Merges the fragments by merging the non-conflicting (merge * requests (u, v, w) such that there's no merge request (v, u, w)) followed * by conflicting ones. * * @g: the graph * @mst: a queuelist to store a list of edges (in the MST) in */ void merge_fragments(graph* g, queuelist* mst) { /** * `ok` denotes whether conflicting merges are okay to merge. This is done * so that non-conflicting merge requests are merged first and the conflicting * ones are done so later. */ for (int ok = 0; ok < 2; ok++) { DEBUG("conflicts phase: %d\n", ok); #pragma omp parallel for schedule(SCHEDULING_METHOD) for (int i = 0; i < g->N; i++) { node* u = elem_at(&g->vertices, i); payload* u_data = u->data; if (u_data->fragment_id != u->label) continue; #pragma omp critical { node* v = elem_at(&g->vertices, u_data->b->v); payload* v_data = v->data; node* v_leader = elem_at(&g->vertices, v_data->fragment_id); payload* v_leader_data = v_leader->data; int conflicting_merges = (u->label == v_leader_data->b->v && v_leader_data->b->u == v->label && u_data->b->v == v->label); if (conflicting_merges == ok) { change_fragment(g, u->label, v_leader->label); edge m = {u->label, v->label, g->adj_mat[u->label][v->label]}; enqueue(mst, 0, &m); } } } } } /** * verify_and_print_solution - Verifies if the produced solution is correct * using Prim's algorithm to compute the minimum spanning tree. * * @g: the graph * @mst: a queuelist to store a list of edges (in the MST) in * * Returns 0 if everything is correct. Returns 1 otherwise. */ int verify_and_print_solution(graph* g, queuelist* mst) { long long int computed_weight = 0; while (!is_ql_queue_empty(mst, 0)) { edge* e = dequeue(mst, 0); computed_weight += e->w; INFO("(%d, %d, %d)\n", e->u, e->v, e->w); } long long int actual_weight = 0; int done = 0; int* in_mst = malloc(g->N * sizeof(int)); int* parent = malloc(g->N * sizeof(int)); int* d = malloc(g->N * sizeof(int)); for (int i = 0; i < g->N; i++) { in_mst[i] = 0; parent[i] = -1; d[i] = INT_MAX; } d[0] = 0; while (done < g->N) { done++; int min = INT_MAX; int min_idx = 0; for (int i = 0; i < g->N; i++) { if (!in_mst[i] && min >= d[i]) { min = d[i]; min_idx = i; } } node* u = elem_at(&g->vertices, min_idx); in_mst[u->label] = 1; for (int i = 0; i < u->degree; i++) { node* v = *((node**) elem_at(&u->neighbors, i)); int w = g->adj_mat[u->label][v->label]; if (in_mst[v->label] == 0 && w < d[v->label]) { d[v->label] = w; parent[v->label] = u->label; } } } for (int i = 1; i < g->N; i++) actual_weight += g->adj_mat[i][parent[i]]; if (actual_weight == computed_weight) INFO("correct! computed tree is the MST\n"); else INFO("incorrect: actual_weight=%lld, computed_weight=%lld\n", actual_weight, computed_weight); return computed_weight != actual_weight; } /** * Based on Roger Wattenhofer's Principles of Distributed Computing's * Algorithm 2.18 (Gallager-Humblet-Spira) to find the minimum spanning * tree of a weighted graph in a distributed manner. */ int main(int argc, char* argv[]) { int N; int M; graph* g; int iterate; int iterations = 1; if ((iterate = input_through_argv(argc, argv))) { FILE* in = fopen(argv[2], "r"); fscanf(in, "%d\n", &N); g = new_graph(N, 0); g->M = M = read_graph(g, in); read_weights(g, in); fclose(in); sscanf(argv[3], "%d", &iterations); } else { N = 16; M = 64; if (argc > 1) { sscanf(argv[1], "%d", &N); sscanf(argv[2], "%d", &M); } g = generate_new_connected_graph(N, M); } long long duration = 0; double total_energy = 0; int verification; for (int i = 0; i < iterations; i++) { queuelist* msgs = new_queuelist(g->N, sizeof(message)); queuelist* tmp_msgs = new_queuelist(g->N, sizeof(message)); queuelist* blues = new_queuelist(g->N, sizeof(edge)); queuelist* mst = new_queuelist(1, sizeof(edge)); begin_timer(); init_energy_measure(); initialize_graph(g); while (multiple_fragments(g)) { find_blue_edges(g, msgs, tmp_msgs, blues); assign_tmp_fragments(g); merge_fragments(g, mst); } total_energy += total_energy_used(); duration += time_elapsed(); free_queuelist(msgs); free_queuelist(tmp_msgs); free_queuelist(blues); verification = verify_and_print_solution(g, mst); free_queuelist(mst); } if (iterate) printf("%.2lf %.2lf\n", ((double) duration) / iterations, total_energy / iterations); return verification; }
GB_unop__cosh_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__cosh_fc32_fc32) // op(A') function: GB (_unop_tran__cosh_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = ccoshf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ccoshf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = ccoshf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_COSH || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cosh_fc32_fc32) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = ccoshf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = ccoshf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cosh_fc32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
gen_int_grid.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include "gen_Lebedev_grid.h" const static double BOHR = 0.52917721092; const static int Leb_ngrid[33] = { 1, 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810 }; // Need to multiple by (1.0 / BOHR) to get the real RADII_BRAGG const static double RADII_BRAGG[] = { 0.35, 1.40, // 1s 1.45, 1.05, 0.85, 0.70, 0.65, 0.60, 0.50, 1.50, // 2s2p 1.80, 1.50, 1.25, 1.10, 1.00, 1.00, 1.00, 1.80, // 3s3p 2.20, 1.80, // 4s 1.60, 1.40, 1.35, 1.40, 1.40, 1.40, 1.35, 1.35, 1.35, 1.35, // 3d 1.30, 1.25, 1.15, 1.15, 1.15, 1.90, // 4p 2.35, 2.00, // 5s 1.80, 1.55, 1.45, 1.45, 1.35, 1.30, 1.35, 1.40, 1.60, 1.55, // 4d 1.55, 1.45, 1.45, 1.40, 1.40, 2.10, // 5p 2.60, 2.15, // 6s 1.95, 1.85, 1.85, 1.85, 1.85, 1.85, 1.85, // La, Ce-Eu 1.80, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, // Gd, Tb-Lu 1.55, 1.45, 1.35, 1.35, 1.30, 1.35, 1.35, 1.35, 1.50, // 5d 1.90, 1.80, 1.60, 1.90, 1.45, 2.10, // 6p 1.80, 2.15, // 7s 1.95, 1.80, 1.80, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75 }; static double alphas[3][4] = { {0.25, 0.5, 1.0, 4.5}, {0.16667, 0.5, 0.9, 3.5}, {0.1, 0.4, 0.8, 2.5} }; // Generate Becke grid points for radial integral // Ref: [JCP 88, 2547], DOI: 10.1063/1.454033 // Input parameters: // npt2 : Total number of grid points+2 // rm : A parameter mentioned in Ref, directly use 1.0 is fine // Output parameters: // rad_r : Size npt2-2, radial direction integral points // rad_w : Size npt2-2, radial direction integral weights static void gen_Becke_grid(const int npt2, const double rm, double *rad_r, double *rad_w) { int npt1 = npt2 - 1; int npt = npt2 - 2; double pi_over_npt1 = M_PI / (double) npt1; double rm3 = rm * rm * rm; // Skip i = 0, since rad_r(0) = rad_w(0) = inf // Skip i = npt1, since rad_r(npt1) = rad_w(npt1) = 0 #pragma omp simd for (int i = 1; i <= npt; i++) { // radr and radw formulas come from: http://sobereva.com/69 , // or multiwfn v3.7 fuzzy.f90, line 449 double radx = cos((double) i * pi_over_npt1); double radr = rm * (1.0 + radx) / (1.0 - radx); double tmp0 = pow(1.0 + radx, 2.5); double tmp1 = pow(1.0 - radx, 3.5); double radw = (2.0 * pi_over_npt1) * rm3 * tmp0 / tmp1; rad_r[npt - i] = radr; rad_w[npt - i] = radw; } } // Prune grids using NWChem scheme // Ref: // 1. https://github.com/pyscf/pyscf/blob/master/pyscf/dft/gen_grid.py // 2. https://github.com/pyscf/pyscf/blob/master/pyscf/data/radii.py // Input parameters: // nuc : Nuclear charge (== atom index) // n_ang : Maximum number of angular grids // n_rad : Number of radial grids // rads : Array, size n_rad, radial grid coordinates // Output parameter: // rad_n_ang : Array, size n_rad, number of angular grids for each radial grid // <return> : Total number of grid points, == sum(rad_n_ang) static int NWChem_prune_grid( const int nuc, const int n_ang, const int n_rad, const double *rads, int *rad_n_ang ) { int Leb_lvl[5] = {4, 5, 5, 5, 4}; if (n_ang < 50) { for (int i = 0; i < n_rad; i++) rad_n_ang[i] = n_ang; return (n_ang * n_rad); } if (n_ang > 50) { int idx; for (idx = 6; idx < 33; idx++) if (n_ang == Leb_ngrid[idx]) break; Leb_lvl[1] = 6; Leb_lvl[2] = idx - 1; Leb_lvl[3] = idx; Leb_lvl[4] = idx - 1; } int npt = 0; double r_atom = (1.0 / BOHR) * RADII_BRAGG[nuc - 1]; for (int i = 0; i < n_rad; i++) { double rad_i_scale = rads[i] / r_atom; double *alpha_i; if (nuc > 10) alpha_i = alphas[2]; if (nuc <= 10) alpha_i = alphas[1]; if (nuc <= 2) alpha_i = alphas[0]; int place; for (place = 0; place < 4; place++) if (rad_i_scale <= alpha_i[place]) break; rad_n_ang[i] = Leb_ngrid[Leb_lvl[place]]; npt += rad_n_ang[i]; } return npt; } // Generate numerical integral points for XC calculations void gen_int_grid( const int natom, const double *atom_xyz, const int *atom_idx, int *npoint_, double **int_grid_ ) { double rm = 1.0; int max_rad = 65; int max_ang = 302; int max_atom_npt = max_rad * max_ang; int max_total_npt = natom * max_atom_npt; double *int_grid = (double*) malloc(sizeof(double) * 4 * max_total_npt); double *dist = (double*) malloc(sizeof(double) * natom * natom); assert(int_grid != NULL && dist != NULL); double *ipx = int_grid + 0 * max_total_npt; double *ipy = int_grid + 1 * max_total_npt; double *ipz = int_grid + 2 * max_total_npt; double *ipw = int_grid + 3 * max_total_npt; const double *atom_x = atom_xyz + 0 * natom; const double *atom_y = atom_xyz + 1 * natom; const double *atom_z = atom_xyz + 2 * natom; for (int i = 0; i < natom; i++) { #pragma omp simd for (int j = 0; j < natom; j++) { double dx = atom_x[i] - atom_x[j]; double dy = atom_y[i] - atom_y[j]; double dz = atom_z[i] - atom_z[j]; double r2 = dx * dx + dy * dy + dz * dz; dist[i * natom + j] = sqrt(r2); } } double *rad_r = (double*) malloc(sizeof(double) * max_rad); double *rad_w = (double*) malloc(sizeof(double) * max_rad); int *rad_n_ang = (int*) malloc(sizeof(int) * max_rad); double *leb_tmp = (double*) malloc(sizeof(double) * max_ang * 4); double *atom_grid = (double*) malloc(sizeof(double) * max_atom_npt * 4); double *W_mat = (double*) malloc(sizeof(double) * natom * natom * max_atom_npt); double *dip = (double*) malloc(sizeof(double) * natom * max_atom_npt); double *pvec = (double*) malloc(sizeof(double) * natom * max_atom_npt); double *sum_pvec = (double*) malloc(sizeof(double) * max_atom_npt); assert(rad_r != NULL && rad_w != NULL && rad_n_ang != NULL); assert(leb_tmp != NULL && W_mat != NULL && atom_grid != NULL); assert(dip != NULL && pvec != NULL && sum_pvec != NULL); int total_npt = 0; for (int iatom = 0; iatom < natom; iatom++) { // (1) Prune grid points according to atom type int n_ang = max_ang; int n_rad = max_rad; if (atom_idx[iatom] <= 10) n_rad = 50; if (atom_idx[iatom] <= 2) n_rad = 35; gen_Becke_grid(n_rad + 2, rm, rad_r, rad_w); int atom_npt = NWChem_prune_grid(atom_idx[iatom], n_ang, n_rad, rad_r, rad_n_ang); // (2) Generate Lebedev points & weights and combine it // with radial direction points & weights int atom_idx = 0; double *atom_ipx = atom_grid + 0 * atom_npt; double *atom_ipy = atom_grid + 1 * atom_npt; double *atom_ipz = atom_grid + 2 * atom_npt; double *atom_ipw = atom_grid + 3 * atom_npt; for (int i = 0; i < n_rad; i++) { int npt_i = gen_Lebedev_grid(rad_n_ang[i], leb_tmp); #pragma omp simd for (int j = 0; j < rad_n_ang[i]; j++) { atom_ipx[atom_idx + j] = leb_tmp[j * 4 + 0] * rad_r[i]; atom_ipy[atom_idx + j] = leb_tmp[j * 4 + 1] * rad_r[i]; atom_ipz[atom_idx + j] = leb_tmp[j * 4 + 2] * rad_r[i]; atom_ipw[atom_idx + j] = leb_tmp[j * 4 + 3] * rad_w[i] * 4 * M_PI; atom_ipx[atom_idx + j] += atom_x[iatom]; atom_ipy[atom_idx + j] += atom_y[iatom]; atom_ipz[atom_idx + j] += atom_z[iatom]; } atom_idx += npt_i; } // End of i loop #pragma omp parallel { // (3) Calculate the mask tensor and the actual weights // W_mat(j, k, i): fuzzy weight of integral point i to atom pair (j, k) #pragma omp for for (int j = 0; j < natom; j++) { double *dip_j = dip + j * atom_npt; #pragma omp simd for (int i = 0; i < atom_npt; i++) { double dx = atom_ipx[i] - atom_x[j]; double dy = atom_ipy[i] - atom_y[j]; double dz = atom_ipz[i] - atom_z[j]; dip_j[i] = sqrt(dx * dx + dy * dy + dz * dz); } } // End of j loop #pragma omp barrier #pragma omp for for (int j = 0; j < natom; j++) { for (int k = 0; k < natom; k++) { double *dip_j = dip + j * atom_npt; double *dip_k = dip + k * atom_npt; double *W_jk = W_mat + (j * natom + k) * atom_npt; if (j == k) { for (int i = 0; i < atom_npt; i++) W_jk[i] = 1.0; } else { double inv_djk = 1.0 / dist[j * natom + k]; #pragma omp simd for (int i = 0; i < atom_npt; i++) { double mu = (dip_j[i] - dip_k[i]) * inv_djk; // s(d(i,j)) = 0.5 * (1 - p(p(p(d(i,j))))) mu = 1.5 * mu - 0.5 * mu * mu * mu; mu = 1.5 * mu - 0.5 * mu * mu * mu; mu = 1.5 * mu - 0.5 * mu * mu * mu; W_jk[i] = 0.5 * (1.0 - mu); } } // End of "if (j == k)" } // End of k loop } // End of j loop // (4) Calculate the final integral weights // \prod_{k} W_mat(j, k, :) is the actual weight of integral points // belonging to atom k. Normalizing it gives us the fuzzy weight. #pragma omp for simd for (int i = 0; i < natom * atom_npt; i++) pvec[i] = 1.0; #pragma omp for simd for (int i = 0; i < atom_npt; i++) sum_pvec[i] = 0.0; #pragma omp barrier #pragma omp for for (int j = 0; j < natom; j++) { double *pvec_j = pvec + j * atom_npt; for (int k = 0; k < natom; k++) { double *W_jk = W_mat + (j * natom + k) * atom_npt; #pragma omp simd for (int i = 0; i < atom_npt; i++) pvec_j[i] *= W_jk[i]; } } #pragma omp barrier for (int j = 0; j < natom; j++) { double *pvec_j = pvec + j * atom_npt; #pragma omp for simd for (int i = 0; i < atom_npt; i++) sum_pvec[i] += pvec_j[i]; } } // End of "pragma omp parallel" // Copy final integral points & weights to the output matrix double *pvec_iatom = pvec + iatom * atom_npt; for (int i = 0; i < atom_npt; i++) { ipx[total_npt + i] = atom_ipx[i]; ipy[total_npt + i] = atom_ipy[i]; ipz[total_npt + i] = atom_ipz[i]; ipw[total_npt + i] = atom_ipw[i] * pvec_iatom[i] / sum_pvec[i]; } total_npt += atom_npt; } // End of iatom loop double *new_int_grid = (double*) malloc(sizeof(double) * total_npt * 4); assert(new_int_grid != NULL); memcpy(new_int_grid + 0 * total_npt, ipx, sizeof(double) * total_npt); memcpy(new_int_grid + 1 * total_npt, ipy, sizeof(double) * total_npt); memcpy(new_int_grid + 2 * total_npt, ipz, sizeof(double) * total_npt); memcpy(new_int_grid + 3 * total_npt, ipw, sizeof(double) * total_npt); *npoint_ = total_npt; *int_grid_ = new_int_grid; free(int_grid); free(dist); free(rad_r); free(rad_w); free(rad_n_ang); free(leb_tmp); free(atom_grid); free(W_mat); free(dip); free(pvec); free(sum_pvec); }
graph_generator.c
/* Copyright (C) 2009-2010 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #include <stdlib.h> #include <stdint.h> #include <assert.h> #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include "user_settings.h" #include "splittable_mrg.h" #include "graph_generator.h" /* Initiator settings: for faster random number generation, the initiator * probabilities are defined as fractions (a = INITIATOR_A_NUMERATOR / * INITIATOR_DENOMINATOR, b = c = INITIATOR_BC_NUMERATOR / * INITIATOR_DENOMINATOR, d = 1 - a - b - c. */ #define INITIATOR_A_NUMERATOR 5700 #define INITIATOR_BC_NUMERATOR 1900 #define INITIATOR_DENOMINATOR 10000 /* If this macro is defined to a non-zero value, use SPK_NOISE_LEVEL / * INITIATOR_DENOMINATOR as the noise parameter to use in introducing noise * into the graph parameters. The approach used is from "A Hitchhiker's Guide * to Choosing Parameters of Stochastic Kronecker Graphs" by C. Seshadhri, Ali * Pinar, and Tamara G. Kolda (http://arxiv.org/abs/1102.5046v1), except that * the adjustment here is chosen based on the current level being processed * rather than being chosen randomly. */ #define SPK_NOISE_LEVEL 0 /* #define SPK_NOISE_LEVEL 1000 -- in INITIATOR_DENOMINATOR units */ static int generate_4way_bernoulli(mrg_state* st, int level, int nlevels) { #if SPK_NOISE_LEVEL == 0 /* Avoid warnings */ (void)level; (void)nlevels; #endif /* Generate a pseudorandom number in the range [0, INITIATOR_DENOMINATOR) * without modulo bias. */ static const uint32_t limit = (UINT32_C(0x7FFFFFFF) % INITIATOR_DENOMINATOR); uint32_t val = mrg_get_uint_orig(st); if (/* Unlikely */ val < limit) { do { val = mrg_get_uint_orig(st); } while (val < limit); } #if SPK_NOISE_LEVEL == 0 int spk_noise_factor = 0; #else int spk_noise_factor = 2 * SPK_NOISE_LEVEL * level / nlevels - SPK_NOISE_LEVEL; #endif unsigned int adjusted_bc_numerator = (unsigned int)(INITIATOR_BC_NUMERATOR + spk_noise_factor); val %= INITIATOR_DENOMINATOR; if (val < adjusted_bc_numerator) return 1; val = (uint32_t)(val - adjusted_bc_numerator); if (val < adjusted_bc_numerator) return 2; val = (uint32_t)(val - adjusted_bc_numerator); #if SPK_NOISE_LEVEL == 0 if (val < INITIATOR_A_NUMERATOR) return 0; #else if (val < INITIATOR_A_NUMERATOR * (INITIATOR_DENOMINATOR - 2 * INITIATOR_BC_NUMERATOR) / (INITIATOR_DENOMINATOR - 2 * adjusted_bc_numerator)) return 0; #endif #if SPK_NOISE_LEVEL == 0 /* Avoid warnings */ (void)level; (void)nlevels; #endif return 3; } /* Reverse bits in a number; this should be optimized for performance * (including using bit- or byte-reverse intrinsics if your platform has them). * */ static inline uint64_t bitreverse(uint64_t x) { #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) #define USE_GCC_BYTESWAP /* __builtin_bswap* are in 4.3 but not 4.2 */ #endif #ifdef FAST_64BIT_ARITHMETIC /* 64-bit code */ #ifdef USE_GCC_BYTESWAP x = __builtin_bswap64(x); #else x = (x >> 32) | (x << 32); x = ((x >> 16) & UINT64_C(0x0000FFFF0000FFFF)) | ((x & UINT64_C(0x0000FFFF0000FFFF)) << 16); x = ((x >> 8) & UINT64_C(0x00FF00FF00FF00FF)) | ((x & UINT64_C(0x00FF00FF00FF00FF)) << 8); #endif x = ((x >> 4) & UINT64_C(0x0F0F0F0F0F0F0F0F)) | ((x & UINT64_C(0x0F0F0F0F0F0F0F0F)) << 4); x = ((x >> 2) & UINT64_C(0x3333333333333333)) | ((x & UINT64_C(0x3333333333333333)) << 2); x = ((x >> 1) & UINT64_C(0x5555555555555555)) | ((x & UINT64_C(0x5555555555555555)) << 1); return x; #else /* 32-bit code */ uint32_t h = (uint32_t)(x >> 32); uint32_t l = (uint32_t)(x & UINT32_MAX); #ifdef USE_GCC_BYTESWAP h = __builtin_bswap32(h); l = __builtin_bswap32(l); #else h = (h >> 16) | (h << 16); l = (l >> 16) | (l << 16); h = ((h >> 8) & UINT32_C(0x00FF00FF)) | ((h & UINT32_C(0x00FF00FF)) << 8); l = ((l >> 8) & UINT32_C(0x00FF00FF)) | ((l & UINT32_C(0x00FF00FF)) << 8); #endif h = ((h >> 4) & UINT32_C(0x0F0F0F0F)) | ((h & UINT32_C(0x0F0F0F0F)) << 4); l = ((l >> 4) & UINT32_C(0x0F0F0F0F)) | ((l & UINT32_C(0x0F0F0F0F)) << 4); h = ((h >> 2) & UINT32_C(0x33333333)) | ((h & UINT32_C(0x33333333)) << 2); l = ((l >> 2) & UINT32_C(0x33333333)) | ((l & UINT32_C(0x33333333)) << 2); h = ((h >> 1) & UINT32_C(0x55555555)) | ((h & UINT32_C(0x55555555)) << 1); l = ((l >> 1) & UINT32_C(0x55555555)) | ((l & UINT32_C(0x55555555)) << 1); return ((uint64_t)l << 32) | h; /* Swap halves */ #endif } /* Apply a permutation to scramble vertex numbers; a randomly generated * permutation is not used because applying it at scale is too expensive. */ static inline int64_t scramble(int64_t v0, int lgN, uint64_t val0, uint64_t val1) { uint64_t v = (uint64_t)v0; v += val0 + val1; v *= (val0 | UINT64_C(0x4519840211493211)); v = (bitreverse(v) >> (64 - lgN)); assert ((v >> lgN) == 0); v *= (val1 | UINT64_C(0x3050852102C843A5)); v = (bitreverse(v) >> (64 - lgN)); assert ((v >> lgN) == 0); return (int64_t)v; } /* Make a single graph edge using a pre-set MRG state. */ static void make_one_edge(int64_t nverts, int level, int lgN, mrg_state* st, packed_edge* result, uint64_t val0, uint64_t val1) { int64_t base_src = 0, base_tgt = 0; while (nverts > 1) { int square = generate_4way_bernoulli(st, level, lgN); int src_offset = square / 2; int tgt_offset = square % 2; assert (base_src <= base_tgt); if (base_src == base_tgt) { /* Clip-and-flip for undirected graph */ if (src_offset > tgt_offset) { int temp = src_offset; src_offset = tgt_offset; tgt_offset = temp; } } nverts /= 2; ++level; base_src += nverts * src_offset; base_tgt += nverts * tgt_offset; } write_edge(result, scramble(base_src, lgN, val0, val1), scramble(base_tgt, lgN, val0, val1)); } /* Generate a range of edges (from start_edge to end_edge of the total graph), * writing into elements [0, end_edge - start_edge) of the edges array. This * code is parallel on OpenMP and XMT; it must be used with * separately-implemented SPMD parallelism for MPI. */ void generate_kronecker_range( const uint_fast32_t seed[5] /* All values in [0, 2^31 - 1), not all zero */, int logN /* In base 2 */, int64_t start_edge, int64_t end_edge, packed_edge* edges) { mrg_state state; int64_t nverts = (int64_t)1 << logN; int64_t ei; mrg_seed(&state, seed); uint64_t val0, val1; /* Values for scrambling */ { mrg_state new_state = state; mrg_skip(&new_state, 50, 7, 0); val0 = mrg_get_uint_orig(&new_state); val0 *= UINT64_C(0xFFFFFFFF); val0 += mrg_get_uint_orig(&new_state); val1 = mrg_get_uint_orig(&new_state); val1 *= UINT64_C(0xFFFFFFFF); val1 += mrg_get_uint_orig(&new_state); } #ifdef _OPENMP #pragma omp parallel for #endif #ifdef __MTA__ #pragma mta assert parallel #pragma mta block schedule #endif for (ei = start_edge; ei < end_edge; ++ei) { mrg_state new_state = state; mrg_skip(&new_state, 0, (uint64_t)ei, 0); make_one_edge(nverts, 0, logN, &new_state, edges + (ei - start_edge), val0, val1); printf("%d;%" PRIu64 ";%" PRIu64 "\n", 0, (edges+(ei-start_edge))->v0, (edges+(ei-start_edge))->v1); } }
section.c
#include<stdio.h> #include<omp.h> int main() { omp_set_num_threads(4); #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp sections { // 3 threads will execute although we have 4 threads. #pragma omp section { printf("%d | Executing 1\n", tid); } #pragma omp section { printf("%d | Executing 2\n", tid); } #pragma omp section { printf("%d | Executing 3\n", tid); } } } }
ast-dump-openmp-target-teams.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test() { #pragma omp target teams ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-target-teams.c:3:1, line:6:1> line:3:6 test 'void ()' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:13, line:6:1> // CHECK-NEXT: `-OMPTargetTeamsDirective {{.*}} <line:4:1, col:25> // CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3> // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: |-CapturedStmt {{.*}} <col:3> // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-CapturedStmt {{.*}} <col:3> // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-NullStmt {{.*}} <col:3> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | `-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition // CHECK-NEXT: | | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-NullStmt {{.*}} <line:5:3> // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict' // CHECK-NEXT: |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .global_tid. 'const int' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict' // CHECK-NEXT: |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition // CHECK-NEXT: | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: |-CapturedStmt {{.*}} <line:5:3> // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-NullStmt {{.*}} <col:3> // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict' // CHECK-NEXT: |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition // CHECK-NEXT: | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: |-NullStmt {{.*}} <line:5:3> // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: `-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-teams.c:4:1) *const restrict'
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 32; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[(t)%2][i ][j ][k ] + coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
pzgetrf.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" #include "core_blas.h" #define A(m, n) (plasma_complex64_t*)plasma_tile_addr(A, m, n) /******************************************************************************/ void plasma_pzgetrf(plasma_desc_t A, int *ipiv, plasma_sequence_t *sequence, plasma_request_t *request) { // Return if failed sequence. if (sequence->status != PlasmaSuccess) return; // Read parameters from the context. plasma_context_t *plasma = plasma_context_self(); // Set tiling parameters. int ib = plasma->ib; for (int k = 0; k < imin(A.mt, A.nt); k++) { plasma_complex64_t *a00, *a20; a00 = A(k, k); a20 = A(A.mt-1, k); int ma00k = (A.mt-k-1)*A.mb; int na00k = plasma_tile_nmain(A, k); int lda20 = plasma_tile_mmain(A, A.mt-1); int nvak = plasma_tile_nview(A, k); int mvak = plasma_tile_mview(A, k); int ldak = plasma_tile_mmain(A, k); int num_panel_threads = imin(plasma->max_panel_threads, imin(A.mt, A.nt)-k); // panel #pragma omp task depend(inout:a00[0:ma00k*na00k]) \ depend(inout:a20[0:lda20*nvak]) \ depend(out:ipiv[k*A.mb:mvak]) \ priority(1) { volatile int *max_idx = (int*)malloc(num_panel_threads*sizeof(int)); if (max_idx == NULL) plasma_request_fail(sequence, request, PlasmaErrorOutOfMemory); volatile plasma_complex64_t *max_val = (plasma_complex64_t*)malloc(num_panel_threads*sizeof( plasma_complex64_t)); if (max_val == NULL) plasma_request_fail(sequence, request, PlasmaErrorOutOfMemory); volatile int info = 0; plasma_barrier_t barrier; plasma_barrier_init(&barrier); if (sequence->status == PlasmaSuccess) { for (int rank = 0; rank < num_panel_threads; rank++) { #pragma omp task shared(barrier) priority(1) { plasma_desc_t view = plasma_desc_view(A, k*A.mb, k*A.nb, A.m-k*A.mb, nvak); core_zgetrf(view, &ipiv[k*A.mb], ib, rank, num_panel_threads, max_idx, max_val, &info, &barrier); if (info != 0) plasma_request_fail(sequence, request, k*A.mb+info); } } } #pragma omp taskwait free((void*)max_idx); free((void*)max_val); for (int i = k*A.mb+1; i <= imin(A.m, k*A.mb+nvak); i++) ipiv[i-1] += k*A.mb; } // update for (int n = k+1; n < A.nt; n++) { plasma_complex64_t *a01, *a11, *a21; a01 = A(k, n); a11 = A(k+1, n); a21 = A(A.mt-1, n); int ma11k = (A.mt-k-2)*A.mb; int na11n = plasma_tile_nmain(A, n); int lda21 = plasma_tile_mmain(A, A.mt-1); int nvan = plasma_tile_nview(A, n); #pragma omp task depend(in:a00[0:ma00k*na00k]) \ depend(in:a20[0:lda20*nvak]) \ depend(in:ipiv[k*A.mb:mvak]) \ depend(inout:a01[0:ldak*nvan]) \ depend(inout:a11[0:ma11k*na11n]) \ depend(inout:a21[0:lda21*nvan]) \ priority(n == k+1) { if (sequence->status == PlasmaSuccess) { // geswp int k1 = k*A.mb+1; int k2 = imin(k*A.mb+A.mb, A.m); plasma_desc_t view = plasma_desc_view(A, 0, n*A.nb, A.m, nvan); core_zgeswp(PlasmaRowwise, view, k1, k2, ipiv, 1); // trsm core_ztrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, mvak, nvan, 1.0, A(k, k), ldak, A(k, n), ldak); // gemm for (int m = k+1; m < A.mt; m++) { int mvam = plasma_tile_mview(A, m); int ldam = plasma_tile_mmain(A, m); #pragma omp task priority(n == k+1) { core_zgemm( PlasmaNoTrans, PlasmaNoTrans, mvam, nvan, A.nb, -1.0, A(m, k), ldam, A(k, n), ldak, 1.0, A(m, n), ldam); } } } #pragma omp taskwait } } } // pivoting to the left for (int k = 1; k < imin(A.mt, A.nt); k++) { plasma_complex64_t *akk; akk = A(k-1, k-1); int makk = (A.mt-k-1)*A.mb; int nakk = plasma_tile_nmain(A, k); #pragma omp task depend(in:ipiv[(imin(A.mt, A.nt)-1)*A.mb]) \ depend(inout:akk[0:makk*nakk]) { if (sequence->status == PlasmaSuccess) { plasma_desc_t view = plasma_desc_view(A, 0, (k-1)*A.nb, A.m, A.nb); int k1 = k*A.mb+1; int k2 = imin(A.m, A.n); core_zgeswp(PlasmaRowwise, view, k1, k2, ipiv, 1); } } } }
GeometryFunctions.h
/* * File: GeometryFunctions.h * Author: msantasusana, Chun Feng * * Created on 21 de mayo de 2012, 19:40 */ #ifndef _GEOMETRYFUNCTIONS_H #define _GEOMETRYFUNCTIONS_H #include <cmath> #include "utilities/openmp_utils.h" #include "utilities/quaternion.h" #include "includes/model_part.h" #include "DEM_application_variables.h" namespace Kratos { namespace GeometryFunctions { typedef Geometry<Node < 3 > > GeometryType; static inline void RotateAVectorAGivenAngleAroundAUnitaryVector(const array_1d<double, 3>& old_vec, const array_1d<double, 3>& axis, const double ang, array_1d<double, 3>& new_vec) { double cang = std::cos(ang); double sang = std::sin(ang); new_vec[0] = axis[0] * (axis[0] * old_vec[0] + axis[1] * old_vec[1] + axis[2] * old_vec[2]) * (1 - cang) + old_vec[0] * cang + (-axis[2] * old_vec[1] + axis[1] * old_vec[2]) * sang; new_vec[1] = axis[1] * (axis[0] * old_vec[0] + axis[1] * old_vec[1] + axis[2] * old_vec[2]) * (1 - cang) + old_vec[1] * cang + ( axis[2] * old_vec[0] - axis[0] * old_vec[2]) * sang; new_vec[2] = axis[2] * (axis[0] * old_vec[0] + axis[1] * old_vec[1] + axis[2] * old_vec[2]) * (1 - cang) + old_vec[2] * cang + (-axis[1] * old_vec[0] + axis[0] * old_vec[1]) * sang; } static inline void TranslateGridOfNodes(const double time, const double velocity_start_time, const double velocity_stop_time, array_1d<double, 3>& center_position, const array_1d<double, 3>& initial_center, array_1d<double, 3>& previous_displ, array_1d<double, 3>& linear_velocity_changed, const double linear_period, const double dt, const array_1d<double, 3>& linear_velocity) { if (time < velocity_start_time || time > velocity_stop_time) { center_position[0] = initial_center[0] + previous_displ[0]; center_position[1] = initial_center[1] + previous_displ[1]; center_position[2] = initial_center[2] + previous_displ[2]; linear_velocity_changed = ZeroVector(3); } else { if (linear_period > 0.0) { double linear_omega = 2.0 * Globals::Pi / linear_period; double inv_linear_omega = 1.0 / linear_omega; noalias(center_position) = initial_center + linear_velocity * std::sin(linear_omega * (time - velocity_start_time)) * inv_linear_omega; noalias(linear_velocity_changed) = linear_velocity * std::cos(linear_omega * (time - velocity_start_time)); noalias(previous_displ) = center_position - initial_center; } else { center_position[0] = initial_center[0] + previous_displ[0] + dt * linear_velocity[0]; center_position[1] = initial_center[1] + previous_displ[1] + dt * linear_velocity[1]; center_position[2] = initial_center[2] + previous_displ[2] + dt * linear_velocity[2]; previous_displ[0] += dt * linear_velocity[0]; previous_displ[1] += dt * linear_velocity[1]; previous_displ[2] += dt * linear_velocity[2]; linear_velocity_changed = linear_velocity; } } } static inline int sign(const double a) { return (0.0 < a) - (a < 0.0); /*int output; if (a < 0.0) output = -1; else if (a > 0.0) output = 1; else output = 0; return output;*/ } static inline double min(double a, double b) { double output; if (a<=b) output = a; else output = b; return output; } static inline double max(double a, double b) { double output; if (a>=b) output = a; else output = b; return output; } static inline void normalize(double Vector[3]) { double distance = DEM_INNER_PRODUCT_3(Vector, Vector); double inv_distance = (distance > 0.0) ? 1.0 / sqrt(distance) : 0.00; Vector[0] = Vector[0] * inv_distance; Vector[1] = Vector[1] * inv_distance; Vector[2] = Vector[2] * inv_distance; } static inline void normalize(array_1d<double,3>& Vector, double& distance) { distance = DEM_MODULUS_3(Vector); double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.00; Vector[0] = Vector[0] * inv_distance; Vector[1] = Vector[1] * inv_distance; Vector[2] = Vector[2] * inv_distance; } static inline void normalize(double Vector[3], double& distance) { distance = DEM_MODULUS_3(Vector); double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.00; Vector[0] = Vector[0] * inv_distance; Vector[1] = Vector[1] * inv_distance; Vector[2] = Vector[2] * inv_distance; } static inline void normalize(array_1d<double,3>& Vector) { double distance = DEM_MODULUS_3(Vector); double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.00; Vector[0] = Vector[0] * inv_distance; Vector[1] = Vector[1] * inv_distance; Vector[2] = Vector[2] * inv_distance; } static inline void module(const array_1d<double,3>& Vector, double& distance) { distance = DEM_MODULUS_3(Vector); } static inline double module(const double Vector[3]) { return DEM_MODULUS_3(Vector); } static inline void module(const double Vector[3], double& distance) { distance = DEM_MODULUS_3(Vector); } static inline double module(const array_1d<double,3>& Vector) { double distance = DEM_MODULUS_3(Vector); return distance; } static inline void VectorGlobal2Local(const double LocalCoordSystem[3][3], const double GlobalVector[3], double LocalVector[3]) { for (int i=0; i<3; i++) { LocalVector[i] = 0.0; for (int j=0; j<3; j++) { LocalVector[i]+=LocalCoordSystem[i][j]*GlobalVector[j]; } } } static inline void VectorGlobal2Local(const double LocalCoordSystem[3][3], const array_1d<double, 3>& GlobalVector, array_1d<double, 3>& LocalVector) { for (int i=0; i<3; i++) { LocalVector[i] = 0.0; for (int j=0; j<3; j++) { LocalVector[i]+=LocalCoordSystem[i][j]*GlobalVector[j]; } } } static inline void VectorGlobal2Local(const double LocalCoordSystem[3][3], const array_1d<double, 3>& GlobalVector, double LocalVector[3]) { for (int i=0; i<3; i++) { LocalVector[i] = 0.0; for (int j=0; j<3; j++) { LocalVector[i]+=LocalCoordSystem[i][j]*GlobalVector[j]; } } } static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const double LocalVector[3], double GlobalVector[3]) { for (int i=0; i<3; i++) { GlobalVector[i] = 0.0; for (int j=0; j<3; j++) { GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j]; } } } static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const array_1d<double, 3>& LocalVector, array_1d<double, 3>& GlobalVector) { for (int i=0; i<3; i++) { GlobalVector[i] = 0.0; for (int j=0; j<3; j++) { GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j]; } } } static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const array_1d<double, 3>& LocalVector, double GlobalVector[3]) { for (int i=0; i<3; i++) { GlobalVector[i] = 0.0; for (int j=0; j<3; j++) { GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j]; } } } static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const double LocalVector[3], array_1d<double, 3>& GlobalVector) { for (int i=0; i<3; i++) { GlobalVector[i] = 0.0; for (int j=0; j<3; j++) { GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j]; } } } static inline void ProductMatrices3X3(const double Matrix1[3][3], const double Matrix2[3][3], double Matrix3[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Matrix3[i][j] = 0.0; for (int k = 0; k < 3; k++) { Matrix3[i][j] += Matrix1[i][k] * Matrix2[k][j]; } } } } static inline void ProductMatrix3X3Vector3X1(const double Matrix[3][3], const array_1d<double,3>& Vector1, array_1d<double,3>& Vector2) { for (int i=0; i<3; i++) { Vector2[i] = 0.0; for (int j=0; j<3; j++) { Vector2[i]+=Matrix[j][i]*Vector1[j]; } } } static inline void TensorGlobal2Local(const double LocalCoordSystem[3][3], const double GlobalTensor[3][3], double LocalTensor[3][3]) { // We will compute LocalTensor = LocalCoordSystem * GlobalTensor * transposed(LocalCoordSystem) // starting on the left, so we will first compute the product TemporalResult = LocalCoordSystem * GlobalTensor // and afterwards TemporalResult * transposed(LocalCoordSystem), which will give the value of the tensor LocalTensor double TransposedLocalCoordSystem[3][3]; double TemporalResult[3][3]; TransposedLocalCoordSystem[0][0] = LocalCoordSystem[0][0]; TransposedLocalCoordSystem[0][1] = LocalCoordSystem[1][0]; TransposedLocalCoordSystem[0][2] = LocalCoordSystem[2][0]; TransposedLocalCoordSystem[1][0] = LocalCoordSystem[0][1]; TransposedLocalCoordSystem[1][1] = LocalCoordSystem[1][1]; TransposedLocalCoordSystem[1][2] = LocalCoordSystem[2][1]; TransposedLocalCoordSystem[2][0] = LocalCoordSystem[0][2]; TransposedLocalCoordSystem[2][1] = LocalCoordSystem[1][2]; TransposedLocalCoordSystem[2][2] = LocalCoordSystem[2][2]; ProductMatrices3X3(LocalCoordSystem, GlobalTensor, TemporalResult); ProductMatrices3X3(TemporalResult, TransposedLocalCoordSystem, LocalTensor); } static inline void TensorLocal2Global(const double LocalCoordSystem[3][3], const double LocalTensor[3][3], double GlobalTensor[3][3]) { // We will compute GlobalTensor = transposed(LocalCoordSystem) * LocalTensor * LocalCoordSystem // starting on the left, so we will first compute the product TemporalResult = transposed(LocalCoordSystem) * LocalTensor // and afterwards TemporalResult * LocalCoordSystem, which will give the value of the tensor LocalTensor double TransposedLocalCoordSystem[3][3]; double TemporalResult[3][3]; TransposedLocalCoordSystem[0][0] = LocalCoordSystem[0][0]; TransposedLocalCoordSystem[0][1] = LocalCoordSystem[1][0]; TransposedLocalCoordSystem[0][2] = LocalCoordSystem[2][0]; TransposedLocalCoordSystem[1][0] = LocalCoordSystem[0][1]; TransposedLocalCoordSystem[1][1] = LocalCoordSystem[1][1]; TransposedLocalCoordSystem[1][2] = LocalCoordSystem[2][1]; TransposedLocalCoordSystem[2][0] = LocalCoordSystem[0][2]; TransposedLocalCoordSystem[2][1] = LocalCoordSystem[1][2]; TransposedLocalCoordSystem[2][2] = LocalCoordSystem[2][2]; ProductMatrices3X3(TransposedLocalCoordSystem, LocalTensor, TemporalResult); ProductMatrices3X3(TemporalResult, LocalCoordSystem, GlobalTensor); } static inline void RotaMatrixTensorLocal2Global(const double R[3][3], const double LocalTensor[3][3], double GlobalTensor[3][3]) { double RT[3][3]; double Temp[3][3]; RT[0][0] = R[0][0]; RT[0][1] = R[1][0]; RT[0][2] = R[2][0]; RT[1][0] = R[0][1]; RT[1][1] = R[1][1]; RT[1][2] = R[2][1]; RT[2][0] = R[0][2]; RT[2][1] = R[1][2]; RT[2][2] = R[2][2]; ProductMatrices3X3(R, LocalTensor, Temp); ProductMatrices3X3(Temp, RT, GlobalTensor); } static inline void ConstructLocalTensor(const double moment_of_inertia, double LocalTensor[3][3]) { LocalTensor[0][0] = moment_of_inertia; LocalTensor[0][1] = 0.0; LocalTensor[0][2] = 0.0; LocalTensor[1][0] = 0.0; LocalTensor[1][1] = moment_of_inertia; LocalTensor[1][2] = 0.0; LocalTensor[2][0] = 0.0; LocalTensor[2][1] = 0.0; LocalTensor[2][2] = moment_of_inertia; } static inline void ConstructInvLocalTensor(const double moment_of_inertia, double LocalTensorInv[3][3]) { double moment_of_inertia_inv = 1/moment_of_inertia; LocalTensorInv[0][0] = moment_of_inertia_inv; LocalTensorInv[0][1] = 0.0; LocalTensorInv[0][2] = 0.0; LocalTensorInv[1][0] = 0.0; LocalTensorInv[1][1] = moment_of_inertia_inv; LocalTensorInv[1][2] = 0.0; LocalTensorInv[2][0] = 0.0; LocalTensorInv[2][1] = 0.0; LocalTensorInv[2][2] = moment_of_inertia_inv; } static inline void ConstructLocalTensor(const array_1d<double, 3 >& moments_of_inertia, double LocalTensor[3][3]) { LocalTensor[0][0] = moments_of_inertia[0]; LocalTensor[0][1] = 0.0; LocalTensor[0][2] = 0.0; LocalTensor[1][0] = 0.0; LocalTensor[1][1] = moments_of_inertia[1]; LocalTensor[1][2] = 0.0; LocalTensor[2][0] = 0.0; LocalTensor[2][1] = 0.0; LocalTensor[2][2] = moments_of_inertia[2]; } static inline void ConstructInvLocalTensor(const array_1d<double, 3 >& moments_of_inertia, double LocalTensorInv[3][3]) { LocalTensorInv[0][0] = 1/moments_of_inertia[0]; LocalTensorInv[0][1] = 0.0; LocalTensorInv[0][2] = 0.0; LocalTensorInv[1][0] = 0.0; LocalTensorInv[1][1] = 1/moments_of_inertia[1]; LocalTensorInv[1][2] = 0.0; LocalTensorInv[2][0] = 0.0; LocalTensorInv[2][1] = 0.0; LocalTensorInv[2][2] = 1/moments_of_inertia[2]; } static inline double DotProduct(double Vector1[3], double Vector2[3]) { return Vector1[0] * Vector2[0] + Vector1[1] * Vector2[1] + Vector1[2] * Vector2[2]; } static inline double DotProduct(const array_1d<double,3>& Vector1, const array_1d<double,3>& Vector2) { return Vector1[0] * Vector2[0] + Vector1[1] * Vector2[1] + Vector1[2] * Vector2[2]; } static inline void CrossProduct(const double u[3], const double v[3], double ReturnVector[3]) { ReturnVector[0] = u[1]*v[2] - u[2]*v[1]; ReturnVector[1] = v[0]*u[2] - u[0]*v[2]; ReturnVector[2] = u[0]*v[1] - u[1]*v[0]; } static inline void CrossProduct(const array_1d<double,3>& u, const array_1d<double,3>& v, array_1d<double,3>& ReturnVector) { ReturnVector[0] = u[1]*v[2] - u[2]*v[1]; ReturnVector[1] = v[0]*u[2] - u[0]*v[2]; ReturnVector[2] = u[0]*v[1] - u[1]*v[0]; } static inline void CrossProduct(const double u[3], const array_1d<double,3>& v, double ReturnVector[3]) { ReturnVector[0] = u[1]*v[2] - u[2]*v[1]; ReturnVector[1] = v[0]*u[2] - u[0]*v[2]; ReturnVector[2] = u[0]*v[1] - u[1]*v[0]; } static inline void CrossProduct(const array_1d<double,3>& u, const double v[3], double ReturnVector[3]) { ReturnVector[0] = u[1]*v[2] - u[2]*v[1]; ReturnVector[1] = v[0]*u[2] - u[0]*v[2]; ReturnVector[2] = u[0]*v[1] - u[1]*v[0]; } static inline void CrossProduct(const array_1d<double,3>& u, const double v[3], array_1d<double,3>& ReturnVector) { ReturnVector[0] = u[1]*v[2] - u[2]*v[1]; ReturnVector[1] = v[0]*u[2] - u[0]*v[2]; ReturnVector[2] = u[0]*v[1] - u[1]*v[0]; } static inline void CrossProduct(const array_1d<double,3>& u, const array_1d<double,3>& v, double ReturnVector[3]) { ReturnVector[0] = u[1]*v[2] - u[2]*v[1]; ReturnVector[1] = v[0]*u[2] - u[0]*v[2]; ReturnVector[2] = u[0]*v[1] - u[1]*v[0]; } static inline void RotateRightHandedBasisAroundAxis(const array_1d<double, 3>& e1, const array_1d<double, 3>& e2, const array_1d<double, 3>& axis, const double ang, array_1d<double, 3>& new_axes1, array_1d<double, 3>& new_axes2, array_1d<double, 3>& new_axes3) { RotateAVectorAGivenAngleAroundAUnitaryVector(e1, axis, ang, new_axes1); RotateAVectorAGivenAngleAroundAUnitaryVector(e2, axis, ang, new_axes2); CrossProduct(new_axes1, new_axes2, new_axes3); } static inline void RotateGridOfNodes(const double time, const double angular_velocity_start_time, const double angular_velocity_stop_time, array_1d<double, 3>& angular_velocity_changed, const double angular_period, const double mod_angular_velocity, const array_1d<double, 3>& angular_velocity, array_1d<double, 3>& new_axes1, array_1d<double, 3>& new_axes2, array_1d<double, 3>& new_axes3) { array_1d<double, 3> angle; noalias(angle) = ZeroVector(3); double sign_angle = 1.0; array_1d<double, 3> final_angle = ZeroVector(3); if (time < angular_velocity_start_time) angular_velocity_changed = ZeroVector(3); else if (((time - angular_velocity_start_time) > 0.0) && ((time - angular_velocity_stop_time) < 0.0)) { if (angular_period > 0.0) { double angular_omega = 2.0 * Globals::Pi / angular_period; double inv_angular_omega = 1.0 / angular_omega; noalias(angle) = angular_velocity * std::sin(angular_omega * (time - angular_velocity_start_time)) * inv_angular_omega; sign_angle = std::sin(angular_omega * (time - angular_velocity_start_time)) / fabs(sin(angular_omega * (time - angular_velocity_start_time))); noalias(angular_velocity_changed) = angular_velocity * std::cos(angular_omega * (time - angular_velocity_start_time)); noalias(final_angle) = angle; } else { noalias(angle) = angular_velocity * (time - angular_velocity_start_time); noalias(angular_velocity_changed) = angular_velocity; } } else { //if ((time - angular_velocity_stop_time) > 0.0) { noalias(angular_velocity_changed) = ZeroVector(3); if (angular_period > 0.0) { double angular_omega = 2.0 * Globals::Pi / angular_period; double inv_angular_omega = 1.0 / angular_omega; noalias(angle) = angular_velocity * std::sin(angular_omega * (angular_velocity_stop_time - angular_velocity_start_time)) * inv_angular_omega; } else { noalias(angle) = angular_velocity * (angular_velocity_stop_time - angular_velocity_start_time); } } //mod_angular_velocity = MathUtils<double>::Norm3(angular_velocity); new_axes1[0] = 1.0; new_axes1[1] = 0.0; new_axes1[2] = 0.0; new_axes2[0] = 0.0; new_axes2[1] = 1.0; new_axes2[2] = 0.0; new_axes3[0] = 0.0; new_axes3[1] = 0.0; new_axes3[2] = 1.0; if (mod_angular_velocity > 0.0) { double ang = sign_angle * MathUtils<double>::Norm3(angle); array_1d<double, 3> rotation_axis; noalias(rotation_axis) = angular_velocity / mod_angular_velocity; array_1d<double, 3> e1; e1[0] = 1.0; e1[1] = 0.0; e1[2] = 0.0; array_1d<double, 3> e2; e2[0] = 0.0; e2[1] = 1.0; e2[2] = 0.0; RotateRightHandedBasisAroundAxis(e1, e2, rotation_axis, ang, new_axes1, new_axes2, new_axes3); } } static inline void UpdateKinematicVariablesOfAGridOfNodes(double mod_angular_velocity, const array_1d<double, 3>& linear_velocity, const array_1d<double, 3>& initial_center, array_1d<double, 3>& new_axes1, array_1d<double, 3>& new_axes2, array_1d<double, 3>& new_axes3, array_1d<double, 3>& angular_velocity_changed, array_1d<double, 3>& linear_velocity_changed, array_1d<double, 3>& center_position, const bool fixed_mesh, const double dt, ModelPart::NodesContainerType& pNodes) { if (mod_angular_velocity > std::numeric_limits<double>::epsilon() || MathUtils<double>::Norm3(linear_velocity) > std::numeric_limits<double>::epsilon()) { #pragma omp parallel for for (int k = 0; k < (int)pNodes.size(); k++) { array_1d<double, 3> local_coordinates = ZeroVector(3); array_1d<double, 3> relative_position = ZeroVector(3); ModelPart::NodeIterator node = pNodes.begin() + k; noalias(local_coordinates) = node->GetInitialPosition().Coordinates() - initial_center; noalias(relative_position) = new_axes1 * local_coordinates[0] + new_axes2 * local_coordinates[1] + new_axes3 * local_coordinates[2]; array_1d<double, 3> old_coordinates; noalias(old_coordinates) = node->Coordinates(); array_1d<double, 3> velocity_due_to_rotation; array_1d<double, 3>& velocity = node->FastGetSolutionStepValue(VELOCITY); CrossProduct(angular_velocity_changed, relative_position, velocity_due_to_rotation); noalias(velocity) = linear_velocity_changed + velocity_due_to_rotation; if (!fixed_mesh) { // NEW POSITION noalias(node->Coordinates()) = center_position + relative_position; // DISPLACEMENT noalias(node->FastGetSolutionStepValue(DISPLACEMENT)) = node->Coordinates() - node->GetInitialPosition().Coordinates(); noalias(node->FastGetSolutionStepValue(DELTA_DISPLACEMENT)) = node->Coordinates() - old_coordinates; } else { (node->FastGetSolutionStepValue(DISPLACEMENT)).clear(); //Set values to zero noalias(node->FastGetSolutionStepValue(DELTA_DISPLACEMENT)) = velocity * dt; //But still there must be some delta_displacement (or motion won't be detected by the spheres!) } } } } //NOTE:: Modified by M. Santasusana Feb 2013 - simplification (the one proposed by F. Chun was for a more generalized case) static inline void ComputeContactLocalCoordSystem(array_1d<double, 3> NormalDirection, const double& distance, double LocalCoordSystem[3][3]) //inline: modifies the LocalCoordSystem as it were a reference { double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.0; NormalDirection[0] *= inv_distance; NormalDirection[1] *= inv_distance; NormalDirection[2] *= inv_distance; double N_fast[3]; N_fast[0] = NormalDirection[0]; N_fast[1] = NormalDirection[1]; N_fast[2] = NormalDirection[2]; if (fabs(N_fast[0]) >= 0.577) //0.57735026919 { LocalCoordSystem[0][0] = - N_fast[1]; LocalCoordSystem[0][1] = N_fast[0]; LocalCoordSystem[0][2] = 0.0; } else if (fabs(N_fast[1]) >= 0.577) { LocalCoordSystem[0][0] = 0.0; LocalCoordSystem[0][1] = - N_fast[2]; LocalCoordSystem[0][2] = N_fast[1]; } else { LocalCoordSystem[0][0] = N_fast[2]; LocalCoordSystem[0][1] = 0.0; LocalCoordSystem[0][2] = - N_fast[0]; } //normalize(Vector0); double distance0 = DEM_MODULUS_3(LocalCoordSystem[0]); double inv_distance0 = (distance0 != 0.0) ? 1.0 / distance0 : 0.0; LocalCoordSystem[0][0] = LocalCoordSystem[0][0] * inv_distance0; LocalCoordSystem[0][1] = LocalCoordSystem[0][1] * inv_distance0; LocalCoordSystem[0][2] = LocalCoordSystem[0][2] * inv_distance0; //CrossProduct(NormalDirection, Vector0, Vector1); LocalCoordSystem[1][0] = N_fast[1] * LocalCoordSystem[0][2] - N_fast[2] * LocalCoordSystem[0][1]; LocalCoordSystem[1][1] = N_fast[2] * LocalCoordSystem[0][0] - N_fast[0] * LocalCoordSystem[0][2]; LocalCoordSystem[1][2] = N_fast[0] * LocalCoordSystem[0][1] - N_fast[1] * LocalCoordSystem[0][0]; //normalize(Vector1); LocalCoordSystem[2][0] = N_fast[0]; LocalCoordSystem[2][1] = N_fast[1]; LocalCoordSystem[2][2] = N_fast[2]; } static inline double DistanceOfTwoPoint(const double coord1[3], const double coord2[3]) { double dx = coord1[0] - coord2[0]; double dy = coord1[1] - coord2[1]; double dz = coord1[2] - coord2[2]; return sqrt(dx * dx + dy * dy + dz * dz); } static inline double DistanceOfTwoPoint(const array_1d<double,3>& coord1, const double coord2[3]) { double dx = coord1[0] - coord2[0]; double dy = coord1[1] - coord2[1]; double dz = coord1[2] - coord2[2]; return sqrt(dx * dx + dy * dy + dz * dz); } static inline double DistanceOfTwoPointSquared(const array_1d<double,3>& coord1, const array_1d<double,3>& coord2) { double dx = coord1[0] - coord2[0]; double dy = coord1[1] - coord2[1]; double dz = coord1[2] - coord2[2]; return (dx * dx + dy * dy + dz * dz); } static inline double DistanceOfTwoPointSquared(double coord1[3], double coord2[3]) { double dx = coord1[0] - coord2[0]; double dy = coord1[1] - coord2[1]; double dz = coord1[2] - coord2[2]; return (dx * dx + dy * dy + dz * dz); } static inline double DistancePointToPlane(const array_1d<double,3>& CoordInPlane, double PlaneUnitNormalVector[3], double TestCoord[3]) { double Vector1[3] = {0.0}; for (unsigned int i = 0; i<3; i++) { Vector1[i] = TestCoord[i]- CoordInPlane[i]; } double dist = fabs (DotProduct(Vector1, PlaneUnitNormalVector)); return dist; } static inline void CoordProjectionOnPlane(double CoordOut[3], double CoordIn[3], double LocalCoordSystem[3][3], double IntersectionCoord[3]) { double out_coord_local[3] = {0.0}; double in_coord_local[3] = {0.0}; VectorGlobal2Local(LocalCoordSystem, CoordOut, out_coord_local); VectorGlobal2Local(LocalCoordSystem, CoordIn, in_coord_local); double vector1[3] = {0.0}; vector1[0] = out_coord_local[0]; vector1[1] = out_coord_local[1]; vector1[2] = in_coord_local [2]; VectorLocal2Global(LocalCoordSystem, vector1, IntersectionCoord); } static inline void CoordProjectionOnPlaneNew(double CoordOut[3], const array_1d<double, 3>& CoordIn, double LocalCoordSystem[3][3], double IntersectionCoord[3]) { double out_coord_local[3] = {0.0}; double in_coord_local[3] = {0.0}; VectorGlobal2Local(LocalCoordSystem, CoordOut, out_coord_local); VectorGlobal2Local(LocalCoordSystem, CoordIn, in_coord_local); double vector1[3] = {0.0}; vector1[0] = out_coord_local[0]; vector1[1] = out_coord_local[1]; vector1[2] = in_coord_local [2]; VectorLocal2Global(LocalCoordSystem, vector1, IntersectionCoord); } static inline void Compute3DimElementFaceLocalSystem(const array_1d <double,3>& FaceCoord1, const array_1d <double,3>& FaceCoord2, const array_1d <double,3>& FaceCoord3, double ParticleCoord[3], double LocalCoordSystem[3][3], double& normal_flag) { //NOTE: this function is designed in a way that the normal always points the side where the center of particle is found. Therefore should only be used in this way if the indentation is less than the radius value. //the function returns a flag with the same value as the dot product of the normal of the triangle and the normal pointing to the particle. double Vector1[3] = {0.0}; double Vector2[3] = {0.0}; double Vector3[3] = {0.0}; double Normal[3] = {0.0}; Vector1[0] = FaceCoord2[0] - FaceCoord1[0]; Vector1[1] = FaceCoord2[1] - FaceCoord1[1]; Vector1[2] = FaceCoord2[2] - FaceCoord1[2]; Vector2[0] = FaceCoord3[0] - FaceCoord2[0]; Vector2[1] = FaceCoord3[1] - FaceCoord2[1]; Vector2[2] = FaceCoord3[2] - FaceCoord2[2]; normalize(Vector1); CrossProduct(Vector1, Vector2, Normal); normalize(Normal); CrossProduct(Normal, Vector1, Vector2); normalize(Vector2); Vector3[0] = ParticleCoord[0] - FaceCoord1[0]; Vector3[1] = ParticleCoord[1] - FaceCoord1[1]; Vector3[2] = ParticleCoord[2] - FaceCoord1[2]; normalize(Vector3); if (DotProduct(Vector3, Normal) > 0.0) { for (int ia = 0; ia < 3; ia++) { normal_flag = 1.0; LocalCoordSystem[0][ia] = Vector1[ia]; LocalCoordSystem[1][ia] = Vector2[ia]; LocalCoordSystem[2][ia] = Normal [ia]; } } else { for (int ia = 0; ia < 3; ia++) { normal_flag = -1.0; LocalCoordSystem[0][ia] = -Vector1[ia]; LocalCoordSystem[1][ia] = -Vector2[ia]; LocalCoordSystem[2][ia] = -Normal [ia]; } } } //MSIMSI this one is being used only for distributed... adapt it static inline void Compute3DimElementFaceLocalSystem(double FaceCoord1[3], double FaceCoord2[3], double FaceCoord3[3], double ParticleCoord[3], double LocalCoordSystem[3][3], double& normal_flag){ //NOTE: this function is designed in a way that the normal always points the side where the center of particle is found. Therefore should only be used in this way if the indentation is less than the radius value. //the function returns a flag with the same value as the dot product of the normal of the triangle and the normal pointing to the particle. double Vector1[3] = {0.0}; double Vector2[3] = {0.0}; double Vector3[3] = {0.0}; double Normal[3] = {0.0}; Vector1[0] = FaceCoord2[0] - FaceCoord1[0]; Vector1[1] = FaceCoord2[1] - FaceCoord1[1]; Vector1[2] = FaceCoord2[2] - FaceCoord1[2]; Vector2[0] = FaceCoord3[0] - FaceCoord2[0]; Vector2[1] = FaceCoord3[1] - FaceCoord2[1]; Vector2[2] = FaceCoord3[2] - FaceCoord2[2]; normalize(Vector1); CrossProduct(Vector1, Vector2, Normal); normalize(Normal); CrossProduct(Normal, Vector1, Vector2); normalize(Vector2); Vector3[0] = ParticleCoord[0] - FaceCoord1[0]; Vector3[1] = ParticleCoord[1] - FaceCoord1[1]; Vector3[2] = ParticleCoord[2] - FaceCoord1[2]; normalize(Vector3); if (DotProduct(Vector3, Normal) > 0.0) { for (int ia = 0; ia < 3; ia++) { normal_flag = 1.0; LocalCoordSystem[0][ia] = Vector1[ia]; LocalCoordSystem[1][ia] = Vector2[ia]; LocalCoordSystem[2][ia] = Normal [ia]; } } else { for (int ia = 0; ia < 3; ia++) { normal_flag = -1.0; LocalCoordSystem[0][ia] = -Vector1[ia]; LocalCoordSystem[1][ia] = -Vector2[ia]; LocalCoordSystem[2][ia] = -Normal [ia]; } } }//Compute3DimElementFaceLocalSystem /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////******Rotate a point over an arbitrary line though an arbitrary point******///////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static inline void RotatePointAboutArbitraryLine(array_1d<double,3>& TargetPoint, const array_1d<double,3>& CentrePoint, const array_1d<double,3>& LineVector, const double RotationAngle) { const double O = RotationAngle; double x = TargetPoint[0], a = CentrePoint[0], u = LineVector[0]; double y = TargetPoint[1], b = CentrePoint[1], v = LineVector[1]; double z = TargetPoint[2], c = CentrePoint[2], w = LineVector[2]; double L = u*u+v*v+w*w; if (L==0) { } else { const double inv_L = 1.0 / L; TargetPoint[0] = ((a*(v*v+w*w)-u*(b*v+c*w-u*x-v*y-w*z))*(1-cos(O))+L*x*cos(O)+sqrt(L)*(-c*w+b*w-w*y+v*z)*sin(O))* inv_L; TargetPoint[1] = ((b*(u*u+w*w)-v*(a*u+c*w-u*x-v*y-w*z))*(1-cos(O))+L*y*cos(O)+sqrt(L)*(c*u-a*w+w*x-u*z)*sin(O))* inv_L; TargetPoint[2] = ((c*(u*u+v*v)-w*(a*u+b*v-u*x-v*y-w*z))*(1-cos(O))+L*z*cos(O)+sqrt(L)*(-b*u+a*v-v*x+u*y)*sin(O))* inv_L; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////******Quaternions******//////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static inline void QuaternionVectorLocal2Global(const Quaternion<double>& Q, const array_1d<double, 3>& LocalVector, array_1d<double, 3>& GlobalVector) { Q.RotateVector3(LocalVector, GlobalVector); } static inline void QuaternionVectorGlobal2Local(const Quaternion<double>& Q, const array_1d<double, 3>& GlobalVector, array_1d<double, 3>& LocalVector) { Quaternion<double> Q_conj = Q.conjugate(); Q_conj.RotateVector3(GlobalVector, LocalVector); } static inline void QuaternionTensorLocal2Global(const Quaternion<double>& Q, const double LocalTensor[3][3], double GlobalTensor[3][3]) { array_1d<double, 3> LocalTensorC1; array_1d<double, 3> LocalTensorC2; array_1d<double, 3> LocalTensorC3; LocalTensorC1[0] = LocalTensor[0][0]; LocalTensorC2[0] = LocalTensor[0][1]; LocalTensorC3[0] = LocalTensor[0][2]; LocalTensorC1[1] = LocalTensor[1][0]; LocalTensorC2[1] = LocalTensor[1][1]; LocalTensorC3[1] = LocalTensor[1][2]; LocalTensorC1[2] = LocalTensor[2][0]; LocalTensorC2[2] = LocalTensor[2][1]; LocalTensorC3[2] = LocalTensor[2][2]; array_1d<double, 3> TempTensorC1; array_1d<double, 3> TempTensorC2; array_1d<double, 3> TempTensorC3; array_1d<double, 3> TempTensorTraspC1; array_1d<double, 3> TempTensorTraspC2; array_1d<double, 3> TempTensorTraspC3; Q.RotateVector3(LocalTensorC1, TempTensorC1); Q.RotateVector3(LocalTensorC2, TempTensorC2); Q.RotateVector3(LocalTensorC3, TempTensorC3); TempTensorTraspC1[0] = TempTensorC1[0]; TempTensorTraspC2[0] = TempTensorC1[1]; TempTensorTraspC3[0] = TempTensorC1[2]; TempTensorTraspC1[1] = TempTensorC2[0]; TempTensorTraspC2[1] = TempTensorC2[1]; TempTensorTraspC3[1] = TempTensorC2[2]; TempTensorTraspC1[2] = TempTensorC3[0]; TempTensorTraspC2[2] = TempTensorC3[1]; TempTensorTraspC3[2] = TempTensorC3[2]; array_1d<double, 3> GlobalTensorTraspC1; array_1d<double, 3> GlobalTensorTraspC2; array_1d<double, 3> GlobalTensorTraspC3; Q.RotateVector3(TempTensorTraspC1, GlobalTensorTraspC1); Q.RotateVector3(TempTensorTraspC2, GlobalTensorTraspC2); Q.RotateVector3(TempTensorTraspC3, GlobalTensorTraspC3); GlobalTensor[0][0] = GlobalTensorTraspC1[0]; GlobalTensor[0][1] = GlobalTensorTraspC1[1]; GlobalTensor[0][2] = GlobalTensorTraspC1[2]; GlobalTensor[1][0] = GlobalTensorTraspC2[0]; GlobalTensor[1][1] = GlobalTensorTraspC2[1]; GlobalTensor[1][2] = GlobalTensorTraspC2[2]; GlobalTensor[2][0] = GlobalTensorTraspC3[0]; GlobalTensor[2][1] = GlobalTensorTraspC3[1]; GlobalTensor[2][2] = GlobalTensorTraspC3[2]; } static inline void UpdateOrientation(array_1d<double, 3>& EulerAngles, Quaternion<double>& Orientation, const array_1d<double, 3>& DeltaRotation) { Quaternion<double> DeltaOrientation = Quaternion<double>::Identity(); array_1d<double, 3 > theta = DeltaRotation; DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5); double thetaMag = DEM_MODULUS_3(theta); const double epsilon = std::numeric_limits<double>::epsilon(); if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle double aux = (1 - thetaMag * thetaMag / 6); DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag / 2), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } else { double aux = std::sin(thetaMag)/thetaMag; DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } Orientation = DeltaOrientation * Orientation; Orientation.ToEulerAngles(EulerAngles); } static inline void UpdateOrientation(Quaternion<double>& Orientation, const array_1d<double, 3>& DeltaRotation) { Quaternion<double> DeltaOrientation = Quaternion<double>::Identity(); array_1d<double, 3 > theta = DeltaRotation; DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5); double thetaMag = DEM_MODULUS_3(theta); const double epsilon = std::numeric_limits<double>::epsilon(); if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle double aux = (1 - thetaMag * thetaMag / 6); DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag * 0.5), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } else { double aux = std::sin(thetaMag)/thetaMag; DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } Orientation = DeltaOrientation * Orientation; } static inline void UpdateOrientation(const Quaternion<double>& Orientation, Quaternion<double>& NewOrientation, const array_1d<double, 3>& DeltaRotation) { Quaternion<double> DeltaOrientation = Quaternion<double>::Identity(); array_1d<double, 3 > theta = DeltaRotation; DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5); double thetaMag = DEM_MODULUS_3(theta); const double epsilon = std::numeric_limits<double>::epsilon(); if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle double aux = (1 - thetaMag * thetaMag / 6); DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag * 0.5), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } else { double aux = std::sin(thetaMag)/thetaMag; DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } NewOrientation = DeltaOrientation * Orientation; } static inline void EulerAnglesFromRotationAngle(array_1d<double, 3>& EulerAngles, const array_1d<double, 3>& RotatedAngle) { Quaternion<double> Orientation = Quaternion<double>::Identity(); array_1d<double, 3 > theta = RotatedAngle; DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5); double thetaMag = DEM_MODULUS_3(theta); const double epsilon = std::numeric_limits<double>::epsilon(); if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle double aux = (1 - thetaMag * thetaMag / 6); Orientation = Quaternion<double>((1 + thetaMag * thetaMag / 2), theta[0]*aux, theta[1]*aux, theta[2]*aux); Orientation.normalize(); } else { double aux = std::sin(thetaMag)/thetaMag; Orientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux); Orientation.normalize(); } Orientation.ToEulerAngles(EulerAngles); } static inline void OrientationFromRotationAngle(Quaternion<double>& DeltaOrientation, const array_1d<double, 3>& DeltaRotation) { array_1d<double, 3 > theta = DeltaRotation; DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5); double thetaMag = DEM_MODULUS_3(theta); const double epsilon = std::numeric_limits<double>::epsilon(); if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle double aux = (1 - thetaMag * thetaMag / 6); DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag / 2), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } else { double aux = std::sin(thetaMag)/thetaMag; DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux); DeltaOrientation.normalize(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////******EULER ANGLES from 2 vectors******///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*static inline void CalculateEulerAngles(const array_1d<double,3>& OriginalVector_X, const array_1d<double,3>& OriginalVector_Z, const array_1d<double,3>& RotatedVector_X, const array_1d<double,3>& RotatedVector_Z, array_1d<double,3>& EulerAngles) { array_1d< double,3 > N = ZeroVector(3); CrossProduct( OriginalVector_Z, RotatedVector_Z, N); double return1 = DotProduct(N,OriginalVector_X); //cos(Alpha) double return2 = DotProduct(OriginalVector_Z, RotatedVector_Z); //cos(Beta) double return3 = DotProduct(N,RotatedVector_X); //cos(Gamma) EulerAngles[0] = acos(return1); EulerAngles[1] = acos(return2); EulerAngles[2] = acos(return3); }*/ static inline bool InsideOutside(const array_1d<double, 3>& Coord1, const array_1d<double, 3>& Coord2, const array_1d<double, 3>& JudgeCoord, const array_1d<double, 3>& normal_element, double& area){ //NOTE:: Normal_out here has to be the normal of the element orientation (not pointing particle) double b[3]; double p1[3]; double coor[3]; DEM_COPY_SECOND_TO_FIRST_3(coor, Coord1) b[0] = Coord2[0] - coor[0]; b[1] = Coord2[1] - coor[1]; b[2] = Coord2[2] - coor[2]; p1[0] = JudgeCoord[0] - coor[0]; p1[1] = JudgeCoord[1] - coor[1]; p1[2] = JudgeCoord[2] - coor[2]; DEM_SET_TO_CROSS_OF_FIRST_TWO_3(b, p1, coor) if (DEM_INNER_PRODUCT_3(coor, normal_element) >= 0){ area = 0.5 * DEM_MODULUS_3(coor); return true; } else return false; }//InsideOutside static inline bool InsideOutside(const array_1d<double, 3> &Coord1, const array_1d<double, 3>& Coord2, const array_1d<double, 3>& JudgeCoord, const array_1d<double, 3>& normal_element) { //NOTE:: Normal_out here has to be the normal of the element orientation (not pointing particle) array_1d<double, 3> cp1; array_1d<double, 3> b_a; array_1d<double, 3> p1_a; noalias(b_a) = Coord2 - Coord1; noalias(p1_a) = JudgeCoord - Coord1; GeometryFunctions::CrossProduct(b_a, p1_a, cp1); if (GeometryFunctions::DotProduct(cp1, normal_element) >= 0) { //area = sqrt(cp1[0] * cp1[0] + cp1[1] * cp1[1] + cp1[2] * cp1[2]) * 0.5; return true; } else return false; }//InsideOutside static inline void WeightsCalculation(std::vector<double> Area, std::vector<double>& Weight) { unsigned int facet_size = Area.size(); if (facet_size == 3) { const double total_area = Area[0]+Area[1]+Area[2]; const double inv_total_area = 1.0 / total_area; for (unsigned int i = 0; i< 3; i++) { Weight[i] = Area[(i+1)%facet_size] * inv_total_area; } } else if (facet_size == 4) { const double total_discriminant = Area[0]*Area[1]+Area[1]*Area[2]+Area[2]*Area[3]+Area[3]*Area[0]; //(Zhong et al 1993) const double inv_total_discriminant = 1.0 / total_discriminant; for (unsigned int i = 0; i< 4; i++) { Weight[i] = (Area[(i+1)%facet_size]*Area[(i+2)%facet_size]) * inv_total_discriminant; } } else { KRATOS_WATCH("WEIGHTS FOR N-SIZE POLYGONAL FE TO BE IMPLEMENTED") } }//WeightsCalculation static inline bool FastFacetCheck(const std::vector< array_1d <double,3> >& Coord, const array_1d <double,3>& Particle_Coord, double rad, double &DistPToB, unsigned int &current_edge_index) { double A[3]; double B[3]; double PC[3]; for (unsigned int i = 0; i < 3; i++){ B[i] = Coord[0][i]; PC[i] = Coord[1][i]; A[i] = Coord[2][i]; } for (unsigned int i = 0; i < 3; i++){ A[i] = A[i] - PC[i]; B[i] = B[i] - PC[i]; PC[i] = Particle_Coord[i] - PC[i]; } //Calculate Normal double N_fast[3]; DEM_SET_TO_CROSS_OF_FIRST_TWO_3(A, B, N_fast) //normalize double normal_flag = 1.0; if (DEM_INNER_PRODUCT_3(PC, N_fast) < 0){ //it is assumed that Indentation wont be greater than radius so we can detect contacts on both sides of the FE. normal_flag = -1.0; } normalize(N_fast); //Calculate distance: DistPToB = 0.0; for (unsigned int i = 0; i < 3; i++){ DistPToB += normal_flag * N_fast[i] * PC[i]; } if (DistPToB < rad){ array_1d <double, 3> IntersectionCoord; array_1d <double, 3> N; for (unsigned int i = 0; i < 3; i++){ IntersectionCoord[i] = Particle_Coord[i] - DistPToB * normal_flag * N_fast[i]; N[i] = N_fast[i]; } int facet_size = Coord.size(); for (int i = 0; i < facet_size; i++) { double this_area = 0.0; if (InsideOutside(Coord[i], Coord[(i+1)%facet_size], IntersectionCoord, N, this_area) == false){ current_edge_index = i; return false; } } return true; }//if DistPToB < rad return false; }//FastFacetCheck static inline bool FacetCheck(const GeometryType& Coord, const array_1d <double,3>& Particle_Coord, double rad, double LocalCoordSystem[3][3], double& DistPToB, std::vector<double>& Weight, unsigned int& current_edge_index, bool& inside) { int facet_size = Coord.size(); //Calculate Normal array_1d <double,3> A; array_1d <double,3> B; array_1d <double,3> N; array_1d <double,3> PC; for (unsigned int i = 0; i<3; i++) { A[i] = Coord[2].Coordinates()[i]-Coord[1].Coordinates()[i]; B[i] = Coord[0].Coordinates()[i]-Coord[1].Coordinates()[i]; PC[i] = Particle_Coord[i]-Coord[1].Coordinates()[i]; } N[0] = A[1]*B[2] - A[2]*B[1]; N[1] = A[2]*B[0] - A[0]*B[2]; N[2] = A[0]*B[1] - A[1]*B[0]; //normalize double normal_flag = 1.0; if (DotProduct(PC,N) < 0) //it is assumed that Indentation wont be greater than radius so we can detect contacts on both sides of the FE. { normal_flag = - 1.0; N[0]=-N[0]; N[1]=-N[1]; N[2]=-N[2]; } normalize(N); //Calculate distance: DistPToB = 0.0; for (unsigned int i = 0; i<3; i++) { DistPToB += N[i]*PC[i]; } // Check if particle is inside Finite Element (even if contact is not possible, i.e. DistPToB >= rad) array_1d <double,3> IntersectionCoord; for (unsigned int i = 0; i<3; i++) { IntersectionCoord[i] = Particle_Coord[i] - DistPToB*N[i]; } std::vector<double> Area; Area.resize(facet_size); for (int i = 0; i<facet_size; i++) { double this_area = 0.0; if (InsideOutside(Coord[i], Coord[(i+1)%facet_size], IntersectionCoord, normal_flag*N, this_area) == false) { current_edge_index = i; inside = false; return false; } else { inside = true; Area[i] = this_area; //the area adjacent to vertex[ID] is assigned as Area[ID] so further treatment shall be done for the Weight calculation } }//for every vertex if (DistPToB < rad) { double auxiliar_unit_vector[3]; CrossProduct( N,A,auxiliar_unit_vector ); normalize( auxiliar_unit_vector ); normalize( A ); for (unsigned int j = 0; j<3; j++) { LocalCoordSystem[0][j] = A[j]; LocalCoordSystem[1][j] = auxiliar_unit_vector[j]; LocalCoordSystem[2][j] = N[j]; } WeightsCalculation(Area,Weight); return true; }//if DistPToB < rad return false; } //FacetCheck static inline bool FastEdgeVertexCheck(const array_1d<double,3>& Coord1, const array_1d<double,3>& Coord2, const array_1d<double,3>& Particle_Coord, double Radius) { double IntersectionCoordEdge[3]; double normal_unit_vector[3]; double edge_unit_vector[3]; double module_edge_vector = 0.0; double particle_vector1[3]; double particle_vector2[3]; for (unsigned int j = 0; j<3; j++) { edge_unit_vector[j] = Coord2[j] - Coord1[j]; particle_vector1[j] = Particle_Coord[j] - Coord1[j]; particle_vector2[j] = Particle_Coord[j] - Coord2[j]; } normalize( edge_unit_vector, module_edge_vector); double projection_on_edge = DotProduct(particle_vector1,edge_unit_vector); double eta = projection_on_edge/module_edge_vector; if ((eta>=0.0) && (eta<=1.0)) //can only be edge, no vertex { for (unsigned int j = 0; j<3; j++) { IntersectionCoordEdge[j] = Coord1[j] + projection_on_edge*edge_unit_vector[j]; normal_unit_vector[j] = Particle_Coord[j] - IntersectionCoordEdge[j]; } double DistParticleToEdge; normalize( normal_unit_vector, DistParticleToEdge); if (DistParticleToEdge < Radius) { return true; } } if (eta < 0.0) //1rst Vertex { double dist_to_vertex_sq = 0.0; double Rad_sq = Radius*Radius; for (unsigned int j = 0; j<3; j++) { dist_to_vertex_sq +=particle_vector1[j]*particle_vector1[j]; } if (dist_to_vertex_sq < Rad_sq) { return true; } } if (eta > 1.0) //2n vertex { double dist_to_vertex_sq = 0.0; double Rad_sq = Radius*Radius; for (unsigned int j = 0; j<3; j++) { dist_to_vertex_sq +=particle_vector2[j]*particle_vector2[j]; } if (dist_to_vertex_sq < Rad_sq) { return true; } } return false; }//FastEdgeVertexCheck; static inline bool EdgeCheck(const array_1d<double,3>& Coord1, const array_1d<double,3>& Coord2, const array_1d<double,3>& Particle_Coord, double Radius, double LocalCoordSystem[3][3], double& DistParticleToEdge, double& eta) { double IntersectionCoordEdge[3]; double normal_unit_vector[3]; double edge_unit_vector[3]; double module_edge_vector = 0.0; double particle_vector[3]; for (unsigned int j = 0; j<3; j++) { edge_unit_vector[j] = Coord2[j] - Coord1[j]; particle_vector[j] = Particle_Coord[j] - Coord1[j]; } normalize(edge_unit_vector, module_edge_vector); double projection_on_edge = DotProduct(particle_vector,edge_unit_vector); for (unsigned int j = 0; j<3; j++) { IntersectionCoordEdge[j] = Coord1[j] + projection_on_edge*edge_unit_vector[j]; normal_unit_vector[j] = Particle_Coord[j] - IntersectionCoordEdge[j]; } normalize( normal_unit_vector, DistParticleToEdge); eta = projection_on_edge / module_edge_vector; if (DistParticleToEdge < Radius) { if ((eta>=0.0) && (eta<=1.0)) { double dummy_length = 0.0; double auxiliar_unit_vector[3]; CrossProduct(normal_unit_vector,edge_unit_vector,auxiliar_unit_vector); normalize(auxiliar_unit_vector, dummy_length); for (unsigned int j = 0; j<3; j++) { LocalCoordSystem[0][j] = edge_unit_vector[j]; LocalCoordSystem[1][j] = auxiliar_unit_vector[j]; LocalCoordSystem[2][j] = normal_unit_vector[j]; } return true; } } //if distance to edge < radius return false; }//EdgeCheck static inline bool VertexCheck(const array_1d<double,3>& Coord, const array_1d<double,3>& Particle_Coord, double Radius, double LocalCoordSystem[3][3], double& DistParticleToVertex) { double dist_sq = 0.0; array_1d<double, 3> normal_v; for (unsigned int j = 0; j < 3; j++) { normal_v[j] = Particle_Coord[j] - Coord[j]; dist_sq += normal_v[j] * normal_v[j]; } if (dist_sq <= Radius * Radius) { DistParticleToVertex = sqrt(dist_sq); ComputeContactLocalCoordSystem(normal_v, DistParticleToVertex, LocalCoordSystem); return true; } return false; }//VertexCheck static inline bool FastVertexCheck(const array_1d<double,3>& Coord, const array_1d<double,3>& Particle_Coord, double Radius) { double dist_sq = 0.0; array_1d<double, 3> normal_v; for (unsigned int j = 0; j < 3; j++) { normal_v[j] = Particle_Coord[j] - Coord[j]; dist_sq += normal_v[j] * normal_v[j]; } if (dist_sq <= Radius * Radius) return true; return false; }//FastVertexCheck /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////******The four Functions BELOW are used to calculate the weight coefficient for quadrilateral*******/////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*static inline void Coord_transform(double origin[3], double coordsystem[3][3], double Coord[3], double TransCoord[3]) { TransCoord[0]=0.0; TransCoord[1]=0.0; TransCoord[2]=0.0; double vector[3]; vector[0]=Coord[0] - origin[0]; vector[1]=Coord[1] - origin[1]; vector[2]=Coord[2] - origin[2]; TransCoord[0]=DotProduct(coordsystem[0],vector); TransCoord[1]=DotProduct(coordsystem[1],vector); TransCoord[2]=DotProduct(coordsystem[2],vector); }*/ /*static inline void N44(double xp,double yp,double xy[4][2],double& N1,double& N2,double& N3,double& N4) { double xc=(xy[0][0]+xy[1][0]+xy[2][0]+xy[3][0])/4.0; double yc=(xy[0][1]+xy[1][1]+xy[2][1]+xy[3][1])/4.0; double elelength_x=2.0*fabs(xy[0][0]-xc); double elelength_y=2.0*fabs(xy[0][1]-yc); double Eps,Ita; Eps=2.0*(xp-xc)/elelength_x; Ita=2.0*(yp-yc)/elelength_y; N1=0.25*(1+Eps*2*(xy[0][0]-xc)/elelength_x)*(1+Ita*2*(xy[0][1]-yc)/elelength_y); N2=0.25*(1+Eps*2*(xy[1][0]-xc)/elelength_x)*(1+Ita*2*(xy[1][1]-yc)/elelength_y); N3=0.25*(1+Eps*2*(xy[2][0]-xc)/elelength_x)*(1+Ita*2*(xy[2][1]-yc)/elelength_y); N4=0.25*(1+Eps*2*(xy[3][0]-xc)/elelength_x)*(1+Ita*2*(xy[3][1]-yc)/elelength_y); }*/ //Cfeng: irregular quadrilateral transfer to regular quadrilateral /*static inline void gl_to_iso(double x0, double y0, double xy[4][2], double& x_exisp, double& y_etasp) { double exisp=0.0; double etasp=0.0; double tolerance=1.0e-8; double x,y,x1,x2,x3,x4,y1,y2,y3,y4,a1,a2,a3,a4,b1,b2,b3,b4,s1,t1,d1,g1,g2,g0; x1 = xy[0][0]; x2 = xy[1][0]; x3 = xy[2][0]; x4 = xy[3][0]; y1 = xy[0][1]; y2 = xy[1][1]; y3 = xy[2][1]; y4 = xy[3][1]; a1=0.25*(-x1+x2+x3-x4); a2=0.25*(x1-x2+x3-x4); a3=0.25*(-x1-x2+x3+x4); a4=0.25*(x1+x2+x3+x4); b1=0.25*(-y1+y2+y3-y4); b2=0.25*(y1-y2+y3-y4); b3=0.25*(-y1-y2+y3+y4); b4=0.25*(y1+y2+y3+y4); x = x0 - a4; y = y0 - b4; s1 = a2*b3 - a3*b2; t1 = b2*x - a2*y + a1*b3 - a3*b1; d1 = b1*x - a1*y; if (fabs(s1) < tolerance) { etasp = -d1/t1; exisp = (x-a3*etasp) / (a1+a2*etasp); } else { const double sqrt_aux = sqrt(t1*t1-4*s1*d1); g1 = (-t1 + sqrt_aux) / (2*s1); g2 = (-t1 - sqrt_aux) / (2*s1); if (fabs(g1) < 1.0+tolerance) { g0 = (x-a3*g1) / (a1+a2*g1); if (fabs(g0) < 1.0+tolerance) { etasp = g1; exisp = g0; } } if(fabs(g2) < 1.0+tolerance) { g0 = (x-a3*g2) / (a1+a2*g2); if(fabs(g0) < 1.0+tolerance) { etasp = g2; exisp = g0; } } } x_exisp=exisp; y_etasp=etasp; }*/ /*static void CalQuadWeightCoefficient(double Coord[4][3], double LocalCoordSystem[3][3], double IntersectionCoord[3], double Weight[4]) { int j; double FaceCenter[3] = {0.0}; for(j = 0; j < 4; j++) { FaceCenter[0] += Coord[j][0] * 0.25; FaceCenter[1] += Coord[j][1] * 0.25; FaceCenter[2] += Coord[j][2] * 0.25; } double TransCoord0[3],TransCoord1[3],TransCoord2[3],TransCoord3[3]; double xy[4][2]; double xy1[4][2]={{-1.0,-1.0},{1.0,-1.0},{1.0,1.0},{-1.0,1.0}}; double TempLocalCoordSystem[3][3]={{0.0}, {0.0}, {0.0}}; double vx[3]={1.0,0,0},vy[3]={0,1.0,0},vz[3]={0, 0, 1.0}; if( DotProduct(LocalCoordSystem[2],vx)<0 || DotProduct(LocalCoordSystem[2],vy)<0 || DotProduct(LocalCoordSystem[2],vz)<0 ) { for(j=0;j<3;j++) { TempLocalCoordSystem[0][j] = LocalCoordSystem[0][j]; TempLocalCoordSystem[1][j] = LocalCoordSystem[1][j]; TempLocalCoordSystem[2][j] = -LocalCoordSystem[2][j]; } } else { for(j=0;j<3;j++) { TempLocalCoordSystem[0][j] = LocalCoordSystem[0][j]; TempLocalCoordSystem[1][j] = LocalCoordSystem[1][j]; TempLocalCoordSystem[2][j] = LocalCoordSystem[2][j]; } } Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[0], TransCoord0); Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[1], TransCoord1); Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[2], TransCoord2); Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[3], TransCoord3); xy[0][0] = TransCoord0[0]; xy[0][1] = TransCoord0[1]; xy[1][0] = TransCoord1[0]; xy[1][1] = TransCoord1[1]; xy[2][0] = TransCoord2[0]; xy[2][1] = TransCoord2[1]; xy[3][0] = TransCoord3[0]; xy[3][1] = TransCoord3[1]; double in0=0.0, in1=0.0, in2=0.0, in3=0.0; double TransCoordp[3]; double Coordp_iso[2]; Coord_transform(FaceCenter, TempLocalCoordSystem, IntersectionCoord, TransCoordp); gl_to_iso(TransCoordp[0],TransCoordp[1],xy,Coordp_iso[0],Coordp_iso[1]); N44(Coordp_iso[0],Coordp_iso[1], xy1, in0, in1, in2, in3); Weight[0]=in0; Weight[1]=in1; Weight[2]=in2; Weight[3]=in3; }*/ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////******The four Functions ABOVE are used to calculate the weight coefficient for quadrilateral*******/////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static inline void GetRotationMatrix(const array_1d<double, 3>& EulerAngles, double rotation_matrix[3][3]) { double cosA=cos(EulerAngles[0]); double sinA=sin(EulerAngles[0]); double cosB=cos(EulerAngles[1]); double sinB=sin(EulerAngles[1]); double cosC=cos(EulerAngles[2]); double sinC=sin(EulerAngles[2]); rotation_matrix[0][0] = cosC*cosA - cosB*sinA*sinC; rotation_matrix[0][1] = -sinC*cosA - cosB*sinA*cosC; rotation_matrix[0][2] = sinB*sinA; rotation_matrix[1][0] = cosC*sinA + cosB*cosA*sinC; rotation_matrix[1][1] = -sinC*sinA + cosB*cosA*cosC; rotation_matrix[1][2] = -sinB*cosA; rotation_matrix[2][0] = sinC*sinB; rotation_matrix[2][1] = cosC*sinB; rotation_matrix[2][2] = cosB; return; } static inline void GetEulerAngles(const double rotation_matrix[3][3], array_1d<double, 3 > & EulerAngles) { if (rotation_matrix[2][2] < 1.0) { if (rotation_matrix[2][2] > -1.0) { EulerAngles[0] = atan2(rotation_matrix[0][2], -rotation_matrix[1][2]); EulerAngles[1] = acos(rotation_matrix[2][2]); EulerAngles[2] = atan2(rotation_matrix[2][0], rotation_matrix[2][1]); } else // r22 = -1 { // Not a unique solution: thetaZ1 - thetaZ0 = atan2(-r01,r00) EulerAngles[0] = -atan2(-rotation_matrix[0][1], rotation_matrix[0][0]); EulerAngles[1] = Globals::Pi; EulerAngles[2] = 0; } } else // r22 = +1 { // Not a unique solution: thetaZ1 + thetaZ0 = atan2(-r01,r00) EulerAngles[0] = atan2(-rotation_matrix[0][1], rotation_matrix[0][0]); EulerAngles[1] = 0; EulerAngles[2] = 0; } return; } static inline void GetGiDEulerAngles(const BoundedMatrix<double, 3, 3>& rotation_matrix, array_1d<double, 3>& EulerAngles) { const double numerical_limit = std::numeric_limits<double>::epsilon(); const double two_pi = 3.1415926535897932384626433 * 2.0; if(rotation_matrix(2, 2)<1.0-numerical_limit && rotation_matrix(2, 2)>-1.0+numerical_limit){ const double senb=sqrt(1.0-rotation_matrix(2, 2)*rotation_matrix(2, 2)); EulerAngles[1]=acos(rotation_matrix(2, 2)); EulerAngles[2]=acos(rotation_matrix(1, 2)/senb); if(rotation_matrix(0, 2)/senb<0.0) EulerAngles[2]=two_pi - EulerAngles[2]; EulerAngles[0]=acos(-rotation_matrix(2, 1)/senb); if(rotation_matrix(2, 0)/senb<0.0) EulerAngles[0]=two_pi - EulerAngles[0]; } else { // fixed a=0.0 (arbitrary) EulerAngles[1]=acos(rotation_matrix(2, 2)); EulerAngles[0]=0.0; EulerAngles[2]=acos(rotation_matrix(0, 0)); if(-rotation_matrix(1, 0)<0.0) EulerAngles[2]=two_pi - EulerAngles[2]; } } inline void QuaternionToGiDEulerAngles(const Quaternion<double>& quaternion, array_1d<double, 3>& EulerAngles) { BoundedMatrix<double, 3, 3> rotation_matrix = ZeroMatrix(3,3); quaternion.ToRotationMatrix(rotation_matrix); GetGiDEulerAngles(rotation_matrix, EulerAngles); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////****************************TRIANGLE - SPHERE INTERSECTION AREA CALCULATION**************************/////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static inline void TriAngleArea(double Coord1[3], double Coord2[3], double Coord3[3], double& area) { int k; double Vector1[3],Vector2[3],Vector0[3]; for (k = 0;k < 3; k++) { Vector1[k] = Coord3[k] - Coord1[k]; Vector2[k] = Coord2[k] - Coord1[k]; } CrossProduct(Vector1, Vector2, Vector0); area = 0.5 * DEM_MODULUS_3(Vector0); } //TriAngle Weight, coord1,coord2,coord3,testcoord,weight static inline void TriAngleWeight(double Coord1[3], double Coord2[3], double Coord3[3], double JudgeCoord[3], double Weight[3]) { double area[3], s; TriAngleArea(Coord1, Coord2, JudgeCoord, area[0]); TriAngleArea(Coord2, Coord3, JudgeCoord, area[1]); TriAngleArea(Coord3, Coord1, JudgeCoord, area[2]); TriAngleArea(Coord1, Coord2, Coord3, s); /////s = area[0] + area[1] + area[2]; const double s_inv = 1.0 / s; Weight[0] = area[1] * s_inv; Weight[1] = area[2] * s_inv; Weight[2] = area[0] * s_inv; } //Quadrilatera Weight, coord1,coord2,coord3,testcoord,weight (Paper Zhang) static inline void QuadAngleWeight(double Coord1[3], double Coord2[3], double Coord3[3], double Coord4[3], double JudgeCoord[3], double Weight[4]) { double area[4], s1, s2, s; TriAngleArea(Coord1, Coord2, JudgeCoord, area[0]); TriAngleArea(Coord2, Coord3, JudgeCoord, area[1]); TriAngleArea(Coord3, Coord4, JudgeCoord, area[2]); TriAngleArea(Coord4, Coord1, JudgeCoord, area[3]); TriAngleArea(Coord1, Coord2, Coord3, s1);//msimsi TriAngleArea(Coord1, Coord3, Coord4, s2);//msimsi s = s1 + s2; if (fabs(area[0] + area[1] + area[2] + area[3] - s) < 1.0e-15) //msimsi { double QuadNormArea = 1 / ((area[0] + area[2]) * (area[1] + area[3])); Weight[0] = (area[1] * area[2]) * QuadNormArea; Weight[1] = (area[2] * area[3]) * QuadNormArea; Weight[2] = (area[3] * area[0]) * QuadNormArea; Weight[3] = (area[0] * area[1]) * QuadNormArea; } } static inline void AreaAndCentroidCircularSector(double C[3], double Radius, double P1[3], double P2[3], double Normal[3], double& Area, double CoMSC[3]) { double a[3] = {0.0}; double c[3] = {0.0}; double bisection[3] = {0.0}; double norm_a = 0.0; for (unsigned int index = 0;index<3;index++) { a[index] = P1[index]-C[index]; c[index] = P2[index]-P1[index]; } CrossProduct(Normal,c,bisection); normalize(bisection); double dot_product = DotProduct(bisection,a); if (dot_product<0.0) { for (unsigned int index = 0;index<3;index++) { bisection[index] = -bisection[index]; } dot_product = -dot_product; } module(a, norm_a); double cos_alpha = dot_product/norm_a; double alpha = acos(cos_alpha); double sin_alpha = std::sin(alpha); Area = Radius*Radius*alpha; double dist = 0.66666666666666*(Radius*sin_alpha/alpha); for (unsigned int index = 0;index<3;index++) { CoMSC[index] = C[index]+dist*bisection[index]; } }//AreaCircularSector static inline void AlternativeAreaCircularSegment(double Radius, double tol_Radius, double V0V1[3], double V0CC[3], double Normal[3], double& AreaSC, bool& flag) { double normal_outwards[3] = {0.0}; flag = false; AreaSC = 0.0; CrossProduct(V0V1, Normal, normal_outwards); normalize(normal_outwards); double dist = DotProduct(normal_outwards,V0CC); double delta_circle = Radius + dist; //distance can be positive or negative, depending on the side where the circle is if ((delta_circle > tol_Radius) && (delta_circle - 2*Radius < -tol_Radius)) {//check for intersection flag = true; double b = sqrt(delta_circle*(2*Radius-delta_circle)); AreaSC = 2.0*Radius*Radius*atan(delta_circle/b)-b*(Radius-delta_circle); } }//AreaAndCentroidCircularSector1 static inline void AreaAndCentroidCircularSegment(double Centre[3], double Radius, double tol_Radius, double V0[3], double V1[3], double Normal[3], double& AreaSegC, double CoMSegC[3], bool& flag) { double V0V1[3] = {0.0}; double V0CC[3] = {0.0}; double a[3] = {0.0}; double normal_outwards[3] = {0.0}; double Radius_SQ = 0.0; double distance_V0V1 = 0.0; double dist_CoM = 0.0; AreaSegC = 0.0; flag = false; for (unsigned int index = 0; index<3; index++) { V0V1[index] = V1[index] - V0[index]; V0CC[index] = Centre[index] - V0[index]; } GeometryFunctions::CrossProduct(V0V1,Normal,normal_outwards); GeometryFunctions::normalize(V0V1,distance_V0V1); double distV0 = GeometryFunctions::DotProduct(V0CC,V0V1); if ((distV0 > 0.0) && (distV0 < distance_V0V1)) { GeometryFunctions::normalize(normal_outwards); double dist_normal = GeometryFunctions::DotProduct(normal_outwards,V0CC); double delta_circle = Radius + dist_normal; //distance can be positive or negative, depending on the side where the circle is if ((delta_circle > tol_Radius) && ( delta_circle - 2.0*Radius < -tol_Radius)) {//check for intersection Radius_SQ = Radius*Radius; double semi_dist = sqrt(Radius_SQ - dist_normal*dist_normal); flag = true; for (unsigned int index = 0;index<3;index++) { a[index] = V0[index] + (distV0 - semi_dist)*V0V1[index] - Centre[index]; //Vector from Center to first intersection point } double cos_alpha = GeometryFunctions::DotProduct(a,normal_outwards)/(GeometryFunctions::module(a)*GeometryFunctions::module(normal_outwards)); double alpha = acos(cos_alpha); double sin_alpha = std::sin(alpha); AreaSegC = Radius_SQ*(alpha-sin_alpha*cos_alpha); if (fabs(sin_alpha) < tol_Radius) {dist_CoM=0.0;} else {dist_CoM = 0.6666666666666 * (Radius*sin_alpha*sin_alpha*sin_alpha/(alpha-sin_alpha*cos_alpha));} for (unsigned int index = 0; index<3; index++) { CoMSegC[index] = Centre[index] + dist_CoM*normal_outwards[index]; } } //if normal dist is okay } // if longitudinal dist is okay }//AreaAndCentroidCircularSegment static inline void AreaAndCentroidTriangle(double Coord1[3], double Coord2[3], double Coord3[3], double& area, double CoMTri[3]) { TriAngleArea(Coord1,Coord2,Coord3,area); for (unsigned int index =0; index<3; index++) { CoMTri[index] = 0.33333333333333 * (Coord1[index]+Coord2[index]+Coord3[index]); } } //AreaAndCentroidTriangle } //namespace GeometryFunctions } //namespace Kratos #endif /* _GEOMETRYFUNCTIONS_H */
GB_unop__identity_bool_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_bool_fc32 // op(A') function: GB_unop_tran__identity_bool_fc32 // C type: bool // A type: GxB_FC32_t // cast: bool cij = (crealf (aij) != 0) || (cimagf (aij) != 0) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ bool z = (crealf (aij) != 0) || (cimagf (aij) != 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = (crealf (aij) != 0) || (cimagf (aij) != 0) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_bool_fc32 ( bool *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; bool z = (crealf (aij) != 0) || (cimagf (aij) != 0) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; bool z = (crealf (aij) != 0) || (cimagf (aij) != 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_bool_fc32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 4; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
GB_unop__identity_uint8_bool.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_uint8_bool // op(A') function: GB_unop_tran__identity_uint8_bool // C type: uint8_t // A type: bool // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint8_t z = (uint8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = (uint8_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_UINT8 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint8_bool ( uint8_t *Cx, // Cx and Ax may be aliased const bool *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool aij = Ax [p] ; uint8_t z = (uint8_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_uint8_bool ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
PoW.c
// Copyright (c) 2016-2018 The Ulord Core Foundation #include "PoW.h" #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <assert.h> #ifndef MAC_OSX #include <omp.h> #endif #include "my_time.h" #include "common.h" #include "my_rand48_r.h" #include "oneWayFunction.h" // #define SSE_VERSION /* * Step 1: Initialize working memory. */ void initWorkMemory(uint8_t *input, uint32_t inputLen, uint8_t *Maddr, const uint32_t K) { uint32_t i, j; uint8_t a[OUTPUT_LEN], b[OUTPUT_LEN]; funcInfor[0].func(input, inputLen, a); uint64_t randSeed[4] = {0, 0, 0, 0}; #ifndef SSE_VERSION struct my_rand48_data randBuffer[4]; #else struct vrand48_data randBuffer[2]; #endif const uint32_t iterNum = WORK_MEMORY_SIZE >> 5; for (i = 0; i < iterNum; ++i) { if (i % K) { #ifndef SSE_VERSION uint64_t num = 0; for (j = 0; j < 4; ++j) { my_rand64_r(&randBuffer[j], &num); memcpy(b + (j << 3), (uint8_t *)&num, 8*sizeof(uint8_t)); } #else vrand64(b, randBuffer); #endif uint8_t shift_num; uint8_t result[OUTPUT_LEN]; reduce_bit((uint8_t *)&i, 4, (uint8_t *)&shift_num, 8); rrs(b, OUTPUT_LEN, result, shift_num); memcpy(Maddr + (i << 5), result, OUTPUT_LEN*sizeof(uint8_t)); for (j = 0; j < 32; ++j) { a[j] ^= result[j]; } } else { uint8_t t = 0, shift_num = 0; reduce_bit(a, 32, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit((uint8_t *)&i, 4, (uint8_t *)&shift_num, 8); uint8_t a_rrs[INPUT_LEN]; rrs(a, OUTPUT_LEN, a_rrs, shift_num); funcInfor[t].func(a_rrs, 32, a); reduce_bit(a, 8, (uint8_t *)&randSeed[0], 48); reduce_bit(a + 8, 8, (uint8_t *)&randSeed[1], 48); reduce_bit(a + 16, 8, (uint8_t *)&randSeed[2], 48); reduce_bit(a + 24, 8, (uint8_t *)&randSeed[3], 48); #ifndef SSE_VERSION my_seed48_r(randSeed[0], &randBuffer[0]); my_seed48_r(randSeed[1], &randBuffer[1]); my_seed48_r(randSeed[2], &randBuffer[2]); my_seed48_r(randSeed[3], &randBuffer[3]); #else vseed48(randSeed , &randBuffer[0]); vseed48(randSeed + 2, &randBuffer[1]); #endif memcpy(Maddr + (i << 5), a, 32*sizeof(uint8_t)); } } } /* * Step 2: Modify the working memory contents. */ void modifyWorkMemory(uint8_t *Maddr, const uint32_t L, const uint32_t C, uint8_t *result) { uint32_t i, j; uint8_t a[OUTPUT_LEN], b[64]; funcInfor[0].func(Maddr + WORK_MEMORY_SIZE - 32, 32, a); memcpy(result, a, OUTPUT_LEN*sizeof(uint8_t)); uint64_t r = 0; reduce_bit(a, 32, (uint8_t *)&r, 64); const uint32_t iterNum = L << 6; for (i = 0; i < C; ++i) { uint64_t randSeed = 0; reduce_bit(a, 32, (uint8_t *)&randSeed, 48); struct my_rand48_data randBuffer; my_seed48_r(randSeed, &randBuffer); uint8_t t1, t2, s; uint64_t randNum = 0, base = 0; for (j = 0; j < iterNum; ++j) { my_rand48_r(&randBuffer, &randNum); base = randNum + r; uint64_t offset = 0; reduce_bit((uint8_t *)&r, 8, (uint8_t *)&offset, 8); offset = (offset << 8) + 1; uint64_t addr1 = (base + WORK_MEMORY_SIZE - offset) % WORK_MEMORY_SIZE; uint64_t addr2 = (base + offset) % WORK_MEMORY_SIZE; t1 = Maddr[addr1]; t2 = Maddr[addr2]; s = a[j & 0x1f]; Maddr[addr1] = t2 ^ s; Maddr[addr2] = t1 ^ s; b[j & 0x3f] = t1 ^ t2; r = r + s + t1 + t2; } uint8_t t = 0; reduce_bit((uint8_t *)&r, 8, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit(b, 64, a, 256); uint8_t shift_num = 0; uint64_t ir = r + i; reduce_bit((uint8_t *)&ir, 8, (uint8_t *)&shift_num, 8); uint8_t a_rrs[INPUT_LEN]; rrs(a, OUTPUT_LEN, a_rrs, shift_num); funcInfor[t].func(a_rrs, 32, a); for (j = 0; j < OUTPUT_LEN; ++j) { result[j] ^= a[j]; } } } /* * Step 3: Calculate the final result. */ void calculateFinalResult(uint8_t *Maddr, uint8_t *c, const uint32_t D, uint8_t *result) { uint32_t i = 0, j = 0, k = 0; memcpy(result, c, OUTPUT_LEN*sizeof(uint8_t)); const uint32_t num = (WORK_MEMORY_SIZE >> 5) - 1; uint32_t it = 0; uint8_t result_rrs[OUTPUT_LEN]; while(1) { uint8_t t = 0, shift_num = 0; uint32_t d = 0; reduce_bit(result, 32, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit(result, 32, (uint8_t *)&d, D); ++d; for (j = 0; j < d; ++j) { uint32_t index = i << 5; for (k = 0; k < 32; ++k) { result[k] ^= Maddr[index + k]; } ++i; if (i == num) { it = i + t; reduce_bit((uint8_t *)&it, 4, (uint8_t *)&shift_num, 8); rrs(result, OUTPUT_LEN, result_rrs, shift_num); funcInfor[0].func(result_rrs, 32, result); return; } } it = t + i; reduce_bit((uint8_t *)&it, 4, (uint8_t *)&shift_num, 8); rrs(result, OUTPUT_LEN, result_rrs, shift_num); funcInfor[t].func(result_rrs, 32, result); } } /* * Correctness & Performance test for Proof of work */ void testPowFunction(uint8_t *mess, uint32_t messLen, const int64_t iterNum) { int64_t j; uint32_t inputLen = messLen; uint8_t input[INPUT_LEN], output[OUTPUT_LEN]; memset(input, 0, INPUT_LEN*sizeof(uint8_t)); memcpy(input, mess, messLen*sizeof(char)); // Init all one-way function initOneWayFunction(); uint8_t *Maddr = (uint8_t *)malloc(64 * WORK_MEMORY_SIZE*sizeof(uint8_t)); assert(NULL != Maddr); memset(Maddr, 0, 64 * WORK_MEMORY_SIZE*sizeof(uint8_t)); printf("****************************** Correctness test (PoW function) ******************************\n"); printf("Test message: %s\n", mess); powFunction(input, inputLen, Maddr, output); view_data_u8("PoW", output, OUTPUT_LEN); printf("*********************************************************************************************\n"); /* printf("*************************************************** Performance test (PoW function) ***************************************************\n"); uint8_t *result = (uint8_t *)malloc(iterNum * OUTPUT_LEN * sizeof(uint8_t)); assert(NULL != result); memset(result, 0, iterNum * OUTPUT_LEN * sizeof(uint8_t)); uint32_t threadNumArr[] = {1, 4, 8, 12, 16, 20, 24, 32, 48, 64}; uint32_t threadNumTypes = sizeof(threadNumArr) / sizeof(uint32_t); printf(" %-18s", "Algorithm"); for (uint32_t ix = 0; ix < threadNumTypes; ++ix) printf("%12d", threadNumArr[ix]); printf("\n"); printf("00 %-18s\t", "PoW"); for (uint32_t ix = 0; ix < threadNumTypes; ++ix) { omp_set_num_threads(threadNumArr[ix]); double startTime = get_wall_time(); if (threadNumArr[ix] == 1) { for (j = 0; j < iterNum; ++j) { powFunction(input, inputLen, Maddr, result + j * OUTPUT_LEN); } } else { #pragma omp parallel for firstprivate(input), private(j) shared(result) for (j = 0; j < iterNum; ++j) { powFunction(input, inputLen, Maddr + omp_get_thread_num() * WORK_MEMORY_SIZE, result + j * OUTPUT_LEN); } } double endTime = get_wall_time(); double costTime = endTime - startTime; printf("%5.0f bps ", iterNum / costTime); fflush(stdout); // Check result for (j = 0; j < iterNum; j += 1) { if (memcmp(output, result + j * OUTPUT_LEN, OUTPUT_LEN)) { printf("Thread num: %d, j: %ld\n", threadNumArr[ix], j); view_data_u8("output", output, OUTPUT_LEN); view_data_u8("result", result + j * OUTPUT_LEN, OUTPUT_LEN); abort(); } } } printf("\n"); printf("***************************************************************************************************************************************\n"); if (NULL != result) { free(result); result = NULL; } */ if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } #define OUTPUT_BUFFER_SIZE (32 * 1024UL * 1024UL) #define MAX_TEST_INPUT_LEN 140 #define MAX_OUT_FILE_NAME_LEN 25 const char testInputCase[][MAX_TEST_INPUT_LEN] = { "", "HelloWorld", "0123456789" }; void powNistTest(const char *outFileName) { const uint64_t iterNum = 1024UL * 1024UL; // const uint64_t iterNum = 1024UL; uint8_t *outputBuffer = (uint8_t *)malloc(OUTPUT_BUFFER_SIZE * sizeof(uint8_t)); assert(NULL != outputBuffer); memset(outputBuffer, 0, OUTPUT_BUFFER_SIZE * sizeof(uint8_t)); uint8_t *Maddr = (uint8_t *)malloc(WORK_MEMORY_SIZE*sizeof(uint8_t)); assert(NULL != Maddr); memset(Maddr, 0, WORK_MEMORY_SIZE*sizeof(uint8_t)); initOneWayFunction(); uint32_t testInputCaseNum = sizeof(testInputCase) / sizeof(const char [MAX_TEST_INPUT_LEN]); for (uint32_t testCaseIx = 0; testCaseIx < testInputCaseNum; ++testCaseIx) { char curOutFileName[MAX_OUT_FILE_NAME_LEN] = ""; sprintf(curOutFileName, "%s-%u.txt", outFileName, testCaseIx); FILE *fp = NULL; if (NULL != (fp = fopen(curOutFileName, "wb"))) { const uint32_t testInputCaseLen = strlen((char *)testInputCase[testCaseIx]); uint8_t input[MAX_TEST_INPUT_LEN]; memset(input, 0, MAX_TEST_INPUT_LEN*sizeof(uint8_t)); memcpy(input, testInputCase[testCaseIx], testInputCaseLen*sizeof(uint8_t)); double startTime = get_wall_time(); powFunction(input, testInputCaseLen, Maddr, outputBuffer); for (uint64_t i = 1, j = 0; i < iterNum; ++i) { memcpy(input, outputBuffer + j, OUTPUT_LEN * sizeof(uint32_t)); j += OUTPUT_LEN; powFunction(input, OUTPUT_LEN, Maddr, outputBuffer + j); /* if (j == OUTPUT_BUFFER_SIZE) { fwrite(outputBuffer, sizeof(uint8_t), OUTPUT_BUFFER_SIZE / sizeof(uint8_t), fp); j = 0; } */ } double endTime = get_wall_time(); double costTime = endTime - startTime; fprintf(stdout, "TestCaseIx: %d, Input: %s, IterNum: %llu, Time: %4.2f, Performance: %5.2f bps\n", testCaseIx, \ testInputCase[testCaseIx], iterNum, costTime, ((double)(iterNum * OUTPUT_LEN)) / costTime); fflush(stdout); fwrite(outputBuffer, sizeof(uint8_t), OUTPUT_BUFFER_SIZE / sizeof(uint8_t), fp); fclose(fp); } else { fprintf(stderr, "Error: Open %s failed!\n", curOutFileName); abort(); } } if (NULL != outputBuffer) { free(outputBuffer); outputBuffer = NULL; } if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } void helloHash(const uint8_t *mess, uint32_t messLen, uint8_t output[OUTPUT_LEN]) { if(messLen != INPUT_LEN) { printf("helloHash:Invalid message length %d\n", messLen); return; } int64_t j; uint32_t inputLen =messLen; uint8_t input[INPUT_LEN]; memset(input, 0, INPUT_LEN*sizeof(uint8_t)); memcpy(input, mess, inputLen*sizeof(char)); //operation: input uint8_t *Maddr = (uint8_t *)malloc(WORK_MEMORY_SIZE*sizeof(uint8_t)); //1024*1024*1 assert(NULL != Maddr); memset(Maddr, 0, WORK_MEMORY_SIZE*sizeof(uint8_t)); powFunction(input, inputLen,Maddr, output); //view_data_u8("PoW", output, OUTPUT_LEN); //output if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } int my_rand64_r (struct my_rand48_data *buffer, uint64_t *result) { uint64_t X = buffer->__x; X = (X * buffer->__a + buffer->__c) & 0xffffffffffffULL; buffer->__x = X; buffer->__x = (X * buffer->__a + buffer->__c) & 0xffffffffffffULL; X ^= buffer->__x << 16; *result = X; return 0; } int my_seed48_r (uint64_t seedval, struct my_rand48_data *buffer) { buffer->__x = seedval & 0xffffffffffffULL; buffer->__a = 0x5deece66dULL; buffer->__c = 0xb; return 0; } void powFunction(uint8_t *input, uint32_t inputLen, uint8_t *Maddr, uint8_t *output) { uint8_t c[OUTPUT_LEN]; // Step 1: Initialize working memory. initWorkMemory(input, inputLen, Maddr, 128); // view_data_u8("Maddr", Maddr, OUTPUT_LEN); // Step 2: Modify the working memory contents. modifyWorkMemory(Maddr, 4, WORK_MEMORY_SIZE >> 11, c); // view_data_u8("c", c, OUTPUT_LEN); // Step 3: Calculate the final result. calculateFinalResult(Maddr, c, 8, output); // view_data_u8("output", output, OUTPUT_LEN); } int my_rand48_r (struct my_rand48_data *buffer, uint64_t *result) { *result = (buffer->__x * buffer->__a + buffer->__c) & 0xffffffffffffULL; buffer->__x = *result; return 0; }
kinFoodWeb_kry_omp.c
/* ----------------------------------------------------------------- * Programmer(s): Ting Yan @ SMU * Based on kinFoodWeb_kry.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example (serial): * * This example solves a nonlinear system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion * on the unit square in two dimensions. The dependent variable * vector is the following: * * 1 2 ns * c = (c , c , ..., c ) (denoted by the variable cc) * * and the PDE's are as follows: * * i i * 0 = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The number np is both the * number of prey and predator species. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * b(i) = BB * (1 + alpha * x * y) (i <= np) * b(i) =-BB * (1 + alpha * x * y) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED ( i > np) * * The various scalar parameters are set using define's or in * routine InitUserData. * * The boundary conditions are: normal derivative = 0, and the * initial guess is constant in x and y, but the final solution * is not. * * The PDEs are discretized by central differencing on an MX by * MY mesh. * * The nonlinear system is solved by KINSOL using the method * specified in the local variable globalstrat. * * The preconditioner matrix is a block-diagonal matrix based on * the partial derivatives of the interaction terms f only. * * Constraints are imposed to make all components of the solution * positive. * * Optionally, we can set the number of threads with an environment * variable or from the command line. To check the current value * for number of threads set by the environment variable: * % echo $OMP_NUM_THREADS * * Execution: * * If the user wants to use the default value or the number of * threads set by the environment variable use * % ./kinFoodWeb_kry_omp * If the user wants to specify the number of threads to use * % ./kinFoodWeb_kry_omp num_threads * where num_threads is the number of threads the user wants to use * * ----------------------------------------------------------------- * References: * * 1. Peter N. Brown and Youcef Saad, * Hybrid Krylov Methods for Nonlinear Systems of Equations * LLNL report UCRL-97645, November 1987. * * 2. Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, * Lawrence Livermore National Laboratory Report UCRL-95088, * Rev. 1, June 1987, and Journal of Applied Mathematics and * Computation, Vol. 31 (May 1989), pp. 40-91. (Presents a * description of the time-dependent version of this test * problem.) * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <kinsol/kinsol.h> /* access to KINSOL func., consts. */ #include <nvector/nvector_openmp.h> /* access to OpenMP N_Vector */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */ #include <sundials/sundials_dense.h> /* use generic dense solver in precond. */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ #include <sundials/sundials_math.h> /* access to SUNMAX, SUNRabs, SUNRsqrt */ #ifdef _OPENMP #include <omp.h> #endif /* Problem Constants */ #define NUM_SPECIES 6 /* must equal 2*(number of prey or predators) number of prey = number of predators */ #define PI RCONST(3.1415926535898) /* pi */ #define MX 8 /* MX = number of x mesh points */ #define MY 8 /* MY = number of y mesh points */ #define NSMX (NUM_SPECIES * MX) #define NEQ (NSMX * MY) /* number of equations in the system */ #define AA RCONST(1.0) /* value of coefficient AA in above eqns */ #define EE RCONST(10000.) /* value of coefficient EE in above eqns */ #define GG RCONST(0.5e-6) /* value of coefficient GG in above eqns */ #define BB RCONST(1.0) /* value of coefficient BB in above eqns */ #define DPREY RCONST(1.0) /* value of coefficient dprey above */ #define DPRED RCONST(0.5) /* value of coefficient dpred above */ #define ALPHA RCONST(1.0) /* value of coefficient alpha above */ #define AX RCONST(1.0) /* total range of x variable */ #define AY RCONST(1.0) /* total range of y variable */ #define FTOL RCONST(1.e-7) /* ftol tolerance */ #define STOL RCONST(1.e-13) /* stol tolerance */ #define THOUSAND RCONST(1000.0) /* one thousand */ #define ZERO RCONST(0.0) /* 0. */ #define ONE RCONST(1.0) /* 1. */ #define TWO RCONST(2.0) /* 2. */ #define PREYIN RCONST(1.0) /* initial guess for prey concentrations. */ #define PREDIN RCONST(30000.0)/* initial guess for predator concs. */ /* User-defined vector access macro: IJ_Vptr */ /* IJ_Vptr is defined in order to translate from the underlying 3D structure of the dependent variable vector to the 1D storage scheme for an N-vector. IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to indices is = 0, jx = i, jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, i*NUM_SPECIES + j*NSMX)) /* Type : UserData contains preconditioner blocks, pivot arrays, and problem constants */ typedef struct { realtype **P[MX][MY]; sunindextype *pivot[MX][MY]; realtype **acoef, *bcoef; N_Vector rates; realtype *cox, *coy; realtype ax, ay, dx, dy; realtype uround, sqruround; sunindextype mx, my, ns, np; int nthreads; } *UserData; /* Functions Called by the KINSOL Solver */ static int func(N_Vector cc, N_Vector fval, void *user_data); static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data); static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data); /* Private Helper Functions */ static UserData AllocUserData(void); static void InitUserData(UserData data); static void FreeUserData(UserData data); static void SetInitialProfiles(N_Vector cc, N_Vector sc); static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol); static void PrintOutput(N_Vector cc); static void PrintFinalStats(void *kmem); static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data); static realtype DotProd(sunindextype size, realtype *x1, realtype *x2); static int check_flag(void *flagvalue, const char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { int globalstrategy; realtype fnormtol, scsteptol; N_Vector cc, sc, constraints; UserData data; int flag, maxl, maxlrst; void *kmem; SUNLinearSolver LS; int num_threads; cc = sc = constraints = NULL; kmem = NULL; LS = NULL; data = NULL; /* Allocate memory, and set problem data, initial values, tolerances */ globalstrategy = KIN_NONE; /* Set the number of threads to use */ num_threads = 1; /* default value*/ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* Overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrithe with command line value, if supplied */ num_threads = strtol(argv[1], NULL, 0); data = AllocUserData(); if (check_flag((void *)data, "AllocUserData", 2)) return(1); InitUserData(data); data->nthreads = num_threads; /* Create serial vectors of length NEQ */ cc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)cc, "N_VNew_OpenMP", 0)) return(1); sc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)sc, "N_VNew_OpenMP", 0)) return(1); data->rates = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)data->rates, "N_VNew_OpenMP", 0)) return(1); constraints = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)constraints, "N_VNew_OpenMP", 0)) return(1); N_VConst(TWO, constraints); SetInitialProfiles(cc, sc); fnormtol=FTOL; scsteptol=STOL; /* Call KINCreate/KINInit to initialize KINSOL. A pointer to KINSOL problem memory is returned and stored in kmem. */ kmem = KINCreate(); if (check_flag((void *)kmem, "KINCreate", 0)) return(1); /* Vector cc passed as template vector. */ flag = KINInit(kmem, func, cc); if (check_flag(&flag, "KINInit", 1)) return(1); flag = KINSetUserData(kmem, data); if (check_flag(&flag, "KINSetUserData", 1)) return(1); flag = KINSetConstraints(kmem, constraints); if (check_flag(&flag, "KINSetConstraints", 1)) return(1); flag = KINSetFuncNormTol(kmem, fnormtol); if (check_flag(&flag, "KINSetFuncNormTol", 1)) return(1); flag = KINSetScaledStepTol(kmem, scsteptol); if (check_flag(&flag, "KINSetScaledStepTol", 1)) return(1); /* We no longer need the constraints vector since KINSetConstraints creates a private copy for KINSOL to use. */ N_VDestroy_OpenMP(constraints); /* Create SUNLinSol_SPGMR object with right preconditioning and the maximum Krylov dimension maxl */ maxl = 15; LS = SUNLinSol_SPGMR(cc, PREC_RIGHT, maxl); if(check_flag((void *)LS, "SUNLinSol_SPGMR", 0)) return(1); /* Attach the linear solver to KINSOL */ flag = KINSetLinearSolver(kmem, LS, NULL); if (check_flag(&flag, "KINSetLinearSolver", 1)) return 1; /* Set the maximum number of restarts */ maxlrst = 2; flag = SUNLinSol_SPGMRSetMaxRestarts(LS, maxlrst); if (check_flag(&flag, "SUNLinSol_SPGMRSetMaxRestarts", 1)) return(1); /* Specify the preconditioner setup and solve routines */ flag = KINSetPreconditioner(kmem, PrecSetupBD, PrecSolveBD); if (check_flag(&flag, "KINSetPreconditioner", 1)) return(1); /* Print out the problem size, solution parameters, initial guess. */ PrintHeader(globalstrategy, maxl, maxlrst, fnormtol, scsteptol); /* Call KINSol and print output concentration profile */ flag = KINSol(kmem, /* KINSol memory block */ cc, /* initial guess on input; solution vector */ globalstrategy, /* global strategy choice */ sc, /* scaling vector for the variable cc */ sc); /* scaling vector for function values fval */ if (check_flag(&flag, "KINSol", 1)) return(1); printf("\n\nComputed equilibrium species concentrations:\n"); PrintOutput(cc); /* Print final statistics and free memory */ PrintFinalStats(kmem); printf("num_threads = %i\n", num_threads); N_VDestroy_OpenMP(cc); N_VDestroy_OpenMP(sc); KINFree(&kmem); SUNLinSolFree(LS); FreeUserData(data); return(0); } /* Readability definitions used in other routines below */ #define acoef (data->acoef) #define bcoef (data->bcoef) #define cox (data->cox) #define coy (data->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY KINSOL *-------------------------------------------------------------------- */ /* * System function for predator-prey system */ static int func(N_Vector cc, N_Vector fval, void *user_data) { realtype xx, yy, delx, dely, *cxy, *rxy, *fxy, dcyli, dcyui, dcxli, dcxri; sunindextype jx, jy, is, idyu, idyl, idxr, idxl; UserData data; data = (UserData)user_data; delx = data->dx; dely = data->dy; /* Loop over all mesh points, evaluating rate array at each point*/ for (jy = 0; jy < MY; jy++) { yy = dely*jy; /* Set lower/upper index shifts, special at boundaries. */ idyl = (jy != 0 ) ? NSMX : -NSMX; idyu = (jy != MY-1) ? NSMX : -NSMX; for (jx = 0; jx < MX; jx++) { xx = delx*jx; /* Set left/right index shifts, special at boundaries. */ idxl = (jx != 0 ) ? NUM_SPECIES : -NUM_SPECIES; idxr = (jx != MX-1) ? NUM_SPECIES : -NUM_SPECIES; cxy = IJ_Vptr(cc,jx,jy); rxy = IJ_Vptr(data->rates,jx,jy); fxy = IJ_Vptr(fval,jx,jy); /* Get species interaction rate array at (xx,yy) */ WebRate(xx, yy, cxy, rxy, user_data); for(is = 0; is < NUM_SPECIES; is++) { /* Differencing in x direction */ dcyli = *(cxy+is) - *(cxy - idyl + is) ; dcyui = *(cxy + idyu + is) - *(cxy+is); /* Differencing in y direction */ dcxli = *(cxy+is) - *(cxy - idxl + is); dcxri = *(cxy + idxr +is) - *(cxy+is); /* Compute the total rate value at (xx,yy) */ fxy[is] = (coy)[is] * (dcyui - dcyli) + (cox)[is] * (dcxri - dcxli) + rxy[is]; } /* end of is loop */ } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner setup routine. Generate and preprocess P. */ static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data) { realtype r, r0, uround, sqruround, xx, yy, delx, dely, csave, fac; realtype *cxy, *scxy, **Pxy, *ratesxy, *Pxycol, perturb_rates[NUM_SPECIES]; sunindextype i, j, jx, jy, ret; UserData data; data = (UserData) user_data; delx = data->dx; dely = data->dy; uround = data->uround; sqruround = data->sqruround; fac = N_VWL2Norm(fval, fscale); r0 = THOUSAND * uround * fac * NEQ; if(r0 == ZERO) r0 = ONE; /* Loop over spatial points; get size NUM_SPECIES Jacobian block at each */ for (jy = 0; jy < MY; jy++) { yy = jy*dely; for (jx = 0; jx < MX; jx++) { xx = jx*delx; Pxy = (data->P)[jx][jy]; cxy = IJ_Vptr(cc,jx,jy); scxy= IJ_Vptr(cscale,jx,jy); ratesxy = IJ_Vptr((data->rates),jx,jy); /* Compute difference quotients of interaction rate fn. */ for (j = 0; j < NUM_SPECIES; j++) { csave = cxy[j]; /* Save the j,jx,jy element of cc */ r = SUNMAX(sqruround*SUNRabs(csave), r0/scxy[j]); cxy[j] += r; /* Perturb the j,jx,jy element of cc */ fac = ONE/r; WebRate(xx, yy, cxy, perturb_rates, data); /* Restore j,jx,jy element of cc */ cxy[j] = csave; /* Load the j-th column of difference quotients */ Pxycol = Pxy[j]; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) Pxycol[i] = (perturb_rates[i] - ratesxy[i]) * fac; } /* end of j loop */ /* Do LU decomposition of size NUM_SPECIES preconditioner block */ ret = denseGETRF(Pxy, NUM_SPECIES, NUM_SPECIES, (data->pivot)[jx][jy]); if (ret != 0) return(1); } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner solve routine */ static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data) { realtype **Pxy, *vxy; sunindextype *piv, jx, jy; UserData data; data = (UserData)user_data; #pragma omp parallel for collapse(2) default(shared) private(jx, jy, Pxy, piv, vxy) schedule(static) for (jx=0; jx<MX; jx++) { for (jy=0; jy<MY; jy++) { /* For each (jx,jy), solve a linear system of size NUM_SPECIES. vxy is the address of the corresponding portion of the vector vv; Pxy is the address of the corresponding block of the matrix P; piv is the address of the corresponding block of the array pivot. */ vxy = IJ_Vptr(vv,jx,jy); Pxy = (data->P)[jx][jy]; piv = (data->pivot)[jx][jy]; denseGETRS(Pxy, NUM_SPECIES, piv, vxy); } /* end of jy loop */ } /* end of jx loop */ return(0); } /* * Interaction rate function routine */ static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data) { sunindextype i; realtype fac; UserData data; data = (UserData)user_data; for (i = 0; i<NUM_SPECIES; i++) ratesxy[i] = DotProd(NUM_SPECIES, cxy, acoef[i]); fac = ONE + ALPHA * xx * yy; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) ratesxy[i] = cxy[i] * ( bcoef[i] * fac + ratesxy[i] ); } /* * Dot product routine for realtype arrays */ static realtype DotProd(sunindextype size, realtype *x1, realtype *x2) { sunindextype i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * Allocate memory for data structure of type UserData */ static UserData AllocUserData(void) { int jx, jy; UserData data; data = (UserData) malloc(sizeof *data); for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { (data->P)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES); (data->pivot)[jx][jy] = newIndexArray(NUM_SPECIES); } } acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES); bcoef = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); cox = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); coy = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); return(data); } /* * Load problem constants in data */ static void InitUserData(UserData data) { sunindextype i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; data->mx = MX; data->my = MY; data->ns = NUM_SPECIES; data->np = NUM_SPECIES/2; data->ax = AX; data->ay = AY; data->dx = (data->ax)/(MX-1); data->dy = (data->ay)/(MY-1); data->uround = UNIT_ROUNDOFF; data->sqruround = SUNRsqrt(data->uround); /* Set up the coefficients a and b plus others found in the equations */ np = data->np; dx2=(data->dx)*(data->dx); dy2=(data->dy)*(data->dy); for (i = 0; i < np; i++) { a1= &(acoef[i][np]); a2= &(acoef[i+np][0]); a3= &(acoef[i][0]); a4= &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* and then change the diagonal elements of acoef to -AA */ acoef[i][i]=-AA; acoef[i+np][i+np] = -AA; bcoef[i] = BB; bcoef[i+np] = -BB; cox[i]=DPREY/dx2; cox[i+np]=DPRED/dx2; coy[i]=DPREY/dy2; coy[i+np]=DPRED/dy2; } } /* * Free data memory */ static void FreeUserData(UserData data) { int jx, jy; for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { destroyMat((data->P)[jx][jy]); destroyArray((data->pivot)[jx][jy]); } } destroyMat(acoef); free(bcoef); free(cox); free(coy); N_VDestroy_OpenMP(data->rates); free(data); } /* * Set initial conditions in cc */ static void SetInitialProfiles(N_Vector cc, N_Vector sc) { int i, jx, jy; realtype *cloc, *sloc; realtype ctemp[NUM_SPECIES], stemp[NUM_SPECIES]; /* Initialize arrays ctemp and stemp used in the loading process */ for (i = 0; i < NUM_SPECIES/2; i++) { ctemp[i] = PREYIN; stemp[i] = ONE; } for (i = NUM_SPECIES/2; i < NUM_SPECIES; i++) { ctemp[i] = PREDIN; stemp[i] = RCONST(0.00001); } /* Load initial profiles into cc and sc vector from ctemp and stemp. */ for (jy = 0; jy < MY; jy++) { for (jx = 0; jx < MX; jx++) { cloc = IJ_Vptr(cc,jx,jy); sloc = IJ_Vptr(sc,jx,jy); for (i = 0; i < NUM_SPECIES; i++) { cloc[i] = ctemp[i]; sloc[i] = stemp[i]; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol) { printf("\nPredator-prey test problem -- KINSol (OpenMP version)\n\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Number of species = %d\n", NUM_SPECIES); printf("Total system size = %d\n\n", NEQ); printf("Flag globalstrategy = %d (0 = None, 1 = Linesearch)\n", globalstrategy); printf("Linear solver is SPGMR with maxl = %d, maxlrst = %d\n", maxl, maxlrst); printf("Preconditioning uses interaction-only block-diagonal matrix\n"); printf("Positivity constraints imposed on all components \n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: fnormtol = %Lg scsteptol = %Lg\n", fnormtol, scsteptol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #else printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #endif printf("\nInitial profile of concentration\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At all mesh points: %Lg %Lg %Lg %Lg %Lg %Lg\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #else printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #endif } /* * Print sampled values of current cc */ static void PrintOutput(N_Vector cc) { int is, jx, jy; realtype *ct; jy = 0; jx = 0; ct = IJ_Vptr(cc,jx,jy); printf("\nAt bottom left:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++){ if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } jy = MY-1; jx = MX-1; ct = IJ_Vptr(cc,jx,jy); printf("\n\nAt top right:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++) { if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } printf("\n\n"); } /* * Print final statistics contained in iopt */ static void PrintFinalStats(void *kmem) { long int nni, nfe, nli, npe, nps, ncfl, nfeSG; int flag; flag = KINGetNumNonlinSolvIters(kmem, &nni); check_flag(&flag, "KINGetNumNonlinSolvIters", 1); flag = KINGetNumFuncEvals(kmem, &nfe); check_flag(&flag, "KINGetNumFuncEvals", 1); flag = KINGetNumLinIters(kmem, &nli); check_flag(&flag, "KINGetNumLinIters", 1); flag = KINGetNumPrecEvals(kmem, &npe); check_flag(&flag, "KINGetNumPrecEvals", 1); flag = KINGetNumPrecSolves(kmem, &nps); check_flag(&flag, "KINGetNumPrecSolves", 1); flag = KINGetNumLinConvFails(kmem, &ncfl); check_flag(&flag, "KINGetNumLinConvFails", 1); flag = KINGetNumLinFuncEvals(kmem, &nfeSG); check_flag(&flag, "KINGetNumLinFuncEvals", 1); printf("Final Statistics.. \n"); printf("nni = %5ld nli = %5ld\n", nni, nli); printf("nfe = %5ld nfeSG = %5ld\n", nfe, nfeSG); printf("nps = %5ld npe = %5ld ncfl = %5ld\n", nps, npe, ncfl); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns a flag so check if * flag >= 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return(1); } } /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
gausstm.c
/* ADD & SOLVE MATRIX BY ECONOMICAL FRONTAL GAUSS METHOD */ int gausmat3(int am, long int mcmax, long int mcmin) /* wn[] - line koef numbers */ /* wi[] - line koef values */ /* am - mode of action rm=1,2,3 - add, rm=0 - solve */ /* val0[] - matrix contents */ /* lin0[] - line numbers for matrix contents */ /* pos0[] - first pos numbers for line in val0[], lin0[] */ /* num0[] - pos numbers for line in val0[], lin0[] */ /* fre0[] - free member for lines */ /* pos0cur - first free position number in val0[], lin0[] */ /* mcmax - current line in num0[] */ /* mcmin - first line in num0[] */ { /* Counters */ long int m1,m2,m3,nempty; /* Limits */ long int linbeg,linend; /* Val Buffer */ double ival; /**/ /* Space Check */ if (mcmax>=MAXPAR) { fprintf(fp_log,"EXIT PROGRAM: Space out in fre0[] %ld",mcmax); fflush(fp_log); exit(0); } /**/ /**/ /**/ /* STEP 1: EXEED KOEF ELIMINATION MATRIX BODY FORMATION am>0 */ if (am>0) { /* fprintf(fp_log,"\n GAUS %ld %ld %ld %ld %e ",am,mcmax,pos0cur,wn[0],wi[0]); getchar(); */ /* First, Last line numbers */ linbeg=wn[1]; linend=wn[wn[0]]; /**/ /* Free member reload from buffer */ fre0[mcmax]=wi[0]; /**/ /* Line koef reload from buffer */ for (m2=1;m2<=wn[0];m2++) { bufv[wn[m2]]+=wi[m2]; /**/ /* First, Last line numbers */ if(wi[m2]) { if (linbeg>wn[m2]) linbeg=wn[m2]; if (linend<wn[m2]) linend=wn[m2]; } /* fprintf(fp_log,"%ld %ld %e",m2,wn[m2],wi[m2]); getchar(); */ } /**/ /* Cur line koef recalc in buffer */ for (m2=linbeg;m2<mcmax;m2++) { if(bufv[m2]) { ival=bufv[m2]; bufv[m2]=0; /* Check Presence of line */ if (!num0[m2]) { fprintf(fp_log,"EXIT PROGRAM: Line %ld absent in matrix when processing Line %ld",m2,mcmax); fflush(fp_log); exit(0); } /* Current Line koef recalc after cur koef and upper line */ /* 1-st coef of any upper line = 1 */ for (m3=1;m3<num0[m2];m3++) { bufv[lin0[pos0[m2]+m3]]-=ival*val0[pos0[m2]+m3]; } /**/ /* Free member recalc after cur koef upper line av=0,1,2 */ fre0[mcmax]-=fre0[m2]*ival; /* Check last line number */ linend=MAXV(linend,lin0[pos0[m2]+num0[m2]-1]); /**/ } } /**/ /* Cur line save in val0[],lin0[],num0[],pos0[] */ /* Check Singularity */ /* Check Presence of line */ if (!bufv[mcmax]) { fprintf(fp_log,"EXIT PROGRAM: Matrix is singular at Line %ld",mcmax); fflush(fp_log); exit(0); } pos0[mcmax]=pos0cur; num0[mcmax]=0; ival=bufv[mcmax]; for (m2=mcmax;m2<=linend;m2++) { /**/ /* Recalc and Save Val>0 */ if (bufv[m2]) { /* Save Cur Koef */ lin0[pos0cur]=m2; val0[pos0cur]=bufv[m2]/ival; /* fprintf(fp_log,"%ld %ld %ld %ld %e ",mcmax,pos0cur,m2,num0[pos0cur],val0[pos0cur]); getchar(); */ pos0cur++; /* Check Space */ if (pos0cur>=MAXMAT) { fprintf(fp_log,"EXIT PROGRAM: Space out in val0[] %ld %ld",mcmax,pos0cur); fflush(fp_log); exit(0); } num0[mcmax]++; } /* Clear Cur Koef */ bufv[m2]=0; } /* Free member recalc */ fre0[mcmax]/=ival; return 0; } /* End STEP 1: EXEED KOEF ELIMINATION MATRIX BODY FORMATION am>0 */ /**/ /**/ /**/ /* STEP 3: SOLUTION CALC CHECK am=0 */ nempty=0; fprintf(fp_log,"TOTAL BAND MATRIX SIZE: val0[%ld]\n",pos0cur); fflush(fp_log); /* */ for (m1=mcmax;m1>=mcmin;m1--) { /* Calc sol0[] */ if (num0[m1]) { /* Recalc koef after Sol */ ival=fre0[m1]; for (m2=0;m2<num0[m1];m2++) { ival-=val0[pos0[m1]+m2]*sol0[lin0[pos0[m1]+m2]]; } /* Calc Sol */ sol0[m1]=ival; } else { sol0[m1]=0; /* fprintf(fp_log,"%ld %ld %e ",m1,num0[m1],sol0[m1]); getchar(); */ nempty++; } /* fprintf(fp_log,"%ld %ld %e ",m1,num0[m1],sol0[m1]); getchar(); */ } /* End STEP 3: SOLUTION CALC CHECK am=0 */ /* fprintf(fp_log,"%ld %ld %ld %e",nempty,pos0cur,mcmax,(double)(pos0cur+1)/(double)(mcmax+1)); getchar(); */ return nempty; } /* End SOLVE MATRIX BY ECONOMICAL GAUSS METHOD */ /* ADD/SOLVE PARDISO MATRIX */ int gausmat4(int am, long int mcmax, long int mcmin) /* wn[] - line koef numbers */ /* wi[] - line koef values */ /* am - mode of action rm=1,2,3 - add, rm=0 - solve */ /* ia[] - first coloumn of each row */ /* ja[] - coloumn position of each koef in the respective row from left to right */ /* a[] - value of each koef */ /* b[] - Right hand side */ /* bufv[] - koefficient values buffer */ /* cur0[] - koefficient use y/n */ { /* Counters */ long int m1,m2,m3,leftnum,rightnum; int i; /* Val Buffer */ double ival; int n_th; /* Space Check */ if (mcmax>=MAXPAR) { fprintf(fp_log,"EXIT PROGRAM: Space out in fre0[] %ld",mcmax); fflush(fp_log); exit(0); } /* Solve Matrix ===================================================== */ if (am==0) { /* Solve Matrix with PARDISO */ /* Matrix data. */ /*Calling function making arrays */ int na=mcmax; /**/ int mtype = 11; /* Real unsymmetric matrix */ /* RHS and solution vectors. */ int nrhs = 1; /* Number of right hand sides. */ /* Internal solver memory pointer pt, */ /* 32-bit: int pt[64]; 64-bit: long int pt[64] */ /* or void *pt[64] should be OK on both architectures */ void *pt[64]; /* Pardiso control parameters. */ int iparm[64]; int maxfct, mnum, phase, error, msglvl; /* Auxiliary variables. */ double ddum; /* Double dummy */ int idum; /* Integer dummy. */ double start=omp_get_wtime(); #pragma omp parallel shared(n_th) { n_th = omp_get_num_threads(); } fprintf(fp_log,"PARDISO on %d Threads\n",n_th); fflush(fp_log); /* -------------------------------------------------------------------- */ /* .. Setup Pardiso control parameters. */ /* -------------------------------------------------------------------- */ // Note that most documentation you see refers to Fortran numbering, which is 1 number higher than in C as C also fills the 0 slot for (i = 0; i < 64; i++) { iparm[i] = 0; } iparm[0] = 1; /* No solver default! All default overwritten by this! QUESTION TARAS: WHY?*/ /* Fill-in reduction reordering for input matrix: 0 = default in series = minimum degree compaction, 2: nested dissection algorithm from METIS, 3 = supposed parallel default */ if (metis_reorder==1) {iparm[1] = 3;} // For first 10 output frames, use METIS=0, to make sure that runs more stable after (re)start else {iparm[1] = 0;} iparm[2] = n_th; /* Numbers of processors, value of OMP_NUM_THREADS */ iparm[3] = 0; /* Preconditioned CGS/CG: No iterative-direct algorithm */ iparm[4] = 0; /* No user fill-in reducing permutation */ iparm[5] = 0; /* Write solution into x */ iparm[6] = 0; /* Output: Number of performed iterative refinement steps */ iparm[7] = 20; /* Max numbers of iterative refinement steps */ iparm[8] = 0; /* Not in use */ iparm[9] = 13; /* Perturb the pivot elements with 1E-13 */ iparm[10] = 1; /* Use nonsymmetric permutation and scaling MPS */ iparm[11] = 0; /* Not in use */ iparm[12] = 0; /* Not in use */ iparm[13] = 0; /* Output: Number of perturbed pivots */ iparm[14] = 0; /* Not in use */ iparm[15] = 0; /* Not in use */ iparm[16] = 0; /* Not in use */ iparm[17] = -1; /* Output: Number of nonzeros in the factor LU */ iparm[18] = -1; /* Output: Mflops for LU factorization */ iparm[19] = 0; /* Output: Numbers of CG Iterations */ iparm[24] = 1; // Backward/forward solve: sequential (0) or parallel (1) maxfct = 1; /* Maximum number of numerical factorizations. */ mnum = 1; /* Which factorization to use; vary to see if helps for seg fault? */ msglvl = 0; /* Print statistical information in file */ error = 0; /* Initialize error flag */ /* -------------------------------------------------------------------- */ /* .. Initialize the internal solver memory pointer. This is only */ /* necessary for the FIRST call of the PARDISO solver. */ /* -------------------------------------------------------------------- */ for (i = 0; i < 64; i++) { pt[i] = 0; } /* -------------------------------------------------------------------- */ /* .. Reordering and Symbolic Factorization. This step also allocates */ /* all memory that is necessary for the factorization. */ /* -------------------------------------------------------------------- */ phase = 11; PARDISO (pt, &maxfct, &mnum, &mtype, &phase, &na, a, ia, ja, &idum, &nrhs, iparm, &msglvl, &ddum, &ddum, &error); if (error != 0) { fprintf(fp_log,"\nPARDISO ERROR during reordering and symbolic factorization: %d", error); fflush(fp_log); exit(1); } fprintf(fp_log,"\nReordering completed ... "); fflush(fp_log); fprintf(fp_log,"\nNumber of nonzeros in factors = %d", iparm[17]); fprintf(fp_log,"\nNumber of factorization MFLOPS = %d", iparm[18]); fflush(fp_log); /* -------------------------------------------------------------------- */ /* .. Numerical factorization.. */ /* -------------------------------------------------------------------- */ phase = 22; PARDISO (pt, &maxfct, &mnum, &mtype, &phase, &na, a, ia, ja, &idum, &nrhs, iparm, &msglvl, &ddum, &ddum, &error); if (error != 0) { fprintf(fp_log,"\nPARDISO ERROR during numerical factorization: %d", error); fflush(fp_log); exit(2); } fprintf(fp_log,"\nFactorization completed ... "); fflush(fp_log); /* -------------------------------------------------------------------- */ /* .. Forward and Backward solve including iterative refinement .. */ /* -------------------------------------------------------------------- */ phase = 33; iparm[7] = 40; /* Max numbers of iterative refinement steps. */ PARDISO (pt, &maxfct, &mnum, &mtype, &phase, &na, a, ia, ja, &idum, &nrhs, iparm, &msglvl, b, x, &error); if (error != 0) { fprintf(fp_log,"\nPARDISO ERROR during solution (back substitution and iterative refinement): %d", error); fflush(fp_log); exit(3); } fprintf(fp_log,"\nSolve completed ... "); fflush(fp_log); /* -------------------------------------------------------------------- */ /* .. Termination and release of memory. */ /* -------------------------------------------------------------------- */ phase = -1; /* Release internal memory. */ PARDISO (pt, &maxfct, &mnum, &mtype, &phase, &na, &ddum, ia, ja, &idum, &nrhs, iparm, &msglvl, &ddum, &ddum, &error); if (printmod) fprintf(fp_log,"PARDISO SOLVER OK!\n"); fflush(fp_log); //fprintf(fp_log,"Time taken for solving = %e s on %d threads \n",omp_get_wtime()-start,n_th); return 0; } /* End Solve Matrix ===================================================== */ /* STEP 0: RELOAD KOEF FROM wi[] to val0[] */ /* Reset coefficients */ for (m2=1;m2<=wn[0];m2++) { /* wi[]>0 */ if (wi[m2]) { bufv[wn[m2]]=0.0; cur0[wn[m2]]=1; } } leftnum=nodenum3+1; rightnum=-1; /* Sum up coefficients */ for (m2=1;m2<=wn[0];m2++) { /* wi[]>0 */ if (wi[m2]) { /* Check left/right band width */ m3=wn[m2]; leftnum=MINV(leftnum,m3); rightnum=MAXV(rightnum,m3); /* Add coefficient */ bufv[wn[m2]]+=wi[m2]; } } /* Free member reload from buffer */ b[mcmax]=wi[0]; /* Line koef reload to a[] from buffer */ ia[mcmax]=pos0cur+1; ia[mcmax+1]=pos0cur+1; for (m2=leftnum;m2<=rightnum;m2++) { /* fprintf(fp_log,"\n GAUS %ld %ld %d %e %ld %ld %e %d %d\n",leftnum,rightnum,wn[0],wi[0],m2,pos0cur,val1[1],lin0[1],num0[mcmax]); */ /* Marked Line */ if(cur0[m2]==1) { /* wi[]>0 */ if (bufv[m2]) { /* Save Cur Koef */ ja[pos0cur]=m2+1; a[pos0cur]=bufv[m2]; pos0cur++; /* Check Space */ if (pos0cur>=MAXVAL) { fprintf(fp_log,"EXIT PROGRAM: Space out in a[] %ld %ld",mcmax,pos0cur); fflush(fp_log); exit(0); } ia[mcmax+1]++; } /* Clean marked line */ bufv[m2]=0.0; cur0[m2]=0; } } return 0; } /* End ADD PARDISO MATRIX */
sumaOMP.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> int suma(int a,int b); int main(int argc, char *argv[]){ int numeroDeHilos=strtol(argv[1],NULL,10); int resultado=0; int a=10, b=20; #pragma omp parallel num_threads(numeroDeHilos) { int mi_resultado=0; mi_resultado=suma(a,b); #pragma omp critical resultado+=mi_resultado; } printf("El resultado de la operación es %d\n", resultado); return 0; } int suma(int a, int b){ int my_rank=omp_get_thread_num(); int numeroDeHilos=omp_get_num_threads(); int mi_suma=a+b; printf("Suma del hilo %d de %d: %d\n",my_rank, numeroDeHilos, mi_suma); return mi_suma; }
first_implementation.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <string.h> #define BUFF_SIZE 50 #define MAXSIZE 100 #define MAXLINE 50 #define N_EXEC 100 //number of parallel executed k_means algorithms #define N_FOLD 10 //number of folds for cross validation #define K_MAX 10 //max number of cluster #define CHUNKSIZE 10 #define IMPL 1 char FILEPATH[] = "../data/breastcancer1.csv"; int k = 2; // initial value of clusters struct data { int dim; int atts; float** data; }; //structure that contains all SSE and centroids computed struct history { float SSE; float** centroids; }; float calcSilhouette(float** dataset, int **clusters, float** centroids, int n, int m); struct data loadDataset(char* fileName, char* dist); void normalize(struct data* dataset); void datasetSubSets(struct data dataset, int fold, struct data* trainingSet, struct data* testSet); float mainAlgo(struct data training, struct data test, int flagFinal); void kmeans (struct data structure, int numIte, float tol, struct history* recordStoria); void copySubMatrix(float** centroids, float** dataset, int *ranNum, int m); void randomIndexes(int *ranNum, int n); void zeroClusters(int **clusters, int n); void findClusters(float** dataset, int **clusters, float** centroids, int n, int m); float calcSSE(float** dataset, int **clusters, float** centroids, int n, int m); void freeArray(float **a, int n); void copyMatrix(float **mat1, float **mat2, int row, int col); void printData(struct data dataset); void getRow(float **matrix, int row, float *array, int m); float eucliDist(float *rec1, float *rec2, int m); void findCentroids(float** centroids, int **clusters, float** dataset, int n, int m); void printClusters(int **clusters, int n); void printCentroids(float** centroids, int m); void writeFile(float** data, int **clusters, int n, int m); void freeArrayInt(int **a, int n); ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// int main (int argc, char *argv[]) { strcpy(FILEPATH,argv[1]); char file[30] = "../data/"; strcat(file,argv[1]); strcat(file,".csv"); double begin = omp_get_wtime(); double end; struct data dataset = loadDataset(file, "\t"); normalize(&dataset); printf("DIM: %d\n", dataset.dim); struct data trainingSet; struct data testSet; int bestk=2; float sumSil[ K_MAX-1 ], appSSE, appSIL, SIL[ K_MAX-1 ]; for(k = 2; k<=K_MAX; k++) { printf("\nAnalizing for k = %d", k); sumSil[k-2] = 0; //N_FOLD-fold cross validation for(int fold=0; fold<N_FOLD; fold++) { trainingSet.data = (float**) calloc (dataset.dim - (dataset.dim / N_FOLD), sizeof(float*)); testSet.data = (float**) calloc (dataset.dim / N_FOLD, sizeof(float*)); datasetSubSets(dataset, fold, &trainingSet, &testSet); sumSil[k-2] +=mainAlgo(trainingSet, testSet, 0); if(fold<N_FOLD-1){ freeArray(trainingSet.data, trainingSet.dim); freeArray(testSet.data, testSet.dim); } } sumSil[k-2] = sumSil[k-2]/N_FOLD; //AIC[k-2] = 2*k + log10(sumSil[k-2]/testSet.dim); //Akaike criterion result printf("\nSilhouette: %f",sumSil[k-2]); //printf("\nAIC: %f, altro: %f", AIC[k-2], testSet.dim*log10(sumSil[k-2]/testSet.dim)); if(k==2) appSIL = sumSil[k-2]; if(sumSil[k-2] > appSIL) { bestk = k; appSIL = sumSil[k-2]; } freeArray(trainingSet.data, trainingSet.dim); freeArray(testSet.data, testSet.dim); end = omp_get_wtime(); double time_spent = (end - begin); printf("\nTime from start: %lf sec \n------------------------", time_spent); } printf("\n best k is: %d with Silhuette: %f", bestk, appSIL); // Setting the number of clusters to the best one chosen before as a result of AIC compare k = bestk; mainAlgo(dataset, dataset, 1); end = omp_get_wtime(); FILE* fd; fd = fopen("tempi.txt", "a"); fprintf(fd,"\n%lf sec\t%d\t%s\t%d",(end - begin), omp_get_num_threads(), FILEPATH, IMPL); printf("\nk_max= %d, Total time: %lf sec\n",K_MAX,(end - begin)); } //main algorithm //flag is =1 only when final iteration is computed (in order to write out the results) float mainAlgo(struct data training, struct data test, int flagFinal) { struct history bestStoria; float supportSSE; int** bestClusters =(int**) calloc(test.dim, sizeof(int*)); bestStoria.centroids = (float**) malloc(k * sizeof(float*)); for(int i=0; i<test.dim; i++) bestClusters[i] =(int*) calloc(k, sizeof(int)); for(int i=0; i<k; i++) bestStoria.centroids[i] =(float*) malloc(training.atts *sizeof(float)); bestStoria.SSE = training.atts * training.dim; struct history storia; storia.centroids = (float**) calloc(k, sizeof(float*)); for(int i=0; i<k; i++) { storia.centroids[i] =(float*) calloc(training.atts, sizeof(float)); } srand( time(NULL) ); for(int i=0; i<N_EXEC; i++) { kmeans(training, 5000, 0.001, &storia); if(storia.SSE <= bestStoria.SSE) { copyMatrix(bestStoria.centroids, storia.centroids, k, training.atts); bestStoria.SSE = storia.SSE; } } zeroClusters(bestClusters, test.dim); //reset best clusters matrix findClusters(test.data, bestClusters, bestStoria.centroids, test.dim, test.atts); //print last iteration results if(flagFinal == 1) { printCentroids(bestStoria.centroids, test.atts); writeFile(test.data, bestClusters, test.dim, test.atts); } float SSEtrovato = calcSSE(test.data, bestClusters, bestStoria.centroids, test.dim, test.atts); float silTrovata = calcSilhouette(test.data, bestClusters, bestStoria.centroids, test.dim, test.atts); //printf("\nthread: %d", omp_get_thread_num()); freeArray(bestStoria.centroids, k); freeArray(storia.centroids, k); freeArrayInt(bestClusters, test.dim); return silTrovata; } void kmeans (struct data structure, int numIte, float tol, struct history* recordStoria) { int n, m, *ranNum; n = structure.dim; m = structure.atts; ranNum = (int*) calloc(k, sizeof(int)); //generate k random indexes to start from randomIndexes(ranNum, n); float** centroids = (float**) calloc(k, sizeof(float*)); int** clusters =(int**) calloc(n, sizeof(int*)); for(int i=0; i<n; i++) { clusters[i] =(int*) calloc(k, sizeof(int)); } for(int i=0; i<k; i++) { centroids[i] =(float*) calloc(m, sizeof(float)); } //saving initial centroids copySubMatrix(centroids, structure.data, ranNum, m); /*saving indexes that corresponds to each of the k clusters. Results will be stored into a matrix which columns are the cluster number and the rows corresponds to the indexes of records */ zeroClusters(clusters, n); //pongo a 0 tutti gli elementi del cluster findClusters(structure.data, clusters, centroids, n, m); int count = 0; float newSSE, currSSE; float** supCentroids = (float**) calloc(k, sizeof(float*)); for(int j = 0; j < k; j++) supCentroids[j] = (float*) calloc(m, sizeof(float)); do { currSSE = calcSSE(structure.data, clusters, centroids, n, m); copyMatrix(supCentroids, centroids, k, m); findCentroids(centroids, clusters, structure.data, n, m); zeroClusters(clusters, n); findClusters(structure.data,clusters,centroids, n, m); newSSE = calcSSE(structure.data, clusters, centroids, n, m); //sum of square errors calculation count++; } while(count < numIte && ((currSSE-newSSE)/currSSE) > tol); if(newSSE > currSSE) { copyMatrix(centroids, supCentroids, k, m); newSSE = currSSE; } copyMatrix(recordStoria->centroids, centroids, k, m); recordStoria->SSE = newSSE; freeArray(centroids,k); freeArrayInt(clusters,n); freeArray(supCentroids,k); free(ranNum); } void printData(struct data dataset) { printf("\n"); for(int i = 0; i < dataset.dim; i++) { printf("%d\t", i + 1); for(int j = 0; j < dataset.atts; j++) { printf("%.2f\t", dataset.data[i][j]); } printf("\n"); } } float calcSilhouette(float** dataset, int **clusters, float** centroids, int n, int m){ float sum=0.0, supDataset[m], supCentroid[m], avgi[k], avge[k], minAvge = 10, a, b, max = 0, sil, meansil = 0; int trovato = 0; int ci = 0; for(int ki=0; ki<k; ki++){ getRow(centroids, ki, supCentroid, m); avgi[ki] = 0; max = 0; for(int i=0;i<n;i++){ getRow(dataset, i, supDataset, m); ci += clusters[i][ki]; avgi[ki] += eucliDist(supCentroid, supDataset, m) * clusters[i][ki]; if(trovato==0) avge[ki] += eucliDist(supCentroid, supDataset, m) * (1 - clusters[i][ki]); if(clusters[i][ki]==0) trovato = 1; if(clusters[i][ki] == 0 && minAvge > eucliDist(supCentroid, supDataset, m)) minAvge = eucliDist(supCentroid, supDataset, m); } if(ci!=0) avgi[ki] = avgi[ki] / ci; trovato = 0; ci=0; } float lowestAvge = minAvge, avgiMean=0; for(int ki=0;ki<k;ki++){ if(lowestAvge>=avgi[ki]){ max = lowestAvge; sil = 1-(avgi[ki]/lowestAvge); } else{ max = avgi[ki]; sil = (lowestAvge/avgi[ki])-1; } meansil += sil; } meansil = meansil / k; return meansil; } void normalize(struct data* dataset) { int i, j; printf("Normalizing the data\n"); float max[dataset->atts]; // Look for max of each column for(i = 0; i < dataset->dim; i++) { for(j = 0; j < dataset->atts; j++) { if(i == 0) { max[j] = 0; } if(max[j] < dataset->data[i][j]) max[j] = dataset->data[i][j]; } } // Normalize the data by dividing each value by the max value of the column for(i = 0; i < dataset->dim; i++) { for(j = 0; j < dataset->atts; j++) { dataset->data[i][j] = dataset->data[i][j] / max[j]; } } } void datasetSubSets(struct data dataset, int fold, struct data* trainingSet, struct data* testSet) { int init, end, apptr = 0, appte=0; init = fold * (dataset.dim / N_FOLD); end = ((fold + 1) * (dataset.dim / N_FOLD)) - 1; trainingSet->dim = 0; trainingSet->atts = dataset.atts; testSet->dim = 0; testSet->atts = dataset.atts; for (int i = 0; i < dataset.dim; i++) { if(i >= init && i <= end) { testSet->data[appte] = (float*) calloc(dataset.atts, sizeof(float)); for(int u=0;u<dataset.atts;u++) testSet->data[appte][u] = dataset.data[i][u]; appte++; } else { trainingSet->data[apptr] = (float*) calloc(dataset.atts, sizeof(float)); for(int u=0; u<dataset.atts; u++) trainingSet->data[apptr][u] = dataset.data[i][u]; apptr++; } } testSet->dim = appte; trainingSet->dim = apptr; } struct data loadDataset(char* fileName, char* dist) { FILE *file; int max = MAXSIZE; float* app; float** data; struct data dataset; // Open file and check for I/O errors file = fopen(fileName, "r"); if (file == NULL) exit(-1); else printf("Loading from file: %s\n", fileName); char buffer[MAXLINE]; // Count the number of attributes if (fgets(buffer, sizeof(buffer), file)) { // Get the number of attributes sscanf(buffer, "%d", &dataset.atts); printf("atts: %d\n", dataset.atts); } // Read the actual data from the file dataset.dim = 0; // Read line by line until there are more in the file dataset.data = (float**) calloc (MAXSIZE, sizeof(float*)); while(fgets(buffer, sizeof(buffer), file)) { dataset.data[dataset.dim] = (float*) calloc(dataset.atts, sizeof(float)); // Take the first token in the current line of data char *headapp = strtok(buffer, dist); int i = 0; do { // Get the token and convert it to float dataset.data[dataset.dim][i] = atof(headapp); // Get the next token headapp = strtok(NULL, dist); i++; } while(headapp != NULL); dataset.dim++; if(dataset.dim > max) { max += MAXSIZE; dataset.data = (float**) realloc(dataset.data, sizeof(float) * dataset.atts * max); } } return dataset; } void freeArray(float **a, int n) { for (int i = 0; i < n; ++i) { free(a[i]); } free(a); } void freeArrayInt(int **a, int n) { for (int i = 0; i < n; ++i) { free(a[i]); } free(a); } void copyMatrix(float **mat1, float **mat2, int row, int col){ //mat1 dest, mat2 source // I/O operazioni non richiedono molto lavoro da parte della CPU, ma piuttosto dalla memoria for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { mat1[i][j] = mat2[i][j]; } } } //copy datasets records that corrensponds to centroids void copySubMatrix(float **centroids, float** dataset, int *ranNum, int m) { for(int i=0; i<k; i++) { for(int j=0; j<m; j++) centroids[i][j] = dataset[ ranNum[i] ][j]; } } float calcSSE(float** dataset, int **clusters, float** centroids, int n, int m){ float sum=0.0, supDataset[m], supCentroid[m]; for(int ki=0; ki<k; ki++){ getRow(centroids, ki, supCentroid, m); #pragma omp parallel for private(supDataset) reduction(+:sum) for(int i=0;i<n;i++){ getRow(dataset, i, supDataset, m); sum += eucliDist(supCentroid, supDataset, m) * clusters[i][ki]; } } return sum; } void printClusters(int **clusters, int n){ printf("\t\t"); for(int ki=0;ki<k;ki++){ printf("k%d\t",ki); } for(int i=0;i<n;i++){ printf("\nrecord%d:\t",i); for(int j=0;j<k;j++){ printf("%d\t",clusters[i][j]); } } printf("\n"); } void findCentroids(float** centroids, int **clusters, float** dataset, int n, int m) { int elemCluster=0; float record[m]; //reset array for(int ki=0; ki<k; ki++) { for(int p=0; p<m; p++) { record[p] = 0; } for(int i=0; i<n; i++) { if(clusters[i][ki]!=0) { elemCluster++; for(int j=0; j<m; j++) record[j] += dataset[i][j]; } } #pragma omp parallel for for(int p=0; p<m; p++) { if(elemCluster!=0) record[p] = record[p]/elemCluster; else record[p]=0; centroids[ki][p] = record[p]; } elemCluster = 0; } } void printCentroids(float** centroids, int m) { int p, i; for(i = 0; i < k; i++) { printf("\ncentroide cluster %d esimo: ",i); for(p=0;p<m;p++){ printf("%.2f,",centroids[i][p]); } printf("\n"); } } void zeroClusters(int **clusters, int n){ for(int i=0;i<n;i++){ for(int j=0;j<k;j++){ clusters[i][j] = 0; } } } //it assigns each dataset record to the nearest centroid, which corrensponds to its cluster void findClusters(float** dataset, int **clusters, float **centroids, int n, int m){ int salvaK=0; float supCentroid[m], supDataset[m], dist=0, lowerDist; #pragma omp parallel for private(lowerDist, dist, salvaK, supCentroid, supDataset) for(int i=0;i<n;i++){ for(int ki=0;ki<k;ki++){ // lowerDist = m because data is normalized, so the max dist between 2 records is the number of attributes if (ki == 0) lowerDist = m; getRow(centroids, ki, supCentroid, m); //extract a row from the centroid matrix getRow(dataset, i, supDataset, m); //extract a row from the dataset matrix dist = eucliDist(supCentroid, supDataset, m); //computing the euclidean distance if(dist<=lowerDist) { lowerDist = dist; salvaK = ki; } if(ki == k - 1) clusters[i][salvaK] = 1; } } } void getRow(float **matrix, int row, float *array, int m){ for(int j = 0; j < m; j++){ array[j] = matrix[row][j]; } } /*function that generate k indexes, which will refer to k initial centroids*/ void randomIndexes(int *ranNum, int n){ int i; for(i=0;i<k;i++){ ranNum[i] = rand()%n; } } /*receive two records in input so it calculates euclidean distance, continuos data required */ float eucliDist(float *rec1, float *rec2, int m){ float sum = 0.0; for(int i=0;i<m;i++){ sum += ((rec1[i]-rec2[i]))*((rec1[i]-rec2[i])); } return sqrt(sum); } void writeFile(float** data ,int **clusters, int n, int m) { FILE* fd; char output[30] = "out/"; strcat(output,FILEPATH); strcat(output,".txt"); fd = fopen(output, "w"); //fd = fopen("out/output_breastcancer_2.txt", "w"); for(int i = 0; i < n; i++) { fprintf(fd, "%d", i); for(int j = 0; j < k; j++) { fprintf(fd, "\t%d", clusters[i][j]); } fprintf(fd,"\n"); } }
DMD5_fmt_plug.c
/* * DMD5_fmt.c * * DIGEST-MD5 authentication module for Solar Designer's John the Ripper * Uses Solar Designer's MD5 implementation. * * This software is Copyright 2006, regenrecht@o2.pl, and * Copyright 2011, 2013 magnum, and it is hereby released to the general * public under the following terms: Redistribution and use in source and * binary forms, with or without modification, are permitted. * * Input format: * $DIGEST-MD5$ username $ realm $ nonce $ digest_uri $ cnonce $ nc $ qop $ response [ $ authzid ] * * Just base64-decode the blob you see when sniffing, to get all data needed * for above. * * See https://tools.ietf.org/html/rfc2831 (Using Digest Authentication as a * SASL Mechanism) for algorithm details. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_DMD5; #elif FMT_REGISTERS_H john_register_one(&fmt_DMD5); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #endif #include "arch.h" #include "misc.h" #include "md5.h" #include "common.h" #include "formats.h" #include "memdbg.h" #define FORMAT_LABEL "dmd5" #define FORMAT_NAME "DIGEST-MD5 C/R" #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define FORMAT_TAG "$DIGEST-MD5$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MD5_HEX_SIZE (2 * BINARY_SIZE) #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #define DSIZE (128 - sizeof(int)) #define CIPHERTEXT_LENGTH (DSIZE * 4) #define PLAINTEXT_LENGTH 32 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static const char itoa16_shr_04[] = "0000000000000000" "1111111111111111" "2222222222222222" "3333333333333333" "4444444444444444" "5555555555555555" "6666666666666666" "7777777777777777" "8888888888888888" "9999999999999999" "aaaaaaaaaaaaaaaa" "bbbbbbbbbbbbbbbb" "cccccccccccccccc" "dddddddddddddddd" "eeeeeeeeeeeeeeee" "ffffffffffffffff"; static const char itoa16_and_0f[] = "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef" "0123456789abcdef"; static struct custom_salt { unsigned char login_id[DSIZE]; // username:realm unsigned int login_id_len; unsigned char nonces[DSIZE]; // :nonce:cnonce[:authzid] unsigned int nonces_len; unsigned char prehash_KD[DSIZE]; // :nonce:nc:cnonce:qop:hex_A2_hash unsigned int prehash_KD_len; } *cur_salt; static uint32_t (*crypt_key)[BINARY_SIZE/4]; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static struct fmt_tests tests[] = { {"$DIGEST-MD5$s3443$pjwstk$00$ldap/10.253.34.43$0734d94ad9abd5bd7fc5e7e77bcf49a8$00000001$auth-int$dd98347e6da3efd6c4ff2263a729ef77", "test"}, // Two hashes from https://tools.ietf.org/html/rfc2831#section-8 {"$DIGEST-MD5$chris$elwood.innosoft.com$OA6MG9tEQGm2hh$imap/elwood.innosoft.com$OA6MHXh6VqTrRk$00000001$auth$d388dad90d4bbd760a152321f2143af7", "secret"}, {"$DIGEST-MD5$chris$elwood.innosoft.com$OA9BSXrbuRhWay$acap/elwood.innosoft.com$OA9BSuZWMSpW8m$00000001$auth$6084c6db3fede7352c551284490fd0fc", "secret"}, {NULL} }; static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, PLAINTEXT_LENGTH + 1); crypt_key = mem_calloc(self->params.max_keys_per_crypt, BINARY_SIZE); } static void done(void) { MEM_FREE(crypt_key); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *data = ciphertext + FORMAT_TAG_LEN; int extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; if (strlen(ciphertext) > CIPHERTEXT_LENGTH) return 0; if (!(p = strchr(data, '$')) || (int)(p-data) >= 64) // username return 0; data = p + 1; // realm if (!(p = strchr(data, '$')) || (int)(p-data) >= 64) return 0; data = p + 1; // nonce if (!(p = strchr(data, '$')) || (int)(p-data) >= 64) return 0; data = p + 1; // digest_uri if (!(p = strchr(data, '$')) || (int)(p-data) >= DSIZE) return 0; data = p + 1; // cnonce if (!(p = strchr(data, '$')) || (int)(p-data) > MD5_HEX_SIZE) return 0; /* if (hexlenl(data, 0) != p-data) // this is not always hex data! return 0; */ data = p + 1; // nc if (!(p = strchr(data, '$')) || (int)(p-data) >= 9) return 0; data = p + 1; // qop if (strncmp(data, "auth", 4) && strncmp(data, "auth-int", 8) && strncmp(data, "auth-conf", 9)) return 0; if (!(p = strchr(data, '$')) || (int)(p-data) >= 9) return 0; data = p + 1; // authzid, optional if ((p = strchr(data, '$'))) { if ((int)(p-data) > MD5_HEX_SIZE || strlen(&p[1]) >= 8) return 0; } else if (strlen(data) > MD5_HEX_SIZE) return 0; if (hexlenl(data, &extra) != MD5_HEX_SIZE || extra) return 0; return 1; } static void *get_binary(char *ciphertext) { static uint32_t out[BINARY_SIZE/4]; char response[MD5_HEX_SIZE + 1]; unsigned int i; char *p, *data = ciphertext + FORMAT_TAG_LEN; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); data = p + 1; p = strchr(data, '$'); if (p && (p - data + 1) < sizeof(response)) strnzcpy(response, data, p - data + 1); else strnzcpy(response, data, sizeof(response)); for (i = 0; i < BINARY_SIZE; ++i) ((unsigned char*)out)[i] = (atoi16[ARCH_INDEX(response[i*2])] << 4) + atoi16[ARCH_INDEX(response[i*2+1])]; return (void*)out; } static void *get_salt(char *ciphertext) { char username[64]; char realm[64]; char nonce[64]; char digest_uri[DSIZE]; char cnonce[MD5_HEX_SIZE + 1]; char nc[9]; char qop[9]; char authzid[8]; unsigned char *ptr_src, *ptr_dst, v, i; char *ccopy = strdup(ciphertext); char *p, *data = ccopy + FORMAT_TAG_LEN; MD5_CTX ctx; char A2[DSIZE]; unsigned char hash[BINARY_SIZE]; unsigned char hex_hash[2*MD5_HEX_SIZE]; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); if ((p = strchr(data, '$'))) *p = 0; strnzcpy(username, data, sizeof(username)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(realm, data, sizeof(realm)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(nonce, data, sizeof(nonce)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(digest_uri, data, sizeof(digest_uri)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(cnonce, data, sizeof(cnonce)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(nc, data, sizeof(nc)); data = p + 1; if ((p = strchr(data, '$'))) *p = 0; strnzcpy(qop, data, sizeof(qop)); data = p + 1; if ((p = strchr(data, '$'))) { *p = 0; data = p + 1; if (*data) strnzcpy(authzid, data, sizeof(authzid)); else *authzid = 0; } else { *authzid = 0; } if (!strcmp(qop, "auth")) snprintf((char*)A2, sizeof(A2), "AUTHENTICATE:%s", digest_uri); else if (!strcmp(qop, "auth-int") || !strcmp(qop, "auth-conf")) snprintf((char*)A2, sizeof(A2), "AUTHENTICATE:%s:00000000000000000000000000000000", digest_uri); MD5_Init(&ctx); MD5_Update(&ctx, A2, strlen((char*)A2)); MD5_Final(hash, &ctx); ptr_src = hash; ptr_dst = hex_hash; for (i = 0; i < BINARY_SIZE; ++i) { v = *ptr_src++; *ptr_dst++ = itoa16_shr_04[ARCH_INDEX(v)]; *ptr_dst++ = itoa16_and_0f[ARCH_INDEX(v)]; } *ptr_dst = 0; snprintf((char*)cs.prehash_KD, sizeof(cs.prehash_KD), ":%s:%s:%s:%s:%s", nonce, nc, cnonce, qop, hex_hash); cs.prehash_KD_len = strlen((char*)cs.prehash_KD); if (authzid[0]) snprintf((char*)cs.nonces, sizeof(cs.nonces), ":%s:%s:%s", nonce, cnonce, authzid); else snprintf((char*)cs.nonces, sizeof(cs.nonces), ":%s:%s", nonce, cnonce); cs.nonces_len = strlen((char*)cs.nonces); snprintf((char*)cs.login_id, sizeof(cs.login_id), "%s:%s:", username, realm); cs.login_id_len = strlen((char*)cs.login_id); MEM_FREE(ccopy); return (void*)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void set_key(char *key, int index) { strnzcpyn(saved_key[index], key, PLAINTEXT_LENGTH + 1); } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { unsigned char hash[16]; unsigned char hex_hash[MD5_HEX_SIZE]; unsigned char *ptr_src, *ptr_dst; MD5_CTX ctx; int i; MD5_Init(&ctx); // "username:realm" MD5_Update(&ctx, cur_salt->login_id, cur_salt->login_id_len); // "password" MD5_Update(&ctx, saved_key[index], strlen(saved_key[index])); MD5_Final(hash, &ctx); MD5_Init(&ctx); // previous result MD5_Update(&ctx, hash, BINARY_SIZE); // ":nonce:cnonce[:authzid]" MD5_Update(&ctx, cur_salt->nonces, cur_salt->nonces_len); MD5_Final(hash, &ctx); // hexify ptr_src = hash; ptr_dst = hex_hash; for (i = 0; i < BINARY_SIZE; ++i) { unsigned char v = *ptr_src++; *ptr_dst++ = itoa16_shr_04[ARCH_INDEX(v)]; *ptr_dst++ = itoa16_and_0f[ARCH_INDEX(v)]; } MD5_Init(&ctx); // previous result, in hex MD5_Update(&ctx, hex_hash, MD5_HEX_SIZE); // ":nonce:nc:cnonce:qop:hex_A2_hash MD5_Update(&ctx, cur_salt->prehash_KD, cur_salt->prehash_KD_len); MD5_Final((unsigned char*)crypt_key[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { #if defined(_OPENMP) || (MAX_KEYS_PER_CRYPT > 1) int index; uint32_t b = ((uint32_t*)binary)[0]; for (index = 0; index < count; index++) if (crypt_key[index][0] == b) return 1; return 0; #else return ((uint32_t*)binary)[0] == crypt_key[0][0]; #endif } 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; } #define COMMON_GET_HASH_VAR crypt_key #include "common-get-hash.h" struct fmt_main fmt_DMD5 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */