source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
mixed_tentusscher_myo_epi_2004_S1_4.c | // Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium)
// (AP + max:dvdt)
#include <stdio.h>
#include "mixed_tentusscher_myo_epi_2004_S1_4.h"
GET_CELL_MODEL_DATA(init_cell_model_data)
{
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu)
{
static bool first_call = true;
if(first_call)
{
print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n");
first_call = false;
}
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
// Initial conditions for TenTusscher myocardium
if (mapping[sv_id] == 0)
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
// Initial conditions for TenTusscher epicardium
else
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5808390037434,0.00128660871673998,0.780017411965445,0.779866089420134,0.000174427830947983,0.485221044706665,0.00293766951726531,0.999998352403933,1.92945075222659e-08,1.88789743418140e-05,0.999774028269383,1.00656274895341,0.999980305363904,5.75119942688369e-05,0.652562498130868,9.24127402937561,140.252453661949};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu)
{
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++)
{
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = (uint32_t )i;
for (int j = 0; j < num_steps; ++j)
{
if (mapping[i] == 0)
solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]);
else
solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_myo(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Myocardium cell
real Gks=0.062;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Myocardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
Irel=A*sd*sg;
Ileak=0.00008f*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
// [!] Myocardium cell
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_epi(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Epicardium cell
real Gks=0.245;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Epicardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={14.1821693920716,0.000262369857178200,0.000171567529876738,0.000414005106483591,0.297500226048348,0.162622717394298,0.207515183338143,3.39980849488085,0.0224798791846427,2.56467648820225,1096.76282222310,0.000572145335603343,0.124382279366777,0.0197003709329121,0.00191117528600119,6.10868623397025e-05};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
gbdt.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_BOOSTING_GBDT_H_
#define LIGHTGBM_BOOSTING_GBDT_H_
#include <LightGBM/boosting.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/prediction_early_stop.h>
#include <LightGBM/cuda/vector_cudahost.h>
#include <LightGBM/utils/json11.h>
#include <LightGBM/utils/threading.h>
#include <string>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <utility>
#include <vector>
#include "score_updater.hpp"
namespace LightGBM {
using json11::Json;
/*!
* \brief GBDT algorithm implementation. including Training, prediction, bagging.
*/
class GBDT : public GBDTBase {
public:
/*!
* \brief Constructor
*/
GBDT();
/*!
* \brief Destructor
*/
~GBDT();
/*!
* \brief Initialization logic
* \param gbdt_config Config for boosting
* \param train_data Training data
* \param objective_function Training objective function
* \param training_metrics Training metrics
*/
void Init(const Config* gbdt_config, const Dataset* train_data,
const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override;
/*!
* \brief Merge model from other boosting object. Will insert to the front of current boosting object
* \param other
*/
void MergeFrom(const Boosting* other) override {
auto other_gbdt = reinterpret_cast<const GBDT*>(other);
// tmp move to other vector
auto original_models = std::move(models_);
models_ = std::vector<std::unique_ptr<Tree>>();
// push model from other first
for (const auto& tree : other_gbdt->models_) {
auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
models_.push_back(std::move(new_tree));
}
num_init_iteration_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
// push model in current object
for (const auto& tree : original_models) {
auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
models_.push_back(std::move(new_tree));
}
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
}
void ShuffleModels(int start_iter, int end_iter) override {
int total_iter = static_cast<int>(models_.size()) / num_tree_per_iteration_;
start_iter = std::max(0, start_iter);
if (end_iter <= 0) {
end_iter = total_iter;
}
end_iter = std::min(total_iter, end_iter);
auto original_models = std::move(models_);
std::vector<int> indices(total_iter);
for (int i = 0; i < total_iter; ++i) {
indices[i] = i;
}
Random tmp_rand(17);
for (int i = start_iter; i < end_iter - 1; ++i) {
int j = tmp_rand.NextShort(i + 1, end_iter);
std::swap(indices[i], indices[j]);
}
models_ = std::vector<std::unique_ptr<Tree>>();
for (int i = 0; i < total_iter; ++i) {
for (int j = 0; j < num_tree_per_iteration_; ++j) {
int tree_idx = indices[i] * num_tree_per_iteration_ + j;
auto new_tree = std::unique_ptr<Tree>(new Tree(*(original_models[tree_idx].get())));
models_.push_back(std::move(new_tree));
}
}
}
/*!
* \brief Reset the training data
* \param train_data New Training data
* \param objective_function Training objective function
* \param training_metrics Training metrics
*/
void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override;
/*!
* \brief Reset Boosting Config
* \param gbdt_config Config for boosting
*/
void ResetConfig(const Config* gbdt_config) override;
/*!
* \brief Adding a validation dataset
* \param valid_data Validation dataset
* \param valid_metrics Metrics for validation dataset
*/
void AddValidDataset(const Dataset* valid_data,
const std::vector<const Metric*>& valid_metrics) override;
/*!
* \brief Perform a full training procedure
* \param snapshot_freq frequence of snapshot
* \param model_output_path path of model file
*/
void Train(int snapshot_freq, const std::string& model_output_path) override;
void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) override;
/*!
* \brief Training logic
* \param gradients nullptr for using default objective, otherwise use self-defined boosting
* \param hessians nullptr for using default objective, otherwise use self-defined boosting
* \return True if cannot train any more
*/
bool TrainOneIter(const score_t* gradients, const score_t* hessians) override;
/*!
* \brief Rollback one iteration
*/
void RollbackOneIter() override;
/*!
* \brief Get current iteration
*/
int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_tree_per_iteration_; }
/*!
* \brief Can use early stopping for prediction or not
* \return True if cannot use early stopping for prediction
*/
bool NeedAccuratePrediction() const override {
if (objective_function_ == nullptr) {
return true;
} else {
return objective_function_->NeedAccuratePrediction();
}
}
/*!
* \brief Get evaluation result at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \return evaluation result
*/
std::vector<double> GetEvalAt(int data_idx) const override;
/*!
* \brief Get current training score
* \param out_len length of returned score
* \return training score
*/
const double* GetTrainingScore(int64_t* out_len) override;
/*!
* \brief Get size of prediction at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \return The size of prediction
*/
int64_t GetNumPredictAt(int data_idx) const override {
CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size()));
data_size_t num_data = train_data_->num_data();
if (data_idx > 0) {
num_data = valid_score_updater_[data_idx - 1]->num_data();
}
return num_data * num_class_;
}
/*!
* \brief Get prediction result at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \param result used to store prediction result, should allocate memory before call this function
* \param out_len length of returned score
*/
void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override;
/*!
* \brief Get number of prediction for one data
* \param start_iteration Start index of the iteration to predict
* \param num_iteration number of used iterations
* \param is_pred_leaf True if predicting leaf index
* \param is_pred_contrib True if predicting feature contribution
* \return number of prediction
*/
inline int NumPredictOneRow(int start_iteration, int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const override {
int num_pred_in_one_row = num_class_;
if (is_pred_leaf) {
int max_iteration = GetCurrentIteration();
start_iteration = std::max(start_iteration, 0);
start_iteration = std::min(start_iteration, max_iteration);
if (num_iteration > 0) {
num_pred_in_one_row *= static_cast<int>(std::min(max_iteration - start_iteration, num_iteration));
} else {
num_pred_in_one_row *= (max_iteration - start_iteration);
}
} else if (is_pred_contrib) {
num_pred_in_one_row = num_tree_per_iteration_ * (max_feature_idx_ + 2); // +1 for 0-based indexing, +1 for baseline
}
return num_pred_in_one_row;
}
void PredictRaw(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
void PredictRawByMap(const std::unordered_map<int, double>& features, double* output,
const PredictionEarlyStopInstance* early_stop) const override;
void Predict(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
void PredictByMap(const std::unordered_map<int, double>& features, double* output,
const PredictionEarlyStopInstance* early_stop) const override;
void PredictLeafIndex(const double* features, double* output) const override;
void PredictLeafIndexByMap(const std::unordered_map<int, double>& features, double* output) const override;
void PredictContrib(const double* features, double* output) const override;
void PredictContribByMap(const std::unordered_map<int, double>& features,
std::vector<std::unordered_map<int, double>>* output) const override;
/*!
* \brief Dump model to json format string
* \param start_iteration The model will be saved start from
* \param num_iteration Number of iterations that want to dump, -1 means dump all
* \param feature_importance_type Type of feature importance, 0: split, 1: gain
* \return Json format string of model
*/
std::string DumpModel(int start_iteration, int num_iteration,
int feature_importance_type) const override;
/*!
* \brief Translate model to if-else statement
* \param num_iteration Number of iterations that want to translate, -1 means translate all
* \return if-else format codes of model
*/
std::string ModelToIfElse(int num_iteration) const override;
/*!
* \brief Translate model to if-else statement
* \param num_iteration Number of iterations that want to translate, -1 means translate all
* \param filename Filename that want to save to
* \return is_finish Is training finished or not
*/
bool SaveModelToIfElse(int num_iteration, const char* filename) const override;
/*!
* \brief Save model to file
* \param start_iteration The model will be saved start from
* \param num_iterations Number of model that want to save, -1 means save all
* \param feature_importance_type Type of feature importance, 0: split, 1: gain
* \param filename Filename that want to save to
* \return is_finish Is training finished or not
*/
bool SaveModelToFile(int start_iteration, int num_iterations,
int feature_importance_type,
const char* filename) const override;
/*!
* \brief Save model to string
* \param start_iteration The model will be saved start from
* \param num_iterations Number of model that want to save, -1 means save all
* \param feature_importance_type Type of feature importance, 0: split, 1: gain
* \return Non-empty string if succeeded
*/
std::string SaveModelToString(int start_iteration, int num_iterations, int feature_importance_type) const override;
/*!
* \brief Restore from a serialized buffer
*/
bool LoadModelFromString(const char* buffer, size_t len) override;
/*!
* \brief Calculate feature importances
* \param num_iteration Number of model that want to use for feature importance, -1 means use all
* \param importance_type: 0 for split, 1 for gain
* \return vector of feature_importance
*/
std::vector<double> FeatureImportance(int num_iteration, int importance_type) const override;
/*!
* \brief Calculate upper bound value
* \return upper bound value
*/
double GetUpperBoundValue() const override;
/*!
* \brief Calculate lower bound value
* \return lower bound value
*/
double GetLowerBoundValue() const override;
/*!
* \brief Get max feature index of this model
* \return Max feature index of this model
*/
inline int MaxFeatureIdx() const override { return max_feature_idx_; }
/*!
* \brief Get feature names of this model
* \return Feature names of this model
*/
inline std::vector<std::string> FeatureNames() const override { return feature_names_; }
/*!
* \brief Get index of label column
* \return index of label column
*/
inline int LabelIdx() const override { return label_idx_; }
/*!
* \brief Get number of weak sub-models
* \return Number of weak sub-models
*/
inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); }
/*!
* \brief Get number of tree per iteration
* \return number of tree per iteration
*/
inline int NumModelPerIteration() const override { return num_tree_per_iteration_; }
/*!
* \brief Get number of classes
* \return Number of classes
*/
inline int NumberOfClasses() const override { return num_class_; }
inline void InitPredict(int start_iteration, int num_iteration, bool is_pred_contrib) override {
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
start_iteration = std::max(start_iteration, 0);
start_iteration = std::min(start_iteration, num_iteration_for_pred_);
if (num_iteration > 0) {
num_iteration_for_pred_ = std::min(num_iteration, num_iteration_for_pred_ - start_iteration);
} else {
num_iteration_for_pred_ = num_iteration_for_pred_ - start_iteration;
}
start_iteration_for_pred_ = start_iteration;
if (is_pred_contrib) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < static_cast<int>(models_.size()); ++i) {
models_[i]->RecomputeMaxDepth();
}
}
}
inline double GetLeafValue(int tree_idx, int leaf_idx) const override {
CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
return models_[tree_idx]->LeafOutput(leaf_idx);
}
inline void SetLeafValue(int tree_idx, int leaf_idx, double val) override {
CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
models_[tree_idx]->SetLeafOutput(leaf_idx, val);
}
/*!
* \brief Get Type name of this boosting object
*/
const char* SubModelName() const override { return "tree"; }
protected:
virtual bool GetIsConstHessian(const ObjectiveFunction* objective_function) {
if (objective_function != nullptr) {
return objective_function->IsConstantHessian();
} else {
return false;
}
}
/*!
* \brief Print eval result and check early stopping
*/
virtual bool EvalAndCheckEarlyStopping();
/*!
* \brief reset config for bagging
*/
void ResetBaggingConfig(const Config* config, bool is_change_dataset);
/*!
* \brief Implement bagging logic
* \param iter Current interation
*/
virtual void Bagging(int iter);
virtual data_size_t BaggingHelper(data_size_t start, data_size_t cnt,
data_size_t* buffer);
data_size_t BalancedBaggingHelper(data_size_t start, data_size_t cnt,
data_size_t* buffer);
/*!
* \brief calculate the object function
*/
virtual void Boosting();
/*!
* \brief updating score after tree was trained
* \param tree Trained tree of this iteration
* \param cur_tree_id Current tree for multiclass training
*/
virtual void UpdateScore(const Tree* tree, const int cur_tree_id);
/*!
* \brief eval results for one metric
*/
virtual std::vector<double> EvalOneMetric(const Metric* metric, const double* score) const;
/*!
* \brief Print metric result of current iteration
* \param iter Current interation
* \return best_msg if met early_stopping
*/
std::string OutputMetric(int iter);
double BoostFromAverage(int class_id, bool update_scorer);
/*! \brief current iteration */
int iter_;
/*! \brief Pointer to training data */
const Dataset* train_data_;
/*! \brief Config of gbdt */
std::unique_ptr<Config> config_;
/*! \brief Tree learner, will use this class to learn trees */
std::unique_ptr<TreeLearner> tree_learner_;
/*! \brief Objective function */
const ObjectiveFunction* objective_function_;
/*! \brief Store and update training data's score */
std::unique_ptr<ScoreUpdater> train_score_updater_;
/*! \brief Metrics for training data */
std::vector<const Metric*> training_metrics_;
/*! \brief Store and update validation data's scores */
std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_;
/*! \brief Metric for validation data */
std::vector<std::vector<const Metric*>> valid_metrics_;
/*! \brief Number of rounds for early stopping */
int early_stopping_round_;
/*! \brief Only use first metric for early stopping */
bool es_first_metric_only_;
/*! \brief Best iteration(s) for early stopping */
std::vector<std::vector<int>> best_iter_;
/*! \brief Best score(s) for early stopping */
std::vector<std::vector<double>> best_score_;
/*! \brief output message of best iteration */
std::vector<std::vector<std::string>> best_msg_;
/*! \brief Trained models(trees) */
std::vector<std::unique_ptr<Tree>> models_;
/*! \brief Max feature index of training data*/
int max_feature_idx_;
#ifdef USE_CUDA
/*! \brief First order derivative of training data */
std::vector<score_t, CHAllocator<score_t>> gradients_;
/*! \brief Second order derivative of training data */
std::vector<score_t, CHAllocator<score_t>> hessians_;
#else
/*! \brief First order derivative of training data */
std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> gradients_;
/*! \brief Second order derivative of training data */
std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> hessians_;
#endif
/*! \brief Store the indices of in-bag data */
std::vector<data_size_t, Common::AlignmentAllocator<data_size_t, kAlignedSize>> bag_data_indices_;
/*! \brief Number of in-bag data */
data_size_t bag_data_cnt_;
/*! \brief Number of training data */
data_size_t num_data_;
/*! \brief Number of trees per iterations */
int num_tree_per_iteration_;
/*! \brief Number of class */
int num_class_;
/*! \brief Index of label column */
data_size_t label_idx_;
/*! \brief number of used model */
int num_iteration_for_pred_;
/*! \brief Start iteration of used model */
int start_iteration_for_pred_;
/*! \brief Shrinkage rate for one iteration */
double shrinkage_rate_;
/*! \brief Number of loaded initial models */
int num_init_iteration_;
/*! \brief Feature names */
std::vector<std::string> feature_names_;
std::vector<std::string> feature_infos_;
std::unique_ptr<Dataset> tmp_subset_;
bool is_use_subset_;
std::vector<bool> class_need_train_;
bool is_constant_hessian_;
std::unique_ptr<ObjectiveFunction> loaded_objective_;
bool average_output_;
bool need_re_bagging_;
bool balanced_bagging_;
std::string loaded_parameter_;
std::vector<int8_t> monotone_constraints_;
const int bagging_rand_block_ = 1024;
std::vector<Random> bagging_rands_;
ParallelPartitionRunner<data_size_t, false> bagging_runner_;
Json forced_splits_json_;
};
} // namespace LightGBM
#endif // LightGBM_BOOSTING_GBDT_H_
|
viterbi_decode_op.h | /* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/elementwise/elementwise_functor.h"
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
#include "paddle/fluid/operators/math/concat_and_split.h"
#include "paddle/fluid/operators/transpose_op.h"
#include "paddle/fluid/operators/unique_op.h"
#include "paddle/phi/kernels/funcs/compare_functors.h"
#include "paddle/phi/kernels/funcs/gather.h"
#ifdef PADDLE_WITH_MKLML
#include <omp.h>
#endif
namespace paddle {
namespace operators {
template <typename DeviceContext, typename T, typename IndType>
struct Argmax {
void operator()(const framework::ExecutionContext& ctx,
const framework::Tensor& input, framework::Tensor* out_idx,
framework::Tensor* out, int axis) {
framework::DDim input_dims = input.dims();
int64_t pre = 1;
int64_t post = 1;
int64_t n = input_dims[axis];
for (int i = 0; i < axis; i++) {
pre *= input_dims[i];
}
for (int i = axis + 1; i < input_dims.size(); i++) {
post *= input_dims[i];
}
int64_t height = pre * post;
int64_t width = n;
const T* in_data = input.data<T>();
IndType* out_idx_data = out_idx->data<IndType>();
T* out_data = out->data<T>();
// Reduce
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
for (int64_t i = 0; i < height; ++i) {
int64_t h = i / post;
int64_t w = i % post;
IndType max_idx = -1;
T max_value = (std::numeric_limits<T>::lowest)(); // for windows compile
for (int64_t j = 0; j < width; ++j) {
if (in_data[h * width * post + j * post + w] > max_value) {
max_value = in_data[h * width * post + j * post + w];
max_idx = j;
}
}
out_data[i] = max_value;
out_idx_data[i] = max_idx;
}
}
};
template <typename DeviceContext>
struct ARange {
void operator()(const DeviceContext& dev_ctx, int64_t* data, int end,
int64_t scale) {
for (int i = 0; i < end; ++i) {
data[i] = i * scale;
}
}
};
template <typename DeviceContext, typename T>
struct GetMaxValue {
void operator()(const DeviceContext& dev_ctx, const framework::Tensor& input,
T* max_value) {
auto input_ptr = input.data<T>();
auto num = input.numel();
*max_value = *std::max_element(input_ptr, input_ptr + num);
}
};
template <typename DeviceContext, typename T, typename IndexT = int>
struct Gather {
void operator()(const DeviceContext& ctx, const framework::Tensor& src,
const framework::Tensor& index, framework::Tensor* output) {
phi::funcs::CPUGather<T, IndexT>(ctx, src, index, output);
}
};
template <typename T, typename Functor, typename OutT = T>
void SameDimsBinaryOP(const framework::Tensor& lhs,
const framework::Tensor& rhs, framework::Tensor* out) {
const T* lhs_ptr = lhs.data<T>();
const T* rhs_ptr = rhs.data<T>();
OutT* out_ptr = out->data<OutT>();
Functor functor;
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
for (int i = 0; i < out->numel(); ++i) {
out_ptr[i] = functor(lhs_ptr[i], rhs_ptr[i]);
}
}
template <typename DeviceContext,
template <typename InT, typename OutT> typename CompareFunctor,
typename T>
struct GetMask {
void operator()(const framework::ExecutionContext& ctx,
const framework::Tensor& lhs, const framework::Tensor& rhs,
framework::Tensor* mask) {
SameDimsBinaryOP<int64_t, CompareFunctor<int64_t, T>, T>(lhs, rhs, mask);
}
};
template <bool is_multi_threads>
struct GetInputIndex {
void operator()(const std::vector<int>& lhs_dims,
const std::vector<int>& rhs_dims,
const std::vector<int>& output_dims,
const std::vector<int>& lhs_strides,
const std::vector<int>& rhs_strides,
const std::vector<int>& output_strides, int output_idx,
int* index_array, int* lhs_idx, int* rhs_idx) {
int out_dims_size = output_strides.size();
for (int j = 0; j < out_dims_size; ++j) {
int curr_idx = output_idx / output_strides[j];
output_idx %= output_strides[j];
*lhs_idx += (lhs_dims[j] > 1) ? curr_idx * lhs_strides[j] : 0;
*rhs_idx += (rhs_dims[j] > 1) ? curr_idx * rhs_strides[j] : 0;
}
}
};
template <>
struct GetInputIndex<false> {
void operator()(const std::vector<int>& lhs_dims,
const std::vector<int>& rhs_dims,
const std::vector<int>& output_dims,
const std::vector<int>& lhs_strides,
const std::vector<int>& rhs_strides,
const std::vector<int>& output_strides, int output_idx,
int* index_array, int* lhs_idx, int* rhs_idx) {
int out_dims_size = output_strides.size();
*lhs_idx = phi::funcs::GetElementwiseIndex(lhs_dims.data(), out_dims_size,
index_array);
*rhs_idx = phi::funcs::GetElementwiseIndex(rhs_dims.data(), out_dims_size,
index_array);
phi::funcs::UpdateElementwiseIndexArray(output_dims.data(), out_dims_size,
index_array);
}
};
template <typename T, typename Functor, bool is_multi_threads = false>
void SimpleBroadcastBinaryOP(const framework::Tensor& lhs,
const framework::Tensor& rhs,
framework::Tensor* out) {
const T* lhs_ptr = lhs.data<T>();
const T* rhs_ptr = rhs.data<T>();
T* out_ptr = out->data<T>();
int out_size = static_cast<int>(out->dims().size());
std::vector<int> out_dims(out_size);
std::vector<int> lhs_dims(out_size);
std::vector<int> rhs_dims(out_size);
std::copy(lhs.dims().Get(), lhs.dims().Get() + out_size, lhs_dims.data());
std::copy(rhs.dims().Get(), rhs.dims().Get() + out_size, rhs_dims.data());
std::copy(out->dims().Get(), out->dims().Get() + out_size, out_dims.data());
std::vector<int> output_strides(out_size, 1);
std::vector<int> lhs_strides(out_size, 1);
std::vector<int> rhs_strides(out_size, 1);
std::vector<int> index_array(out_size, 0);
// calculate strides
for (int i = out_size - 2; i >= 0; --i) {
output_strides[i] = output_strides[i + 1] * out_dims[i + 1];
lhs_strides[i] = lhs_strides[i + 1] * lhs_dims[i + 1];
rhs_strides[i] = rhs_strides[i + 1] * rhs_dims[i + 1];
}
Functor functor;
GetInputIndex<is_multi_threads> get_input_index;
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
for (int i = 0; i < out->numel(); ++i) {
int lhs_idx = 0;
int rhs_idx = 0;
get_input_index(lhs_dims, rhs_dims, out_dims, lhs_strides, rhs_strides,
output_strides, i, index_array.data(), &lhs_idx, &rhs_idx);
out_ptr[i] = functor(lhs_ptr[lhs_idx], rhs_ptr[rhs_idx]);
}
}
template <typename DeviceContext, template <typename T> typename BinaryFunctor,
typename T>
struct BinaryOperation {
void operator()(const DeviceContext& dev_ctx, const framework::Tensor& lhs,
const framework::Tensor& rhs, framework::Tensor* output) {
if (lhs.dims() == rhs.dims()) {
SameDimsBinaryOP<T, BinaryFunctor<T>>(lhs, rhs, output);
} else {
bool is_multi_threads = false;
#ifdef PADDLE_WITH_MKLML
if (omp_get_max_threads() > 1) {
is_multi_threads = true;
}
#endif
if (is_multi_threads) {
SimpleBroadcastBinaryOP<T, BinaryFunctor<T>, true>(lhs, rhs, output);
} else {
SimpleBroadcastBinaryOP<T, BinaryFunctor<T>, false>(lhs, rhs, output);
}
}
}
};
class TensorBuffer {
public:
explicit TensorBuffer(const framework::LoDTensor& in)
: buffer_(in), offset_(0) {
buffer_.Resize({buffer_.numel()});
}
framework::Tensor GetBufferBlock(std::initializer_list<int64_t> shape) {
int64_t size = std::accumulate(shape.begin(), shape.end(), 1,
std::multiplies<int64_t>());
framework::Tensor block = buffer_.Slice(offset_, offset_ + size);
offset_ += size;
block.Resize(shape);
return block;
}
private:
framework::LoDTensor buffer_; // need to resize 1-D Tensor
int offset_;
};
template <typename DeviceContext, typename T>
class ViterbiDecodeKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
bool include_bos_eos_tag = ctx.Attr<bool>("include_bos_eos_tag");
auto& dev_ctx = ctx.template device_context<DeviceContext>();
auto curr_place = ctx.GetPlace();
auto* input = ctx.Input<framework::Tensor>("Input");
auto batch_size = static_cast<int>(input->dims()[0]);
auto seq_len = static_cast<int>(input->dims()[1]);
auto n_labels = static_cast<int>(input->dims()[2]);
phi::funcs::SetConstant<DeviceContext, T> float_functor;
phi::funcs::SetConstant<DeviceContext, int64_t> int_functor;
std::vector<framework::Tensor> historys;
// We create tensor buffer in order to avoid allocating memory frequently
// 10 means allocate 10*batch_size bytes memory, such as int_mask, zero...
int buffer_size = batch_size * (n_labels + 1) * seq_len + 10 * batch_size;
framework::LoDTensor int_buffer;
int_buffer.Resize(phi::make_ddim({buffer_size}));
int_buffer.mutable_data<int64_t>(ctx.GetPlace());
TensorBuffer int_tensor_buffer(int_buffer);
// create float tensor buffer
// 10 means allocate 10*batch_size*n_labels bytes, such as alpha, alpha_max
buffer_size = batch_size * (seq_len + 10) * n_labels +
(batch_size + 2) * n_labels * n_labels;
framework::LoDTensor float_buffer;
float_buffer.Resize(phi::make_ddim({buffer_size}));
float_buffer.mutable_data<T>(ctx.GetPlace());
TensorBuffer float_tensor_buffer(float_buffer);
auto* length = ctx.Input<framework::Tensor>("Length");
framework::Tensor left_length =
int_tensor_buffer.GetBufferBlock({batch_size, 1});
framework::TensorCopy(*length, curr_place, dev_ctx, &left_length);
int64_t max_seq_len = 0;
GetMaxValue<DeviceContext, int64_t> get_max_value;
get_max_value(dev_ctx, left_length, &max_seq_len);
auto* scores = ctx.Output<framework::Tensor>("Scores");
scores->mutable_data<T>(curr_place);
auto* path = ctx.Output<framework::Tensor>("Path");
path->Resize({batch_size, max_seq_len});
path->mutable_data<int64_t>(curr_place);
framework::Tensor tpath =
int_tensor_buffer.GetBufferBlock({max_seq_len, batch_size});
auto batch_path = Unbind(tpath);
for (auto it = batch_path.begin(); it != batch_path.end(); ++it) {
it->Resize({batch_size});
}
// create and init required tensor
framework::Tensor input_exp =
float_tensor_buffer.GetBufferBlock({seq_len, batch_size, n_labels});
TransCompute<DeviceContext, T>(3, dev_ctx, *input, &input_exp, {1, 0, 2});
auto* transition = ctx.Input<framework::Tensor>("Transition");
framework::Tensor trans_exp =
float_tensor_buffer.GetBufferBlock({n_labels, n_labels});
framework::TensorCopy(*transition, curr_place, dev_ctx, &trans_exp);
trans_exp.Resize({1, n_labels, n_labels});
framework::Tensor alpha =
float_tensor_buffer.GetBufferBlock({batch_size, n_labels});
framework::Tensor zero = int_tensor_buffer.GetBufferBlock({batch_size, 1});
int_functor(dev_ctx, &zero, 0);
framework::Tensor one = int_tensor_buffer.GetBufferBlock({batch_size, 1});
int_functor(dev_ctx, &one, 1);
framework::Tensor float_one =
float_tensor_buffer.GetBufferBlock({batch_size, 1});
float_functor(dev_ctx, &float_one, static_cast<T>(1.0));
framework::Tensor alpha_trn_sum =
float_tensor_buffer.GetBufferBlock({batch_size, n_labels, n_labels});
framework::Tensor alpha_max =
float_tensor_buffer.GetBufferBlock({batch_size, n_labels});
framework::Tensor alpha_argmax =
int_tensor_buffer.GetBufferBlock({seq_len, batch_size, n_labels});
auto alpha_argmax_unbind = Unbind(alpha_argmax);
framework::Tensor alpha_nxt =
float_tensor_buffer.GetBufferBlock({batch_size, n_labels});
framework::Tensor int_mask = int_tensor_buffer.GetBufferBlock({batch_size});
framework::Tensor zero_len_mask =
int_tensor_buffer.GetBufferBlock({batch_size});
framework::Tensor float_mask =
float_tensor_buffer.GetBufferBlock({batch_size, 1});
framework::Tensor stop_trans =
float_tensor_buffer.GetBufferBlock({1, 1, n_labels});
framework::Tensor start_trans =
float_tensor_buffer.GetBufferBlock({1, 1, n_labels});
framework::Tensor rest_trans =
float_tensor_buffer.GetBufferBlock({1, n_labels - 2, n_labels});
framework::Tensor last_ids = int_tensor_buffer.GetBufferBlock({batch_size});
framework::Tensor last_ids_tmp =
int_tensor_buffer.GetBufferBlock({batch_size});
framework::Tensor batch_offset =
int_tensor_buffer.GetBufferBlock({batch_size});
framework::Tensor gather_idx =
int_tensor_buffer.GetBufferBlock({batch_size});
std::vector<const framework::Tensor*> shape{&rest_trans, &stop_trans,
&start_trans};
std::vector<framework::Tensor*> outputs{&rest_trans, &stop_trans,
&start_trans};
math::SplitFunctor<DeviceContext, T> split_functor;
split_functor(dev_ctx, trans_exp, shape, 1, &outputs);
stop_trans.Resize({1, n_labels});
start_trans.Resize({1, n_labels});
auto logit0 = input_exp.Slice(0, 1);
logit0.Resize({batch_size, n_labels});
BinaryOperation<DeviceContext, AddFunctor, T> AddFloat;
BinaryOperation<DeviceContext, AddFunctor, int64_t> AddInt;
BinaryOperation<DeviceContext, MulFunctor, T> MulFloat;
BinaryOperation<DeviceContext, MulFunctor, int64_t> MulInt;
BinaryOperation<DeviceContext, SubFunctor, T> SubFloat;
BinaryOperation<DeviceContext, SubFunctor, int64_t> SubInt;
if (include_bos_eos_tag) {
AddFloat(dev_ctx, logit0, start_trans, &alpha);
GetMask<DeviceContext, phi::funcs::EqualFunctor, T>()(ctx, left_length,
one, &float_mask);
MulFloat(dev_ctx, stop_trans, float_mask, &alpha_nxt);
AddFloat(dev_ctx, alpha, alpha_nxt, &alpha);
} else {
alpha = logit0;
}
SubInt(dev_ctx, left_length, one, &left_length);
Argmax<DeviceContext, T, int64_t> argmax;
for (int64_t i = 1; i < max_seq_len; ++i) {
framework::Tensor logit = input_exp.Slice(i, i + 1);
logit.Resize({batch_size, n_labels});
framework::Tensor& alpha_exp = alpha.Resize({batch_size, n_labels, 1});
AddFloat(dev_ctx, alpha_exp, trans_exp, &alpha_trn_sum);
auto alpha_argmax_temp = alpha_argmax_unbind[i - 1];
alpha_argmax_temp.Resize({batch_size, n_labels});
argmax(ctx, alpha_trn_sum, &alpha_argmax_temp, &alpha_max, 1);
historys.emplace_back(alpha_argmax_temp);
AddFloat(dev_ctx, alpha_max, logit, &alpha_nxt);
alpha.Resize({batch_size, n_labels});
// mask = paddle.cast((left_length > 0), dtype='float32')
// alpha = mask * alpha_nxt + (1 - mask) * alpha
GetMask<DeviceContext, phi::funcs::GreaterThanFunctor, T>()(
ctx, left_length, zero, &float_mask);
// alpha_nxt = mask * alpha_nxt
MulFloat(dev_ctx, alpha_nxt, float_mask, &alpha_nxt);
// inv_mask = 1 - mask
SubFloat(dev_ctx, float_one, float_mask, &float_mask);
// alpha = (1 - mask) * alpha
MulFloat(dev_ctx, alpha, float_mask, &alpha);
// alpha += alpha_nxt
AddFloat(dev_ctx, alpha, alpha_nxt, &alpha);
if (include_bos_eos_tag) {
GetMask<DeviceContext, phi::funcs::EqualFunctor, T>()(ctx, left_length,
one, &float_mask);
// alpha += mask * trans_exp[:, self.stop_idx]
MulFloat(dev_ctx, stop_trans, float_mask, &alpha_nxt);
AddFloat(dev_ctx, alpha, alpha_nxt, &alpha);
}
SubInt(dev_ctx, left_length, one, &left_length);
}
argmax(ctx, alpha, &last_ids, scores, 1);
left_length.Resize({batch_size});
GetMask<DeviceContext, phi::funcs::GreaterEqualFunctor, int64_t>()(
ctx, left_length, zero, &int_mask);
// last_ids_update = last_ids * tag_mask
int last_ids_index = 1;
int actual_len = (std::min)(seq_len, static_cast<int>(max_seq_len));
MulInt(dev_ctx, last_ids, int_mask,
&batch_path[actual_len - last_ids_index]);
// The algorithm below can refer to
// https://github.com/PaddlePaddle/PaddleNLP/blob/develop/paddlenlp/layers/crf.py#L438
ARange<DeviceContext> arange;
arange(dev_ctx, batch_offset.data<int64_t>(), batch_size, n_labels);
Gather<DeviceContext, int64_t, int64_t> gather;
for (auto hist = historys.rbegin(); hist != historys.rend(); ++hist) {
++last_ids_index;
AddInt(dev_ctx, left_length, one, &left_length);
AddInt(dev_ctx, batch_offset, last_ids, &gather_idx);
framework::Tensor& last_ids_update =
batch_path[actual_len - last_ids_index];
hist->Resize({batch_size * n_labels});
gather(dev_ctx, *hist, gather_idx, &last_ids_update);
GetMask<DeviceContext, phi::funcs::GreaterThanFunctor, int64_t>()(
ctx, left_length, zero, &int_mask);
MulInt(dev_ctx, last_ids_update, int_mask, &last_ids_update);
GetMask<DeviceContext, phi::funcs::EqualFunctor, int64_t>()(
ctx, left_length, zero, &zero_len_mask);
MulInt(dev_ctx, last_ids, zero_len_mask, &last_ids_tmp);
SubInt(dev_ctx, one, zero_len_mask, &zero_len_mask);
MulInt(dev_ctx, last_ids_update, zero_len_mask, &last_ids_update);
AddInt(dev_ctx, last_ids_update, last_ids_tmp, &last_ids_update);
GetMask<DeviceContext, phi::funcs::LessThanFunctor, int64_t>()(
ctx, left_length, zero, &int_mask);
MulInt(dev_ctx, last_ids, int_mask, &last_ids);
AddInt(dev_ctx, last_ids_update, last_ids, &last_ids);
}
TransCompute<DeviceContext, int64_t>(2, dev_ctx, tpath, path, {1, 0});
}
};
} // namespace operators
} // namespace paddle
|
test.c | #include <stdlib.h>
#include <check.h>
#include <omp.h>
START_TEST(omp_parallel_plain)
{/*{{{*/
int a = 0;
int num_threads;
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
num_threads = omp_get_num_threads();
}
ck_assert_int_eq(a, num_threads);
}/*}}}*/
END_TEST
START_TEST(omp_parallel_num_threads_shell)
{/*{{{*/
int a = 0;
int num_threads_reqd = 1;
setenv("OMP_NUM_THREADS", "1", 1);
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
}
unsetenv("OMP_NUM_THREADS");
ck_assert_int_eq(a, num_threads_reqd);
}/*}}}*/
END_TEST
START_TEST(omp_parallel_num_threads_one)
{/*{{{*/
int a = 0;
int num_threads_reqd = 1;
#pragma omp parallel shared(a) num_threads(num_threads_reqd)
{
__sync_fetch_and_add(&a, 1);
}
ck_assert_int_eq(a, num_threads_reqd);
}/*}}}*/
END_TEST
START_TEST(omp_parallel_num_threads_small)
{/*{{{*/
int a = 0;
int num_threads_reqd = 2;
#pragma omp parallel shared(a) num_threads(num_threads_reqd)
{
__sync_fetch_and_add(&a, 1);
}
ck_assert_int_eq(a, num_threads_reqd);
}/*}}}*/
END_TEST
// TODO: Add test for teams larger than number of MIR workers.
// Large teams are unsupported in MIR.
// The test should therefore pass if MIR throws an assertion.
START_TEST(omp_sequential_parallel)
{/*{{{*/
int a = 0;
int num_threads;
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
num_threads = omp_get_num_threads();
}
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
}
ck_assert_int_eq(a, 2*num_threads);
}/*}}}*/
END_TEST
START_TEST(omp_nested_parallel)
{/*{{{*/
int a = 0;
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
/* Nested parallel block. */
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
}
}
ck_assert_int_eq(a, 2);
}/*}}}*/
END_TEST
START_TEST(omp_nested_sequential_parallel)
{/*{{{*/
int a = 0;
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
/* Nested parallel block. */
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
}
}
ck_assert_int_eq(a, 2);
#pragma omp parallel shared(a)
{
__sync_fetch_and_add(&a, 1);
}
ck_assert_int_eq(a, 3);
}/*}}}*/
END_TEST
Suite* test_suite(void)
{/*{{{*/
Suite* s = suite_create("Test");
TCase* tc = tcase_create("omp_parallel");
tcase_add_test(tc, omp_parallel_plain);
tcase_add_test(tc, omp_parallel_num_threads_shell);
tcase_add_test(tc, omp_parallel_num_threads_one);
tcase_add_test(tc, omp_parallel_num_threads_small);
tcase_add_test(tc, omp_sequential_parallel);
/* tcase_add_test(tc, omp_nested_parallel); */
/* tcase_add_test(tc, omp_nested_sequential_parallel); */
suite_add_tcase(s, tc);
return s;
}/*}}}*/
int main(void)
{/*{{{*/
int number_failed;
Suite* s;
SRunner* sr;
s = test_suite();
sr = srunner_create(s);
srunner_run_all(sr, CK_VERBOSE);
number_failed = srunner_ntests_failed(sr);
srunner_free(sr);
return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}/*}}}*/
|
declare_variant_messages.c | // RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp -std=c99 -fms-extensions -Wno-pragma-pack -Wno-strict-prototypes %s
// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp-simd -std=c99 -fms-extensions -Wno-pragma-pack -Wno-strict-prototypes %s
#pragma omp declare // expected-error {{expected an OpenMP directive}}
int foo(void);
#pragma omp declare variant // expected-error {{expected '(' after 'declare variant'}}
#pragma omp declare variant( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo // expected-error {{expected ')'}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} expected-note {{to match this '('}}
#pragma omp declare variant(x) // expected-error {{use of undeclared identifier 'x'}} expected-error {{expected 'match' clause on}}
#pragma omp declare variant(foo) // expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) // expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) xxx // expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) match // expected-error {{expected '(' after 'match'}}
#pragma omp declare variant(foo) match( // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context set; set skipped}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match() // expected-warning {{expected identifier or string literal describing a context set; set skipped}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx=) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx=yyy) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx=yyy}) // expected-error {{expected ')'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) match(xxx={) // expected-error {{expected ')'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx={vvv, vvv}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx={vvv} xxx) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp declare variant(foo) match(xxx={vvv}) xxx // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) match(implementation={xxx}) // expected-warning {{'xxx' is not a valid context selector for the context set 'implementation'; selector ignored}} expected-note {{context selector options are: 'vendor' 'extension' 'unified_address' 'unified_shared_memory' 'reverse_offload' 'dynamic_allocators' 'atomic_default_mem_order'}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(implementation={vendor}) // expected-warning {{the context selector 'vendor' in context set 'implementation' requires a context property defined in parentheses; selector ignored}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(implementation={vendor(}) // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(implementation={vendor()}) // expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}}
#pragma omp declare variant(foo) match(implementation={vendor(score ibm)}) // expected-error {{expected '(' after 'score'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}}
#pragma omp declare variant(foo) match(implementation={vendor(score( ibm)}) // expected-error {{use of undeclared identifier 'ibm'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(implementation={vendor(score(2 ibm)}) // expected-error {{expected ')'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{to match this '('}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(implementation={vendor(score(foo()) ibm)}) // expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{score expressions in the OpenMP context selector need to be constant; foo() is not and will be ignored}}
#pragma omp declare variant(foo) match(implementation={vendor(score(5): ibm), vendor(llvm)}) // expected-warning {{the context selector 'vendor' was used already in the same 'omp declare variant' directive; selector ignored}} expected-note {{the previous context selector 'vendor' used here}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(implementation={vendor(score(5): ibm), kind(cpu)}) // expected-warning {{the context selector 'kind' is not valid for the context set 'implementation'; selector ignored}} expected-note {{the context selector 'kind' can be nested in the context set 'device'; try 'match(device={kind(property)})'}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(device={xxx}) // expected-warning {{'xxx' is not a valid context selector for the context set 'device'; selector ignored}} expected-note {{context selector options are: 'kind' 'arch' 'isa'}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(device={kind}) // expected-warning {{the context selector 'kind' in context set 'device' requires a context property defined in parentheses; selector ignored}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(device={kind(}) // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(device={kind()}) // expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}}
#pragma omp declare variant(foo) match(device={kind(score cpu)}) // expected-error {{expected '(' after 'score'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<invalid>'); score ignored}}
#pragma omp declare variant(foo) match(device = {kind(score(ibm) }) // expected-error {{use of undeclared identifier 'ibm'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<recovery-expr>()'); score ignored}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(device={kind(score(2 gpu)}) // expected-error {{expected ')'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('2'); score ignored}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{to match this '('}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}}
#pragma omp declare variant(foo) match(device={kind(score(foo()) ibm)}) // expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} expected-warning {{'ibm' is not a valid context property for the context selector 'kind' and the context set 'device'; property ignored}} expected-note {{try 'match(implementation={vendor(ibm)})'}} expected-note {{the ignored property spans until here}}
#pragma omp declare variant(foo) match(device={kind(score(5): host), kind(llvm)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('5'); score ignored}} expected-warning {{the context selector 'kind' was used already in the same 'omp declare variant' directive; selector ignored}} expected-note {{the previous context selector 'kind' used here}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(device={kind(score(5): nohost), vendor(llvm)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('5'); score ignored}} expected-warning {{the context selector 'vendor' is not valid for the context set 'device'; selector ignored}} expected-note {{the context selector 'vendor' can be nested in the context set 'implementation'; try 'match(implementation={vendor(property)})'}} expected-note {{the ignored selector spans until here}}
#pragma omp declare variant(foo) match(implementation={extension("aaa")}) // expected-warning {{'aaa' is not a valid context property for the context selector 'extension' and the context set 'implementation'; property ignored}} expected-note {{context property options are: 'match_all' 'match_any' 'match_none'}} expected-note {{the ignored property spans until here}}
int bar(void);
#pragma omp declare variant(foo) match(implementation = {vendor(score(foo) :llvm)}) // expected-warning {{score expressions in the OpenMP context selector need to be constant; foo is not and will be ignored}}
#pragma omp declare variant(foo) match(implementation = {vendor(score(foo()) :llvm)}) // expected-warning {{score expressions in the OpenMP context selector need to be constant; foo() is not and will be ignored}}
#pragma omp declare variant(foo) match(implementation = {vendor(score(<expr>) :llvm)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}}
#pragma omp declare variant(foo) match(user = {condition(foo)}) // expected-error {{the user condition in the OpenMP context selector needs to be constant; foo is not}}
#pragma omp declare variant(foo) match(user = {condition(foo())}) // expected-error {{the user condition in the OpenMP context selector needs to be constant; foo() is not}}
#pragma omp declare variant(foo) match(user = {condition(<expr>)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}} expected-note {{the ignored selector spans until here}}
int score_and_cond_non_const(void);
#pragma omp declare variant(foo) match(construct={teams,parallel,for,simd})
#pragma omp declare variant(foo) match(construct={target teams}) // expected-error {{expected ')'}} expected-warning {{expected '}' after the context selectors for the context set "construct"; '}' assumed}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) match(construct={parallel for}) // expected-error {{expected ')'}} expected-warning {{expected '}' after the context selectors for the context set "construct"; '}' assumed}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}}
#pragma omp declare variant(foo) match(construct={for simd}) // expected-error {{expected ')'}} expected-warning {{expected '}' after the context selectors for the context set "construct"; '}' assumed}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}}
int construct(void);
#pragma omp declare variant(foo) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int a; // expected-error {{'#pragma omp declare variant' can only be applied to functions}}
#pragma omp declare variant(foo) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
#pragma omp threadprivate(a) // expected-error {{'#pragma omp declare variant' can only be applied to functions}}
int var;
#pragma omp threadprivate(var)
#pragma omp declare variant(foo) match(xxx={}) // expected-error {{function declaration is expected after 'declare variant' directive}}
#pragma omp declare // expected-error {{expected an OpenMP directive}}
#pragma omp declare variant(foo) match(xxx={}) // expected-error {{function declaration is expected after 'declare variant' directive}}
#pragma omp declare variant(foo) match(xxx={}) // expected-error {{function declaration is expected after 'declare variant' directive}}
#pragma options align=packed
int main(void);
#pragma omp declare variant(foo) match(implementation={vendor(llvm)}) // expected-error {{function declaration is expected after 'declare variant' directive}}
#pragma omp declare variant(foo) match(implementation={vendor(llvm)}) // expected-error {{function declaration is expected after 'declare variant' directive}}
#pragma init_seg(compiler)
int main(void);
#pragma omp declare variant(foo) match(xxx={}) // expected-error {{single declaration is expected after 'declare variant' directive}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int b, c;
int no_proto();
#pragma omp declare variant(no_proto) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int no_proto_too();
int proto1(int);
#pragma omp declare variant(proto1) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int diff_proto(); // expected-note {{previous declaration is here}}
int diff_proto(double); // expected-error {{conflicting types for 'diff_proto'}}
#pragma omp declare variant(no_proto) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int diff_proto1(double);
int after_use_variant(void);
int after_use(void);
int bar(void) {
return after_use();
}
// expected-error@+1 {{variant in '#pragma omp declare variant' is the same as the base function}}
#pragma omp declare variant (self) \
match(construct={dispatch}, device={arch(arm)})
void self(int n);
void self_test(int n, int d_no) {
#pragma omp dispatch device(d_no) nowait
self(n);
}
#pragma omp declare variant(after_use_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{'#pragma omp declare variant' cannot be applied for function after first usage; the original function might be used}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int after_use(void);
#pragma omp declare variant(after_use_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int defined(void) { return 0; }
int defined1(void) { return 0; }
#pragma omp declare variant(after_use_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{'#pragma omp declare variant' cannot be applied to the function that was defined already; the original function might be used}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
int defined1(void);
int diff_cc_variant(void);
#pragma omp declare variant(diff_cc_variant) match(xxx={}) // expected-error {{variant in '#pragma omp declare variant' with type 'int (void)' is incompatible with type 'int (void) __attribute__((vectorcall))'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
__vectorcall int diff_cc(void);
int diff_ret_variant(void);
#pragma omp declare variant(diff_ret_variant) match(xxx={}) // expected-error {{variant in '#pragma omp declare variant' with type 'int (void)' is incompatible with type 'void (void)'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
void diff_ret(void);
void marked(void);
void not_marked(void);
#pragma omp declare variant(not_marked) match(implementation={vendor(unknown)}, device={kind(cpu)}) // expected-note {{marked as 'declare variant' here}}
void marked_variant(void);
#pragma omp declare variant(marked_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{variant function in '#pragma omp declare variant' is itself marked as '#pragma omp declare variant'}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}}
void marked(void);
#pragma omp declare variant(foo) match(device = {isa("foo")})
int unknown_isa_trait(void);
#pragma omp declare variant(foo) match(device = {isa(foo)})
int unknown_isa_trait2(void);
#pragma omp declare variant(foo) match(device = {kind(fpga), isa(bar)})
int ignored_isa_trait(void);
void caller(void) {
unknown_isa_trait(); // expected-warning {{isa trait 'foo' is not known to the current target; verify the spelling or consider restricting the context selector with the 'arch' selector further}}
unknown_isa_trait2(); // expected-warning {{isa trait 'foo' is not known to the current target; verify the spelling or consider restricting the context selector with the 'arch' selector further}}
ignored_isa_trait();
}
// Unknown arch
#pragma omp begin declare variant match(device={isa(sse2020)}) // expected-warning {{isa trait 'sse2020' is not known to the current target; verify the spelling or consider restricting the context selector with the 'arch' selector further}}
#pragma omp end declare variant
// Unknown arch guarded by arch.
#pragma omp begin declare variant match(device={isa(sse2020), arch(ppc)})
#pragma omp end declare variant
#pragma omp declare variant // expected-error {{function declaration is expected after 'declare variant' directive}}
#pragma omp declare variant // expected-error {{function declaration is expected after 'declare variant' directive}}
// FIXME: If the scores are equivalent we should detect that and allow it.
#pragma omp begin declare variant match(implementation = {vendor(score(2) \
: llvm)})
#pragma omp declare variant(foo) match(implementation = {vendor(score(2) \
: llvm)}) // expected-error@-1 {{nested OpenMP context selector contains duplicated trait 'llvm' in selector 'vendor' and set 'implementation' with different score}}
int conflicting_nested_score(void);
#pragma omp end declare variant
// FIXME: We should build the conjuction of different conditions, see also the score fixme above.
#pragma omp begin declare variant match(user = {condition(1)})
#pragma omp declare variant(foo) match(user = {condition(1)}) // expected-error {{nested user conditions in OpenMP context selector not supported (yet)}}
int conflicting_nested_condition(void);
#pragma omp end declare variant
|
Parser.h | //===--- Parser.h - C Language Parser ---------------------------*- 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 Parser interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_PARSE_PARSER_H
#define LLVM_CLANG_PARSE_PARSER_H
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Availability.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SaveAndRestore.h"
#include <memory>
#include <stack>
namespace clang {
class PragmaHandler;
class Scope;
class BalancedDelimiterTracker;
class CorrectionCandidateCallback;
class DeclGroupRef;
class DiagnosticBuilder;
struct LoopHint;
class Parser;
class ParsingDeclRAIIObject;
class ParsingDeclSpec;
class ParsingDeclarator;
class ParsingFieldDeclarator;
class ColonProtectionRAIIObject;
class InMessageExpressionRAIIObject;
class PoisonSEHIdentifiersRAIIObject;
class OMPClause;
class ObjCTypeParamList;
class ObjCTypeParameter;
/// Parser - This implements a parser for the C family of languages. After
/// parsing units of the grammar, productions are invoked to handle whatever has
/// been read.
///
class Parser : public CodeCompletionHandler {
friend class ColonProtectionRAIIObject;
friend class ParsingOpenMPDirectiveRAII;
friend class InMessageExpressionRAIIObject;
friend class PoisonSEHIdentifiersRAIIObject;
friend class ObjCDeclContextSwitch;
friend class ParenBraceBracketBalancer;
friend class BalancedDelimiterTracker;
Preprocessor &PP;
/// Tok - The current token we are peeking ahead. All parsing methods assume
/// that this is valid.
Token Tok;
// PrevTokLocation - The location of the token we previously
// consumed. This token is used for diagnostics where we expected to
// see a token following another token (e.g., the ';' at the end of
// a statement).
SourceLocation PrevTokLocation;
/// Tracks an expected type for the current token when parsing an expression.
/// Used by code completion for ranking.
PreferredTypeBuilder PreferredType;
unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
unsigned short MisplacedModuleBeginCount = 0;
/// Actions - These are the callbacks we invoke as we parse various constructs
/// in the file.
Sema &Actions;
DiagnosticsEngine &Diags;
/// ScopeCache - Cache scopes to reduce malloc traffic.
enum { ScopeCacheSize = 16 };
unsigned NumCachedScopes;
Scope *ScopeCache[ScopeCacheSize];
/// Identifiers used for SEH handling in Borland. These are only
/// allowed in particular circumstances
// __except block
IdentifierInfo *Ident__exception_code,
*Ident___exception_code,
*Ident_GetExceptionCode;
// __except filter expression
IdentifierInfo *Ident__exception_info,
*Ident___exception_info,
*Ident_GetExceptionInfo;
// __finally
IdentifierInfo *Ident__abnormal_termination,
*Ident___abnormal_termination,
*Ident_AbnormalTermination;
/// Contextual keywords for Microsoft extensions.
IdentifierInfo *Ident__except;
mutable IdentifierInfo *Ident_sealed;
/// Ident_super - IdentifierInfo for "super", to support fast
/// comparison.
IdentifierInfo *Ident_super;
/// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
/// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
IdentifierInfo *Ident_vector;
IdentifierInfo *Ident_bool;
/// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
/// Only present if AltiVec enabled.
IdentifierInfo *Ident_pixel;
/// Objective-C contextual keywords.
IdentifierInfo *Ident_instancetype;
/// Identifier for "introduced".
IdentifierInfo *Ident_introduced;
/// Identifier for "deprecated".
IdentifierInfo *Ident_deprecated;
/// Identifier for "obsoleted".
IdentifierInfo *Ident_obsoleted;
/// Identifier for "unavailable".
IdentifierInfo *Ident_unavailable;
/// Identifier for "message".
IdentifierInfo *Ident_message;
/// Identifier for "strict".
IdentifierInfo *Ident_strict;
/// Identifier for "replacement".
IdentifierInfo *Ident_replacement;
/// Identifiers used by the 'external_source_symbol' attribute.
IdentifierInfo *Ident_language, *Ident_defined_in,
*Ident_generated_declaration;
/// C++11 contextual keywords.
mutable IdentifierInfo *Ident_final;
mutable IdentifierInfo *Ident_GNU_final;
mutable IdentifierInfo *Ident_override;
// C++2a contextual keywords.
mutable IdentifierInfo *Ident_import;
mutable IdentifierInfo *Ident_module;
// C++ type trait keywords that can be reverted to identifiers and still be
// used as type traits.
llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
std::unique_ptr<PragmaHandler> AlignHandler;
std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
std::unique_ptr<PragmaHandler> OptionsHandler;
std::unique_ptr<PragmaHandler> PackHandler;
std::unique_ptr<PragmaHandler> MSStructHandler;
std::unique_ptr<PragmaHandler> UnusedHandler;
std::unique_ptr<PragmaHandler> WeakHandler;
std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
std::unique_ptr<PragmaHandler> FPContractHandler;
std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
std::unique_ptr<PragmaHandler> OpenMPHandler;
std::unique_ptr<PragmaHandler> PCSectionHandler;
std::unique_ptr<PragmaHandler> MSCommentHandler;
std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
std::unique_ptr<PragmaHandler> MSPointersToMembers;
std::unique_ptr<PragmaHandler> MSVtorDisp;
std::unique_ptr<PragmaHandler> MSInitSeg;
std::unique_ptr<PragmaHandler> MSDataSeg;
std::unique_ptr<PragmaHandler> MSBSSSeg;
std::unique_ptr<PragmaHandler> MSConstSeg;
std::unique_ptr<PragmaHandler> MSCodeSeg;
std::unique_ptr<PragmaHandler> MSSection;
std::unique_ptr<PragmaHandler> MSRuntimeChecks;
std::unique_ptr<PragmaHandler> MSIntrinsic;
std::unique_ptr<PragmaHandler> MSOptimize;
std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
std::unique_ptr<PragmaHandler> OptimizeHandler;
std::unique_ptr<PragmaHandler> LoopHintHandler;
std::unique_ptr<PragmaHandler> UnrollHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
std::unique_ptr<PragmaHandler> STDCFENVHandler;
std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
std::unique_ptr<PragmaHandler> STDCUnknownHandler;
std::unique_ptr<PragmaHandler> AttributePragmaHandler;
std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
std::unique_ptr<CommentHandler> CommentSemaHandler;
/// Whether the '>' token acts as an operator or not. This will be
/// true except when we are parsing an expression within a C++
/// template argument list, where the '>' closes the template
/// argument list.
bool GreaterThanIsOperator;
/// ColonIsSacred - When this is false, we aggressively try to recover from
/// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
/// safe in case statements and a few other things. This is managed by the
/// ColonProtectionRAIIObject RAII object.
bool ColonIsSacred;
/// Parsing OpenMP directive mode.
bool OpenMPDirectiveParsing = false;
/// When true, we are directly inside an Objective-C message
/// send expression.
///
/// This is managed by the \c InMessageExpressionRAIIObject class, and
/// should not be set directly.
bool InMessageExpression;
/// Gets set to true after calling ProduceSignatureHelp, it is for a
/// workaround to make sure ProduceSignatureHelp is only called at the deepest
/// function call.
bool CalledSignatureHelp = false;
/// The "depth" of the template parameters currently being parsed.
unsigned TemplateParameterDepth;
/// RAII class that manages the template parameter depth.
class TemplateParameterDepthRAII {
unsigned &Depth;
unsigned AddedLevels;
public:
explicit TemplateParameterDepthRAII(unsigned &Depth)
: Depth(Depth), AddedLevels(0) {}
~TemplateParameterDepthRAII() {
Depth -= AddedLevels;
}
void operator++() {
++Depth;
++AddedLevels;
}
void addDepth(unsigned D) {
Depth += D;
AddedLevels += D;
}
void setAddedDepth(unsigned D) {
Depth = Depth - AddedLevels + D;
AddedLevels = D;
}
unsigned getDepth() const { return Depth; }
unsigned getOriginalDepth() const { return Depth - AddedLevels; }
};
/// Factory object for creating ParsedAttr objects.
AttributeFactory AttrFactory;
/// Gathers and cleans up TemplateIdAnnotations when parsing of a
/// top-level declaration is finished.
SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
/// Identifiers which have been declared within a tentative parse.
SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
/// Tracker for '<' tokens that might have been intended to be treated as an
/// angle bracket instead of a less-than comparison.
///
/// This happens when the user intends to form a template-id, but typoes the
/// template-name or forgets a 'template' keyword for a dependent template
/// name.
///
/// We track these locations from the point where we see a '<' with a
/// name-like expression on its left until we see a '>' or '>>' that might
/// match it.
struct AngleBracketTracker {
/// Flags used to rank candidate template names when there is more than one
/// '<' in a scope.
enum Priority : unsigned short {
/// A non-dependent name that is a potential typo for a template name.
PotentialTypo = 0x0,
/// A dependent name that might instantiate to a template-name.
DependentName = 0x2,
/// A space appears before the '<' token.
SpaceBeforeLess = 0x0,
/// No space before the '<' token
NoSpaceBeforeLess = 0x1,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
};
struct Loc {
Expr *TemplateName;
SourceLocation LessLoc;
AngleBracketTracker::Priority Priority;
unsigned short ParenCount, BracketCount, BraceCount;
bool isActive(Parser &P) const {
return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
P.BraceCount == BraceCount;
}
bool isActiveOrNested(Parser &P) const {
return isActive(P) || P.ParenCount > ParenCount ||
P.BracketCount > BracketCount || P.BraceCount > BraceCount;
}
};
SmallVector<Loc, 8> Locs;
/// Add an expression that might have been intended to be a template name.
/// In the case of ambiguity, we arbitrarily select the innermost such
/// expression, for example in 'foo < bar < baz', 'bar' is the current
/// candidate. No attempt is made to track that 'foo' is also a candidate
/// for the case where we see a second suspicious '>' token.
void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
Priority Prio) {
if (!Locs.empty() && Locs.back().isActive(P)) {
if (Locs.back().Priority <= Prio) {
Locs.back().TemplateName = TemplateName;
Locs.back().LessLoc = LessLoc;
Locs.back().Priority = Prio;
}
} else {
Locs.push_back({TemplateName, LessLoc, Prio,
P.ParenCount, P.BracketCount, P.BraceCount});
}
}
/// Mark the current potential missing template location as having been
/// handled (this happens if we pass a "corresponding" '>' or '>>' token
/// or leave a bracket scope).
void clear(Parser &P) {
while (!Locs.empty() && Locs.back().isActiveOrNested(P))
Locs.pop_back();
}
/// Get the current enclosing expression that might hve been intended to be
/// a template name.
Loc *getCurrent(Parser &P) {
if (!Locs.empty() && Locs.back().isActive(P))
return &Locs.back();
return nullptr;
}
};
AngleBracketTracker AngleBrackets;
IdentifierInfo *getSEHExceptKeyword();
/// True if we are within an Objective-C container while parsing C-like decls.
///
/// This is necessary because Sema thinks we have left the container
/// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
/// be NULL.
bool ParsingInObjCContainer;
/// Whether to skip parsing of function bodies.
///
/// This option can be used, for example, to speed up searches for
/// declarations/definitions when indexing.
bool SkipFunctionBodies;
/// The location of the expression statement that is being parsed right now.
/// Used to determine if an expression that is being parsed is a statement or
/// just a regular sub-expression.
SourceLocation ExprStatementTokLoc;
/// Flags describing a context in which we're parsing a statement.
enum class ParsedStmtContext {
/// This context permits declarations in language modes where declarations
/// are not statements.
AllowDeclarationsInC = 0x1,
/// This context permits standalone OpenMP directives.
AllowStandaloneOpenMPDirectives = 0x2,
/// This context is at the top level of a GNU statement expression.
InStmtExpr = 0x4,
/// The context of a regular substatement.
SubStmt = 0,
/// The context of a compound-statement.
Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
};
/// Act on an expression statement that might be the last statement in a
/// GNU statement expression. Checks whether we are actually at the end of
/// a statement expression and builds a suitable expression statement.
StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
public:
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
~Parser() override;
const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
Preprocessor &getPreprocessor() const { return PP; }
Sema &getActions() const { return Actions; }
AttributeFactory &getAttrFactory() { return AttrFactory; }
const Token &getCurToken() const { return Tok; }
Scope *getCurScope() const { return Actions.getCurScope(); }
void incrementMSManglingNumber() const {
return Actions.incrementMSManglingNumber();
}
Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
// Type forwarding. All of these are statically 'void*', but they may all be
// different actual classes based on the actions in place.
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
typedef Sema::FullExprArg FullExprArg;
// Parsing methods.
/// Initialize - Warm up the parser.
///
void Initialize();
/// Parse the first top-level declaration in a translation unit.
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
/// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
/// the EOF was encountered.
bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false);
bool ParseTopLevelDecl() {
DeclGroupPtrTy Result;
return ParseTopLevelDecl(Result);
}
/// ConsumeToken - Consume the current 'peek token' and lex the next one.
/// This does not work with special tokens: string literals, code completion,
/// annotation tokens and balanced tokens must be handled using the specific
/// consume methods.
/// Returns the location of the consumed token.
SourceLocation ConsumeToken() {
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
bool TryConsumeToken(tok::TokenKind Expected) {
if (Tok.isNot(Expected))
return false;
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return true;
}
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
if (!TryConsumeToken(Expected))
return false;
Loc = PrevTokLocation;
return true;
}
/// ConsumeAnyToken - Dispatch to the right Consume* method based on the
/// current token type. This should only be used in cases where the type of
/// the token really isn't known, e.g. in error recovery.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
if (isTokenParen())
return ConsumeParen();
if (isTokenBracket())
return ConsumeBracket();
if (isTokenBrace())
return ConsumeBrace();
if (isTokenStringLiteral())
return ConsumeStringToken();
if (Tok.is(tok::code_completion))
return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
: handleUnexpectedCodeCompletionToken();
if (Tok.isAnnotation())
return ConsumeAnnotationToken();
return ConsumeToken();
}
SourceLocation getEndOfPreviousToken() {
return PP.getLocForEndOfToken(PrevTokLocation);
}
/// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
/// to the given nullability kind.
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
return Actions.getNullabilityKeyword(nullability);
}
private:
//===--------------------------------------------------------------------===//
// Low-Level token peeking and consumption methods.
//
/// isTokenParen - Return true if the cur token is '(' or ')'.
bool isTokenParen() const {
return Tok.isOneOf(tok::l_paren, tok::r_paren);
}
/// isTokenBracket - Return true if the cur token is '[' or ']'.
bool isTokenBracket() const {
return Tok.isOneOf(tok::l_square, tok::r_square);
}
/// isTokenBrace - Return true if the cur token is '{' or '}'.
bool isTokenBrace() const {
return Tok.isOneOf(tok::l_brace, tok::r_brace);
}
/// isTokenStringLiteral - True if this token is a string-literal.
bool isTokenStringLiteral() const {
return tok::isStringLiteral(Tok.getKind());
}
/// isTokenSpecial - True if this token requires special consumption methods.
bool isTokenSpecial() const {
return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
}
/// Returns true if the current token is '=' or is a type of '='.
/// For typos, give a fixit to '='
bool isTokenEqualOrEqualTypo();
/// Return the current token to the token stream and make the given
/// token the current token.
void UnconsumeToken(Token &Consumed) {
Token Next = Tok;
PP.EnterToken(Consumed, /*IsReinject*/true);
PP.Lex(Tok);
PP.EnterToken(Next, /*IsReinject*/true);
}
SourceLocation ConsumeAnnotationToken() {
assert(Tok.isAnnotation() && "wrong consume method");
SourceLocation Loc = Tok.getLocation();
PrevTokLocation = Tok.getAnnotationEndLoc();
PP.Lex(Tok);
return Loc;
}
/// ConsumeParen - This consume method keeps the paren count up-to-date.
///
SourceLocation ConsumeParen() {
assert(isTokenParen() && "wrong consume method");
if (Tok.getKind() == tok::l_paren)
++ParenCount;
else if (ParenCount) {
AngleBrackets.clear(*this);
--ParenCount; // Don't let unbalanced )'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBracket - This consume method keeps the bracket count up-to-date.
///
SourceLocation ConsumeBracket() {
assert(isTokenBracket() && "wrong consume method");
if (Tok.getKind() == tok::l_square)
++BracketCount;
else if (BracketCount) {
AngleBrackets.clear(*this);
--BracketCount; // Don't let unbalanced ]'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBrace - This consume method keeps the brace count up-to-date.
///
SourceLocation ConsumeBrace() {
assert(isTokenBrace() && "wrong consume method");
if (Tok.getKind() == tok::l_brace)
++BraceCount;
else if (BraceCount) {
AngleBrackets.clear(*this);
--BraceCount; // Don't let unbalanced }'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeStringToken - Consume the current 'peek token', lexing a new one
/// and returning the token kind. This method is specific to strings, as it
/// handles string literal concatenation, as per C99 5.1.1.2, translation
/// phase #6.
SourceLocation ConsumeStringToken() {
assert(isTokenStringLiteral() &&
"Should only consume string literals with this method");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// Consume the current code-completion token.
///
/// This routine can be called to consume the code-completion token and
/// continue processing in special cases where \c cutOffParsing() isn't
/// desired, such as token caching or completion with lookahead.
SourceLocation ConsumeCodeCompletionToken() {
assert(Tok.is(tok::code_completion));
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
///\ brief When we are consuming a code-completion token without having
/// matched specific position in the grammar, provide code-completion results
/// based on context.
///
/// \returns the source location of the code-completion token.
SourceLocation handleUnexpectedCodeCompletionToken();
/// Abruptly cut off parsing; mainly used when we have reached the
/// code-completion point.
void cutOffParsing() {
if (PP.isCodeCompletionEnabled())
PP.setCodeCompletionReached();
// Cut off parsing by acting as if we reached the end-of-file.
Tok.setKind(tok::eof);
}
/// Determine if we're at the end of the file or at a transition
/// between modules.
bool isEofOrEom() {
tok::TokenKind Kind = Tok.getKind();
return Kind == tok::eof || Kind == tok::annot_module_begin ||
Kind == tok::annot_module_end || Kind == tok::annot_module_include;
}
/// Checks if the \p Level is valid for use in a fold expression.
bool isFoldOperator(prec::Level Level) const;
/// Checks if the \p Kind is a valid operator for fold expressions.
bool isFoldOperator(tok::TokenKind Kind) const;
/// Initialize all pragma handlers.
void initializePragmaHandlers();
/// Destroy and reset all pragma handlers.
void resetPragmaHandlers();
/// Handle the annotation token produced for #pragma unused(...)
void HandlePragmaUnused();
/// Handle the annotation token produced for
/// #pragma GCC visibility...
void HandlePragmaVisibility();
/// Handle the annotation token produced for
/// #pragma pack...
void HandlePragmaPack();
/// Handle the annotation token produced for
/// #pragma ms_struct...
void HandlePragmaMSStruct();
/// Handle the annotation token produced for
/// #pragma comment...
void HandlePragmaMSComment();
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
void HandlePragmaMSPragma();
bool HandlePragmaMSSection(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSSegment(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSInitSeg(StringRef PragmaName,
SourceLocation PragmaLocation);
/// Handle the annotation token produced for
/// #pragma align...
void HandlePragmaAlign();
/// Handle the annotation token produced for
/// #pragma clang __debug dump...
void HandlePragmaDump();
/// Handle the annotation token produced for
/// #pragma weak id...
void HandlePragmaWeak();
/// Handle the annotation token produced for
/// #pragma weak id = id...
void HandlePragmaWeakAlias();
/// Handle the annotation token produced for
/// #pragma redefine_extname...
void HandlePragmaRedefineExtname();
/// Handle the annotation token produced for
/// #pragma STDC FP_CONTRACT...
void HandlePragmaFPContract();
/// Handle the annotation token produced for
/// #pragma STDC FENV_ACCESS...
void HandlePragmaFEnvAccess();
/// \brief Handle the annotation token produced for
/// #pragma clang fp ...
void HandlePragmaFP();
/// Handle the annotation token produced for
/// #pragma OPENCL EXTENSION...
void HandlePragmaOpenCLExtension();
/// Handle the annotation token produced for
/// #pragma clang __debug captured
StmtResult HandlePragmaCaptured();
/// Handle the annotation token produced for
/// #pragma clang loop and #pragma unroll.
bool HandlePragmaLoopHint(LoopHint &Hint);
bool ParsePragmaAttributeSubjectMatchRuleSet(
attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
void HandlePragmaAttribute();
/// GetLookAheadToken - This peeks ahead N tokens and returns that token
/// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
/// returns the token after Tok, etc.
///
/// Note that this differs from the Preprocessor's LookAhead method, because
/// the Parser always has one token lexed that the preprocessor doesn't.
///
const Token &GetLookAheadToken(unsigned N) {
if (N == 0 || Tok.is(tok::eof)) return Tok;
return PP.LookAhead(N-1);
}
public:
/// NextToken - This peeks ahead one token and returns it without
/// consuming it.
const Token &NextToken() {
return PP.LookAhead(0);
}
/// getTypeAnnotation - Read a parsed type out of an annotation token.
static ParsedType getTypeAnnotation(const Token &Tok) {
return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
}
private:
static void setTypeAnnotation(Token &Tok, ParsedType T) {
Tok.setAnnotationValue(T.getAsOpaquePtr());
}
static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
return static_cast<NamedDecl*>(Tok.getAnnotationValue());
}
static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
Tok.setAnnotationValue(ND);
}
static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
}
static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
Tok.setAnnotationValue(ND);
}
/// Read an already-translated primary expression out of an annotation
/// token.
static ExprResult getExprAnnotation(const Token &Tok) {
return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
}
/// Set the primary expression corresponding to the given annotation
/// token.
static void setExprAnnotation(Token &Tok, ExprResult ER) {
Tok.setAnnotationValue(ER.getAsOpaquePointer());
}
public:
// If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
// find a type name by attempting typo correction.
bool TryAnnotateTypeOrScopeToken();
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
bool IsNewScope);
bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
bool MightBeCXXScopeToken() {
return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
(Tok.is(tok::annot_template_id) &&
NextToken().is(tok::coloncolon)) ||
Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super);
}
bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
}
private:
enum AnnotatedNameKind {
/// Annotation has failed and emitted an error.
ANK_Error,
/// The identifier is a tentatively-declared name.
ANK_TentativeDecl,
/// The identifier is a template name. FIXME: Add an annotation for that.
ANK_TemplateName,
/// The identifier can't be resolved.
ANK_Unresolved,
/// Annotation was successful.
ANK_Success
};
AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr);
/// Push a tok::annot_cxxscope token onto the token stream.
void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
/// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
/// replacing them with the non-context-sensitive keywords. This returns
/// true if the token was replaced.
bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
return false;
if (Tok.getIdentifierInfo() != Ident_vector &&
Tok.getIdentifierInfo() != Ident_bool &&
(!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
return false;
return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
}
/// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
/// identifier token, replacing it with the non-context-sensitive __vector.
/// This returns true if the token was replaced.
bool TryAltiVecVectorToken() {
if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
Tok.getIdentifierInfo() != Ident_vector) return false;
return TryAltiVecVectorTokenOutOfLine();
}
bool TryAltiVecVectorTokenOutOfLine();
bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid);
/// Returns true if the current token is the identifier 'instancetype'.
///
/// Should only be used in Objective-C language modes.
bool isObjCInstancetype() {
assert(getLangOpts().ObjC);
if (Tok.isAnnotation())
return false;
if (!Ident_instancetype)
Ident_instancetype = PP.getIdentifierInfo("instancetype");
return Tok.getIdentifierInfo() == Ident_instancetype;
}
/// TryKeywordIdentFallback - For compatibility with system headers using
/// keywords as identifiers, attempt to convert the current token to an
/// identifier and optionally disable the keyword for the remainder of the
/// translation unit. This returns false if the token was not replaced,
/// otherwise emits a diagnostic and returns true.
bool TryKeywordIdentFallback(bool DisableKeyword);
/// Get the TemplateIdAnnotation from the token.
TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
/// TentativeParsingAction - An object that is used as a kind of "tentative
/// parsing transaction". It gets instantiated to mark the token position and
/// after the token consumption is done, Commit() or Revert() is called to
/// either "commit the consumed tokens" or revert to the previously marked
/// token position. Example:
///
/// TentativeParsingAction TPA(*this);
/// ConsumeToken();
/// ....
/// TPA.Revert();
///
class TentativeParsingAction {
Parser &P;
PreferredTypeBuilder PrevPreferredType;
Token PrevTok;
size_t PrevTentativelyDeclaredIdentifierCount;
unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
bool isActive;
public:
explicit TentativeParsingAction(Parser& p) : P(p) {
PrevPreferredType = P.PreferredType;
PrevTok = P.Tok;
PrevTentativelyDeclaredIdentifierCount =
P.TentativelyDeclaredIdentifiers.size();
PrevParenCount = P.ParenCount;
PrevBracketCount = P.BracketCount;
PrevBraceCount = P.BraceCount;
P.PP.EnableBacktrackAtThisPos();
isActive = true;
}
void Commit() {
assert(isActive && "Parsing action was finished!");
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.PP.CommitBacktrackedTokens();
isActive = false;
}
void Revert() {
assert(isActive && "Parsing action was finished!");
P.PP.Backtrack();
P.PreferredType = PrevPreferredType;
P.Tok = PrevTok;
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.ParenCount = PrevParenCount;
P.BracketCount = PrevBracketCount;
P.BraceCount = PrevBraceCount;
isActive = false;
}
~TentativeParsingAction() {
assert(!isActive && "Forgot to call Commit or Revert!");
}
};
/// A TentativeParsingAction that automatically reverts in its destructor.
/// Useful for disambiguation parses that will always be reverted.
class RevertingTentativeParsingAction
: private Parser::TentativeParsingAction {
public:
RevertingTentativeParsingAction(Parser &P)
: Parser::TentativeParsingAction(P) {}
~RevertingTentativeParsingAction() { Revert(); }
};
class UnannotatedTentativeParsingAction;
/// ObjCDeclContextSwitch - An object used to switch context from
/// an objective-c decl context to its enclosing decl context and
/// back.
class ObjCDeclContextSwitch {
Parser &P;
Decl *DC;
SaveAndRestore<bool> WithinObjCContainer;
public:
explicit ObjCDeclContextSwitch(Parser &p)
: P(p), DC(p.getObjCDeclContext()),
WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
if (DC)
P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
}
~ObjCDeclContextSwitch() {
if (DC)
P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
}
};
/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
/// input. If so, it is consumed and false is returned.
///
/// If a trivial punctuator misspelling is encountered, a FixIt error
/// diagnostic is issued and false is returned after recovery.
///
/// If the input is malformed, this emits the specified diagnostic and true is
/// returned.
bool ExpectAndConsume(tok::TokenKind ExpectedTok,
unsigned Diag = diag::err_expected,
StringRef DiagMsg = "");
/// The parser expects a semicolon and, if present, will consume it.
///
/// If the next token is not a semicolon, this emits the specified diagnostic,
/// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
/// to the semicolon, consumes that extra token.
bool ExpectAndConsumeSemi(unsigned DiagID);
/// The kind of extra semi diagnostic to emit.
enum ExtraSemiKind {
OutsideFunction = 0,
InsideStruct = 1,
InstanceVariableList = 2,
AfterMemberFunctionDefinition = 3
};
/// Consume any extra semi-colons until the end of the line.
void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
/// Return false if the next token is an identifier. An 'expected identifier'
/// error is emitted otherwise.
///
/// The parser tries to recover from the error by checking if the next token
/// is a C++ keyword when parsing Objective-C++. Return false if the recovery
/// was successful.
bool expectIdentifier();
public:
//===--------------------------------------------------------------------===//
// Scope manipulation
/// ParseScope - Introduces a new scope for parsing. The kind of
/// scope is determined by ScopeFlags. Objects of this type should
/// be created on the stack to coincide with the position where the
/// parser enters the new scope, and this object's constructor will
/// create that new scope. Similarly, once the object is destroyed
/// the parser will exit the scope.
class ParseScope {
Parser *Self;
ParseScope(const ParseScope &) = delete;
void operator=(const ParseScope &) = delete;
public:
// ParseScope - Construct a new object to manage a scope in the
// parser Self where the new Scope is created with the flags
// ScopeFlags, but only when we aren't about to enter a compound statement.
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
bool BeforeCompoundStmt = false)
: Self(Self) {
if (EnteredScope && !BeforeCompoundStmt)
Self->EnterScope(ScopeFlags);
else {
if (BeforeCompoundStmt)
Self->incrementMSManglingNumber();
this->Self = nullptr;
}
}
// Exit - Exit the scope associated with this object now, rather
// than waiting until the object is destroyed.
void Exit() {
if (Self) {
Self->ExitScope();
Self = nullptr;
}
}
~ParseScope() {
Exit();
}
};
/// EnterScope - Start a new scope.
void EnterScope(unsigned ScopeFlags);
/// ExitScope - Pop a scope off the scope stack.
void ExitScope();
private:
/// RAII object used to modify the scope flags for the current scope.
class ParseScopeFlags {
Scope *CurScope;
unsigned OldFlags;
ParseScopeFlags(const ParseScopeFlags &) = delete;
void operator=(const ParseScopeFlags &) = delete;
public:
ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
~ParseScopeFlags();
};
//===--------------------------------------------------------------------===//
// Diagnostic Emission and Error recovery.
public:
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
DiagnosticBuilder Diag(unsigned DiagID) {
return Diag(Tok, DiagID);
}
private:
void SuggestParentheses(SourceLocation Loc, unsigned DK,
SourceRange ParenRange);
void CheckNestedObjCContexts(SourceLocation AtLoc);
public:
/// Control flags for SkipUntil functions.
enum SkipUntilFlags {
StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
/// Stop skipping at specified token, but don't skip the token itself
StopBeforeMatch = 1 << 1,
StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
};
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
SkipUntilFlags R) {
return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
static_cast<unsigned>(R));
}
/// SkipUntil - Read tokens until we get to the specified token, then consume
/// it (unless StopBeforeMatch is specified). Because we cannot guarantee
/// that the token will ever occur, this skips to the next token, or to some
/// likely good stopping point. If Flags has StopAtSemi flag, skipping will
/// stop at a ';' character. Balances (), [], and {} delimiter tokens while
/// skipping.
///
/// If SkipUntil finds the specified token, it returns true, otherwise it
/// returns false.
bool SkipUntil(tok::TokenKind T,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
return SkipUntil(llvm::makeArrayRef(T), Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2, T3};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
/// SkipMalformedDecl - Read tokens until we get to some likely good stopping
/// point for skipping past a simple-declaration.
void SkipMalformedDecl();
/// The location of the first statement inside an else that might
/// have a missleading indentation. If there is no
/// MisleadingIndentationChecker on an else active, this location is invalid.
SourceLocation MisleadingIndentationElseLoc;
private:
//===--------------------------------------------------------------------===//
// Lexing and parsing of C++ inline methods.
struct ParsingClass;
/// [class.mem]p1: "... the class is regarded as complete within
/// - function bodies
/// - default arguments
/// - exception-specifications (TODO: C++0x)
/// - and brace-or-equal-initializers for non-static data members
/// (including such things in nested classes)."
/// LateParsedDeclarations build the tree of those elements so they can
/// be parsed after parsing the top-level class.
class LateParsedDeclaration {
public:
virtual ~LateParsedDeclaration();
virtual void ParseLexedMethodDeclarations();
virtual void ParseLexedMemberInitializers();
virtual void ParseLexedMethodDefs();
virtual void ParseLexedAttributes();
virtual void ParseLexedPragmas();
};
/// Inner node of the LateParsedDeclaration tree that parses
/// all its members recursively.
class LateParsedClass : public LateParsedDeclaration {
public:
LateParsedClass(Parser *P, ParsingClass *C);
~LateParsedClass() override;
void ParseLexedMethodDeclarations() override;
void ParseLexedMemberInitializers() override;
void ParseLexedMethodDefs() override;
void ParseLexedAttributes() override;
void ParseLexedPragmas() override;
private:
Parser *Self;
ParsingClass *Class;
};
/// Contains the lexed tokens of an attribute with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
/// FIXME: Perhaps we should change the name of LateParsedDeclaration to
/// LateParsedTokens.
struct LateParsedAttribute : public LateParsedDeclaration {
Parser *Self;
CachedTokens Toks;
IdentifierInfo &AttrName;
IdentifierInfo *MacroII = nullptr;
SourceLocation AttrNameLoc;
SmallVector<Decl*, 2> Decls;
explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
SourceLocation Loc)
: Self(P), AttrName(Name), AttrNameLoc(Loc) {}
void ParseLexedAttributes() override;
void addDecl(Decl *D) { Decls.push_back(D); }
};
/// Contains the lexed tokens of a pragma with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
class LateParsedPragma : public LateParsedDeclaration {
Parser *Self = nullptr;
AccessSpecifier AS = AS_none;
CachedTokens Toks;
public:
explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
: Self(P), AS(AS) {}
void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
const CachedTokens &toks() const { return Toks; }
AccessSpecifier getAccessSpecifier() const { return AS; }
void ParseLexedPragmas() override;
};
// A list of late-parsed attributes. Used by ParseGNUAttributes.
class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
public:
LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
bool parseSoon() { return ParseSoon; }
private:
bool ParseSoon; // Are we planning to parse these shortly after creation?
};
/// Contains the lexed tokens of a member function definition
/// which needs to be parsed at the end of the class declaration
/// after parsing all other member declarations.
struct LexedMethod : public LateParsedDeclaration {
Parser *Self;
Decl *D;
CachedTokens Toks;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
explicit LexedMethod(Parser* P, Decl *MD)
: Self(P), D(MD), TemplateScope(false) {}
void ParseLexedMethodDefs() override;
};
/// LateParsedDefaultArgument - Keeps track of a parameter that may
/// have a default argument that cannot be parsed yet because it
/// occurs within a member function declaration inside the class
/// (C++ [class.mem]p2).
struct LateParsedDefaultArgument {
explicit LateParsedDefaultArgument(Decl *P,
std::unique_ptr<CachedTokens> Toks = nullptr)
: Param(P), Toks(std::move(Toks)) { }
/// Param - The parameter declaration for this parameter.
Decl *Param;
/// Toks - The sequence of tokens that comprises the default
/// argument expression, not including the '=' or the terminating
/// ')' or ','. This will be NULL for parameters that have no
/// default argument.
std::unique_ptr<CachedTokens> Toks;
};
/// LateParsedMethodDeclaration - A method declaration inside a class that
/// contains at least one entity whose parsing needs to be delayed
/// until the class itself is completely-defined, such as a default
/// argument (C++ [class.mem]p2).
struct LateParsedMethodDeclaration : public LateParsedDeclaration {
explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
: Self(P), Method(M), TemplateScope(false),
ExceptionSpecTokens(nullptr) {}
void ParseLexedMethodDeclarations() override;
Parser* Self;
/// Method - The method declaration.
Decl *Method;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
/// DefaultArgs - Contains the parameters of the function and
/// their default arguments. At least one of the parameters will
/// have a default argument, but all of the parameters of the
/// method will be stored so that they can be reintroduced into
/// scope at the appropriate times.
SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
/// The set of tokens that make up an exception-specification that
/// has not yet been parsed.
CachedTokens *ExceptionSpecTokens;
};
/// LateParsedMemberInitializer - An initializer for a non-static class data
/// member whose parsing must to be delayed until the class is completely
/// defined (C++11 [class.mem]p2).
struct LateParsedMemberInitializer : public LateParsedDeclaration {
LateParsedMemberInitializer(Parser *P, Decl *FD)
: Self(P), Field(FD) { }
void ParseLexedMemberInitializers() override;
Parser *Self;
/// Field - The field declaration.
Decl *Field;
/// CachedTokens - The sequence of tokens that comprises the initializer,
/// including any leading '='.
CachedTokens Toks;
};
/// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
/// C++ class, its method declarations that contain parts that won't be
/// parsed until after the definition is completed (C++ [class.mem]p2),
/// the method declarations and possibly attached inline definitions
/// will be stored here with the tokens that will be parsed to create those
/// entities.
typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
/// Representation of a class that has been parsed, including
/// any member function declarations or definitions that need to be
/// parsed after the corresponding top-level class is complete.
struct ParsingClass {
ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
: TopLevelClass(TopLevelClass), TemplateScope(false),
IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
/// Whether this is a "top-level" class, meaning that it is
/// not nested within another class.
bool TopLevelClass : 1;
/// Whether this class had an associated template
/// scope. When true, TagOrTemplate is a template declaration;
/// otherwise, it is a tag declaration.
bool TemplateScope : 1;
/// Whether this class is an __interface.
bool IsInterface : 1;
/// The class or class template whose definition we are parsing.
Decl *TagOrTemplate;
/// LateParsedDeclarations - Method declarations, inline definitions and
/// nested classes that contain pieces whose parsing will be delayed until
/// the top-level class is fully defined.
LateParsedDeclarationsContainer LateParsedDeclarations;
};
/// The stack of classes that is currently being
/// parsed. Nested and local classes will be pushed onto this stack
/// when they are parsed, and removed afterward.
std::stack<ParsingClass *> ClassStack;
ParsingClass &getCurrentClass() {
assert(!ClassStack.empty() && "No lexed method stacks!");
return *ClassStack.top();
}
/// RAII object used to manage the parsing of a class definition.
class ParsingClassDefinition {
Parser &P;
bool Popped;
Sema::ParsingClassState State;
public:
ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
bool IsInterface)
: P(P), Popped(false),
State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
}
/// Pop this class of the stack.
void Pop() {
assert(!Popped && "Nested class has already been popped");
Popped = true;
P.PopParsingClass(State);
}
~ParsingClassDefinition() {
if (!Popped)
P.PopParsingClass(State);
}
};
/// Contains information about any template-specific
/// information that has been parsed prior to parsing declaration
/// specifiers.
struct ParsedTemplateInfo {
ParsedTemplateInfo()
: Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
bool isSpecialization,
bool lastParameterListWasEmpty = false)
: Kind(isSpecialization? ExplicitSpecialization : Template),
TemplateParams(TemplateParams),
LastParameterListWasEmpty(lastParameterListWasEmpty) { }
explicit ParsedTemplateInfo(SourceLocation ExternLoc,
SourceLocation TemplateLoc)
: Kind(ExplicitInstantiation), TemplateParams(nullptr),
ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
LastParameterListWasEmpty(false){ }
/// The kind of template we are parsing.
enum {
/// We are not parsing a template at all.
NonTemplate = 0,
/// We are parsing a template declaration.
Template,
/// We are parsing an explicit specialization.
ExplicitSpecialization,
/// We are parsing an explicit instantiation.
ExplicitInstantiation
} Kind;
/// The template parameter lists, for template declarations
/// and explicit specializations.
TemplateParameterLists *TemplateParams;
/// The location of the 'extern' keyword, if any, for an explicit
/// instantiation
SourceLocation ExternLoc;
/// The location of the 'template' keyword, for an explicit
/// instantiation.
SourceLocation TemplateLoc;
/// Whether the last template parameter list was empty.
bool LastParameterListWasEmpty;
SourceRange getSourceRange() const LLVM_READONLY;
};
void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
static void LateTemplateParserCleanupCallback(void *P);
Sema::ParsingClassState
PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
void DeallocateParsedClasses(ParsingClass *Class);
void PopParsingClass(Sema::ParsingClassState);
enum CachedInitKind {
CIK_DefaultArgument,
CIK_DefaultInitializer
};
NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
ParsedAttributes &AccessAttrs,
ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo,
const VirtSpecifiers &VS,
SourceLocation PureSpecLoc);
void ParseCXXNonStaticMemberInitializer(Decl *VarD);
void ParseLexedAttributes(ParsingClass &Class);
void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
bool EnterScope, bool OnDefinition);
void ParseLexedAttribute(LateParsedAttribute &LA,
bool EnterScope, bool OnDefinition);
void ParseLexedMethodDeclarations(ParsingClass &Class);
void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
void ParseLexedMethodDefs(ParsingClass &Class);
void ParseLexedMethodDef(LexedMethod &LM);
void ParseLexedMemberInitializers(ParsingClass &Class);
void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
void ParseLexedPragmas(ParsingClass &Class);
void ParseLexedPragma(LateParsedPragma &LP);
bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
bool ConsumeAndStoreConditional(CachedTokens &Toks);
bool ConsumeAndStoreUntil(tok::TokenKind T1,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true) {
return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
}
bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true);
//===--------------------------------------------------------------------===//
// C99 6.9: External Definitions.
struct ParsedAttributesWithRange : ParsedAttributes {
ParsedAttributesWithRange(AttributeFactory &factory)
: ParsedAttributes(factory) {}
void clear() {
ParsedAttributes::clear();
Range = SourceRange();
}
SourceRange Range;
};
struct ParsedAttributesViewWithRange : ParsedAttributesView {
ParsedAttributesViewWithRange() : ParsedAttributesView() {}
void clearListOnly() {
ParsedAttributesView::clearListOnly();
Range = SourceRange();
}
SourceRange Range;
};
DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr);
bool isDeclarationAfterDeclarator();
bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr,
AccessSpecifier AS = AS_none);
DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
ParsingDeclSpec &DS,
AccessSpecifier AS);
void SkipFunctionBody();
Decl *ParseFunctionDefinition(ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
LateParsedAttrList *LateParsedAttrs = nullptr);
void ParseKNRParamDeclarations(Declarator &D);
// EndLoc is filled with the location of the last token of the simple-asm.
ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
// Objective-C External Declarations
void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
ParsedAttributes &prefixAttrs);
class ObjCTypeParamListScope;
ObjCTypeParamList *parseObjCTypeParamList();
ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
SmallVectorImpl<IdentifierLocPair> &protocolIdents,
SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
BalancedDelimiterTracker &T,
SmallVectorImpl<Decl *> &AllIvarDecls,
bool RBraceMissing);
void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
tok::ObjCKeywordKind visibility,
SourceLocation atLoc);
bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
SmallVectorImpl<SourceLocation> &PLocs,
bool WarnOnDeclarations,
bool ForObjCContainer,
SourceLocation &LAngleLoc,
SourceLocation &EndProtoLoc,
bool consumeLastToken);
/// Parse the first angle-bracket-delimited clause for an
/// Objective-C object or object pointer type, which may be either
/// type arguments or protocol qualifiers.
void parseObjCTypeArgsOrProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken,
bool warnOnIncompleteProtocols);
/// Parse either Objective-C type arguments or protocol qualifiers; if the
/// former, also parse protocol qualifiers afterward.
void parseObjCTypeArgsAndProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken);
/// Parse a protocol qualifier type such as '<NSCopying>', which is
/// an anachronistic way of writing 'id<NSCopying>'.
TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
/// Parse Objective-C type arguments and protocol qualifiers, extending the
/// current type with the parsed result.
TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
ParsedType type,
bool consumeLastToken,
SourceLocation &endLoc);
void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
Decl *CDecl);
DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
ParsedAttributes &prefixAttrs);
struct ObjCImplParsingDataRAII {
Parser &P;
Decl *Dcl;
bool HasCFunction;
typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
LateParsedObjCMethodContainer LateParsedObjCMethods;
ObjCImplParsingDataRAII(Parser &parser, Decl *D)
: P(parser), Dcl(D), HasCFunction(false) {
P.CurParsedObjCImpl = this;
Finished = false;
}
~ObjCImplParsingDataRAII();
void finish(SourceRange AtEnd);
bool isFinished() const { return Finished; }
private:
bool Finished;
};
ObjCImplParsingDataRAII *CurParsedObjCImpl;
void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
ParsedAttributes &Attrs);
DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
// Definitions for Objective-c context sensitive keywords recognition.
enum ObjCTypeQual {
objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
objc_nonnull, objc_nullable, objc_null_unspecified,
objc_NumQuals
};
IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
bool isTokIdentifier_in() const;
ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
ParsedAttributes *ParamAttrs);
void ParseObjCMethodRequirement();
Decl *ParseObjCMethodPrototype(
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition = true);
Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition=true);
void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
Decl *ParseObjCMethodDefinition();
public:
//===--------------------------------------------------------------------===//
// C99 6.5: Expressions.
/// TypeCastState - State whether an expression is or may be a type cast.
enum TypeCastState {
NotTypeCast = 0,
MaybeTypeCast,
IsTypeCast
};
ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpressionInExprEvalContext(
TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseCaseExpression(SourceLocation CaseLoc);
ExprResult ParseConstraintExpression();
ExprResult
ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
// Expr that doesn't include commas.
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
unsigned &NumLineToksConsumed,
bool IsUnevaluated);
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
private:
ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
prec::Level MinPrec);
/// Control what ParseCastExpression will parse.
enum CastParseKind {
AnyCastExpr = 0,
UnaryExprOnly,
PrimaryExprOnly
};
ExprResult ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral = false,
bool *NotPrimaryExpression = nullptr);
ExprResult ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand = false,
TypeCastState isTypeCast = NotTypeCast,
bool isVectorLiteral = false,
bool *NotPrimaryExpression = nullptr);
/// Returns true if the next token cannot start an expression.
bool isNotExpressionStart();
/// Returns true if the next token would start a postfix-expression
/// suffix.
bool isPostfixExpressionSuffixStart() {
tok::TokenKind K = Tok.getKind();
return (K == tok::l_square || K == tok::l_paren ||
K == tok::period || K == tok::arrow ||
K == tok::plusplus || K == tok::minusminus);
}
bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
const Token &OpToken);
bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
if (auto *Info = AngleBrackets.getCurrent(*this))
return checkPotentialAngleBracketDelimiter(*Info, OpToken);
return false;
}
ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
ExprResult ParseUnaryExprOrTypeTraitExpression();
ExprResult ParseBuiltinPrimaryExpression();
ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange);
typedef SmallVector<Expr*, 20> ExprListTy;
typedef SmallVector<SourceLocation, 20> CommaLocsTy;
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs,
llvm::function_ref<void()> ExpressionStarts =
llvm::function_ref<void()>());
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
/// used for misc language extensions.
bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs);
/// ParenParseOption - Control what ParseParenExpression will parse.
enum ParenParseOption {
SimpleExpr, // Only parse '(' expression ')'
FoldExpr, // Also allow fold-expression <anything>
CompoundStmt, // Also allow '(' compound-statement ')'
CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
CastExpr // Also allow '(' type-name ')' <anything>
};
ExprResult ParseParenExpression(ParenParseOption &ExprType,
bool stopIfCastExpr,
bool isTypeCast,
ParsedType &CastTy,
SourceLocation &RParenLoc);
ExprResult ParseCXXAmbiguousParenExpression(
ParenParseOption &ExprType, ParsedType &CastTy,
BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
ExprResult ParseGenericSelectionExpression();
ExprResult ParseObjCBoolLiteral();
ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
//===--------------------------------------------------------------------===//
// C++ Expressions
ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
Token &Replacement);
ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
bool areTokensAdjacent(const Token &A, const Token &B);
void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
bool EnteringContext, IdentifierInfo &II,
CXXScopeSpec &SS);
bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType,
bool EnteringContext,
bool *MayBePseudoDestructor = nullptr,
bool IsTypename = false,
IdentifierInfo **LastII = nullptr,
bool OnlyNamespace = false,
bool InUsingDeclaration = false);
//===--------------------------------------------------------------------===//
// C++11 5.1.2: Lambda expressions
/// Result of tentatively parsing a lambda-introducer.
enum class LambdaIntroducerTentativeParse {
/// This appears to be a lambda-introducer, which has been fully parsed.
Success,
/// This is a lambda-introducer, but has not been fully parsed, and this
/// function needs to be called again to parse it.
Incomplete,
/// This is definitely an Objective-C message send expression, rather than
/// a lambda-introducer, attribute-specifier, or array designator.
MessageSend,
/// This is not a lambda-introducer.
Invalid,
};
// [...] () -> type {...}
ExprResult ParseLambdaExpression();
ExprResult TryParseLambdaExpression();
bool
ParseLambdaIntroducer(LambdaIntroducer &Intro,
LambdaIntroducerTentativeParse *Tentative = nullptr);
ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Casts
ExprResult ParseCXXCasts();
/// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
ExprResult ParseBuiltinBitCast();
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Type Identification
ExprResult ParseCXXTypeid();
//===--------------------------------------------------------------------===//
// C++ : Microsoft __uuidof Expression
ExprResult ParseCXXUuidof();
//===--------------------------------------------------------------------===//
// C++ 5.2.4: C++ Pseudo-Destructor Expressions
ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
ParsedType ObjectType);
//===--------------------------------------------------------------------===//
// C++ 9.3.2: C++ 'this' pointer
ExprResult ParseCXXThis();
//===--------------------------------------------------------------------===//
// C++ 15: C++ Throw Expression
ExprResult ParseThrowExpression();
ExceptionSpecificationType tryParseExceptionSpecification(
bool Delayed,
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &DynamicExceptions,
SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
ExprResult &NoexceptExpr,
CachedTokens *&ExceptionSpecTokens);
// EndLoc is filled with the location of the last token of the specification.
ExceptionSpecificationType ParseDynamicExceptionSpecification(
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &Exceptions,
SmallVectorImpl<SourceRange> &Ranges);
//===--------------------------------------------------------------------===//
// C++0x 8: Function declaration trailing-return-type
TypeResult ParseTrailingReturnType(SourceRange &Range,
bool MayBeFollowedByDirectInit);
//===--------------------------------------------------------------------===//
// C++ 2.13.5: C++ Boolean Literals
ExprResult ParseCXXBoolLiteral();
//===--------------------------------------------------------------------===//
// C++ 5.2.3: Explicit type conversion (functional notation)
ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
/// This should only be called when the current token is known to be part of
/// simple-type-specifier.
void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
//===--------------------------------------------------------------------===//
// C++ 5.3.4 and 5.3.5: C++ new and delete
bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
Declarator &D);
void ParseDirectNewDeclarator(Declarator &D);
ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
ExprResult ParseCXXDeleteExpression(bool UseGlobal,
SourceLocation Start);
//===--------------------------------------------------------------------===//
// C++ if/switch/while/for condition expression.
struct ForRangeInfo;
Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
SourceLocation Loc,
Sema::ConditionKind CK,
ForRangeInfo *FRI = nullptr);
//===--------------------------------------------------------------------===//
// C++ Coroutines
ExprResult ParseCoyieldExpression();
//===--------------------------------------------------------------------===//
// C++ Concepts
ExprResult ParseRequiresExpression();
void ParseTrailingRequiresClause(Declarator &D);
//===--------------------------------------------------------------------===//
// C99 6.7.8: Initialization.
/// ParseInitializer
/// initializer: [C99 6.7.8]
/// assignment-expression
/// '{' ...
ExprResult ParseInitializer() {
if (Tok.isNot(tok::l_brace))
return ParseAssignmentExpression();
return ParseBraceInitializer();
}
bool MayBeDesignationStart();
ExprResult ParseBraceInitializer();
ExprResult ParseInitializerWithPotentialDesignator(
llvm::function_ref<void(const Designation &)> CodeCompleteCB);
//===--------------------------------------------------------------------===//
// clang Expressions
ExprResult ParseBlockLiteralExpression(); // ^{...}
//===--------------------------------------------------------------------===//
// Objective-C Expressions
ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
bool isSimpleObjCMessageExpression();
ExprResult ParseObjCMessageExpression();
ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr);
ExprResult ParseAssignmentExprWithObjCMessageExprStart(
SourceLocation LBracloc, SourceLocation SuperLoc,
ParsedType ReceiverType, Expr *ReceiverExpr);
bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
//===--------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
/// A SmallVector of statements, with stack size 32 (as that is the only one
/// used.)
typedef SmallVector<Stmt*, 32> StmtVector;
/// A SmallVector of expressions, with stack size 12 (the maximum used.)
typedef SmallVector<Expr*, 12> ExprVector;
/// A SmallVector of types.
typedef SmallVector<ParsedType, 12> TypeVector;
StmtResult
ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
StmtResult ParseStatementOrDeclaration(
StmtVector &Stmts, ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc = nullptr);
StmtResult ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs,
ParsedStmtContext StmtCtx);
StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
bool MissingCase = false,
ExprResult Expr = ExprResult());
StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
StmtResult ParseCompoundStatement(bool isStmtExpr = false);
StmtResult ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags);
void ParseCompoundStatementLeadingPragmas();
bool ConsumeNullStmt(StmtVector &Stmts);
StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
bool ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &CondResult,
SourceLocation Loc,
Sema::ConditionKind CK);
StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseDoStatement();
StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseGotoStatement();
StmtResult ParseContinueStatement();
StmtResult ParseBreakStatement();
StmtResult ParseReturnStatement();
StmtResult ParseAsmStatement(bool &msAsm);
StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
/// Describes the behavior that should be taken for an __if_exists
/// block.
enum IfExistsBehavior {
/// Parse the block; this code is always used.
IEB_Parse,
/// Skip the block entirely; this code is never used.
IEB_Skip,
/// Parse the block as a dependent block, which may be used in
/// some template instantiations but not others.
IEB_Dependent
};
/// Describes the condition of a Microsoft __if_exists or
/// __if_not_exists block.
struct IfExistsCondition {
/// The location of the initial keyword.
SourceLocation KeywordLoc;
/// Whether this is an __if_exists block (rather than an
/// __if_not_exists block).
bool IsIfExists;
/// Nested-name-specifier preceding the name.
CXXScopeSpec SS;
/// The name we're looking for.
UnqualifiedId Name;
/// The behavior of this __if_exists or __if_not_exists block
/// should.
IfExistsBehavior Behavior;
};
bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
void ParseMicrosoftIfExistsExternalDeclaration();
void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
ParsedAttributes &AccessAttrs,
AccessSpecifier &CurAS);
bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
bool &InitExprsOk);
bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
SmallVectorImpl<Expr *> &Constraints,
SmallVectorImpl<Expr *> &Exprs);
//===--------------------------------------------------------------------===//
// C++ 6: Statements and Blocks
StmtResult ParseCXXTryBlock();
StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
StmtResult ParseCXXCatchBlock(bool FnCatch = false);
//===--------------------------------------------------------------------===//
// MS: SEH Statements and Blocks
StmtResult ParseSEHTryBlock();
StmtResult ParseSEHExceptBlock(SourceLocation Loc);
StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
StmtResult ParseSEHLeaveStatement();
//===--------------------------------------------------------------------===//
// Objective-C Statements
StmtResult ParseObjCAtStatement(SourceLocation atLoc,
ParsedStmtContext StmtCtx);
StmtResult ParseObjCTryStmt(SourceLocation atLoc);
StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
//===--------------------------------------------------------------------===//
// C99 6.7: Declarations.
/// A context for parsing declaration specifiers. TODO: flesh this
/// out, there are other significant restrictions on specifiers than
/// would be best implemented in the parser.
enum class DeclSpecContext {
DSC_normal, // normal context
DSC_class, // class context, enables 'friend'
DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
DSC_top_level, // top-level/namespace declaration context
DSC_template_param, // template parameter context
DSC_template_type_arg, // template type argument context
DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
DSC_condition // condition declaration context
};
/// Is this a context in which we are parsing just a type-specifier (or
/// trailing-type-specifier)?
static bool isTypeSpecifier(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_condition:
return false;
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_type_specifier:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return true;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Is this a context in which we can perform class template argument
/// deduction?
static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_condition:
case DeclSpecContext::DSC_type_specifier:
return true;
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return false;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Information on a C++0x for-range-initializer found while parsing a
/// declaration which turns out to be a for-range-declaration.
struct ForRangeInit {
SourceLocation ColonLoc;
ExprResult RangeExpr;
bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
};
struct ForRangeInfo : ForRangeInit {
StmtResult LoopVar;
};
DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs,
SourceLocation *DeclSpecStart = nullptr);
DeclGroupPtrTy
ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs, bool RequireSemi,
ForRangeInit *FRI = nullptr,
SourceLocation *DeclSpecStart = nullptr);
bool MightBeDeclarator(DeclaratorContext Context);
DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
SourceLocation *DeclEnd = nullptr,
ForRangeInit *FRI = nullptr);
Decl *ParseDeclarationAfterDeclarator(Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
bool ParseAsmAttributesAfterDeclarator(Declarator &D);
Decl *ParseDeclarationAfterDeclaratorAndAttributes(
Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ForRangeInit *FRI = nullptr);
Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
/// When in code-completion, skip parsing of the function/method body
/// unless the body contains the code-completion point.
///
/// \returns true if the function body was skipped.
bool trySkippingFunctionBody();
bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC,
ParsedAttributesWithRange &Attrs);
DeclSpecContext
getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
void ParseDeclarationSpecifiers(
DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal,
LateParsedAttrList *LateAttrs = nullptr);
bool DiagnoseMissingSemiAfterTagDefinition(
DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
LateParsedAttrList *LateAttrs = nullptr);
void ParseSpecifierQualifierList(
DeclSpec &DS, AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal);
void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
DeclaratorContext Context);
void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC);
void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
Decl *TagDecl);
void ParseStructDeclaration(
ParsingDeclSpec &DS,
llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
bool isTypeSpecifierQualifier();
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
/// is definitely a type-specifier. Return false if it isn't part of a type
/// specifier or if we're not sure.
bool isKnownToBeTypeSpecifier(const Token &Tok) const;
/// Return true if we know that we are definitely looking at a
/// decl-specifier, and isn't part of an expression such as a function-style
/// cast. Return false if it's no a decl-specifier, or we're not sure.
bool isKnownToBeDeclarationSpecifier() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationSpecifier() == TPResult::True;
return isDeclarationSpecifier(true);
}
/// isDeclarationStatement - Disambiguates between a declaration or an
/// expression statement, when parsing function bodies.
/// Returns true for declaration, false for expression.
bool isDeclarationStatement() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationStatement();
return isDeclarationSpecifier(true);
}
/// isForInitDeclaration - Disambiguates between a declaration or an
/// expression in the context of the C 'clause-1' or the C++
// 'for-init-statement' part of a 'for' statement.
/// Returns true for declaration, false for expression.
bool isForInitDeclaration() {
if (getLangOpts().OpenMP)
Actions.startOpenMPLoop();
if (getLangOpts().CPlusPlus)
return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
return isDeclarationSpecifier(true);
}
/// Determine whether this is a C++1z for-range-identifier.
bool isForRangeIdentifier();
/// Determine whether we are currently at the start of an Objective-C
/// class message that appears to be missing the open bracket '['.
bool isStartOfObjCClassMessageMissingOpenBracket();
/// Starting with a scope specifier, identifier, or
/// template-id that refers to the current class, determine whether
/// this is a constructor declarator.
bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
/// Specifies the context in which type-id/expression
/// disambiguation will occur.
enum TentativeCXXTypeIdContext {
TypeIdInParens,
TypeIdUnambiguous,
TypeIdAsTemplateArgument
};
/// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
/// whether the parens contain an expression or a type-id.
/// Returns true for a type-id and false for an expression.
bool isTypeIdInParens(bool &isAmbiguous) {
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdInParens, isAmbiguous);
isAmbiguous = false;
return isTypeSpecifierQualifier();
}
bool isTypeIdInParens() {
bool isAmbiguous;
return isTypeIdInParens(isAmbiguous);
}
/// Checks if the current tokens form type-id or expression.
/// It is similar to isTypeIdInParens but does not suppose that type-id
/// is in parenthesis.
bool isTypeIdUnambiguously() {
bool IsAmbiguous;
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
return isTypeSpecifierQualifier();
}
/// isCXXDeclarationStatement - C++-specialized function that disambiguates
/// between a declaration or an expression statement, when parsing function
/// bodies. Returns true for declaration, false for expression.
bool isCXXDeclarationStatement();
/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
/// between a simple-declaration or an expression-statement.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
/// Returns false if the statement is disambiguated as expression.
bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
/// a constructor-style initializer, when parsing declaration statements.
/// Returns true for function declarator and false for constructor-style
/// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
/// might be a constructor-style initializer.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
struct ConditionDeclarationOrInitStatementState;
enum class ConditionOrInitStatement {
Expression, ///< Disambiguated as an expression (either kind).
ConditionDecl, ///< Disambiguated as the declaration form of condition.
InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
ForRangeDecl, ///< Disambiguated as a for-range declaration.
Error ///< Can't be any of the above!
};
/// Disambiguates between the different kinds of things that can happen
/// after 'if (' or 'switch ('. This could be one of two different kinds of
/// declaration (depending on whether there is a ';' later) or an expression.
ConditionOrInitStatement
isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
bool CanBeForRangeDecl);
bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
bool isAmbiguous;
return isCXXTypeId(Context, isAmbiguous);
}
/// TPResult - Used as the result value for functions whose purpose is to
/// disambiguate C++ constructs by "tentatively parsing" them.
enum class TPResult {
True, False, Ambiguous, Error
};
/// Based only on the given token kind, determine whether we know that
/// we're at the start of an expression or a type-specifier-seq (which may
/// be an expression, in C++).
///
/// This routine does not attempt to resolve any of the trick cases, e.g.,
/// those involving lookup of identifiers.
///
/// \returns \c TPR_true if this token starts an expression, \c TPR_false if
/// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
/// tell.
TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
/// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
/// declaration specifier, TPResult::False if it is not,
/// TPResult::Ambiguous if it could be either a decl-specifier or a
/// function-style cast, and TPResult::Error if a parsing error was
/// encountered. If it could be a braced C++11 function-style cast, returns
/// BracedCastResult.
/// Doesn't consume tokens.
TPResult
isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
bool *InvalidAsDeclSpec = nullptr);
/// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
/// \c TPResult::Ambiguous, determine whether the decl-specifier would be
/// a type-specifier other than a cv-qualifier.
bool isCXXDeclarationSpecifierAType();
/// Determine whether the current token sequence might be
/// '<' template-argument-list '>'
/// rather than a less-than expression.
TPResult isTemplateArgumentList(unsigned TokensToSkip);
/// Determine whether an '(' after an 'explicit' keyword is part of a C++20
/// 'explicit(bool)' declaration, in earlier language modes where that is an
/// extension.
TPResult isExplicitBool();
/// Determine whether an identifier has been tentatively declared as a
/// non-type. Such tentative declarations should not be found to name a type
/// during a tentative parse, but also should not be annotated as a non-type.
bool isTentativelyDeclared(IdentifierInfo *II);
// "Tentative parsing" functions, used for disambiguation. If a parsing error
// is encountered they will return TPResult::Error.
// Returning TPResult::True/False indicates that the ambiguity was
// resolved and tentative parsing may stop. TPResult::Ambiguous indicates
// that more tentative parsing is necessary for disambiguation.
// They all consume tokens, so backtracking should be used after calling them.
TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
TPResult TryParseTypeofSpecifier();
TPResult TryParseProtocolQualifiers();
TPResult TryParsePtrOperatorSeq();
TPResult TryParseOperatorId();
TPResult TryParseInitDeclaratorList();
TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
bool mayHaveDirectInit = false);
TPResult
TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
bool VersusTemplateArg = false);
TPResult TryParseFunctionDeclarator();
TPResult TryParseBracketDeclarator();
TPResult TryConsumeDeclarationSpecifier();
/// Try to skip a possibly empty sequence of 'attribute-specifier's without
/// full validation of the syntactic structure of attributes.
bool TrySkipAttributes();
public:
TypeResult ParseTypeName(SourceRange *Range = nullptr,
DeclaratorContext Context
= DeclaratorContext::TypeNameContext,
AccessSpecifier AS = AS_none,
Decl **OwnedType = nullptr,
ParsedAttributes *Attrs = nullptr);
private:
void ParseBlockId(SourceLocation CaretLoc);
/// Are [[]] attributes enabled?
bool standardAttributesAllowed() const {
const LangOptions &LO = getLangOpts();
return LO.DoubleSquareBracketAttributes;
}
// Check for the start of an attribute-specifier-seq in a context where an
// attribute is not allowed.
bool CheckProhibitedCXX11Attribute() {
assert(Tok.is(tok::l_square));
if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
return false;
return DiagnoseProhibitedCXX11Attribute();
}
bool DiagnoseProhibitedCXX11Attribute();
void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation) {
if (!standardAttributesAllowed())
return;
if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
Tok.isNot(tok::kw_alignas))
return;
DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
}
void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation);
void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
DeclSpec &DS, Sema::TagUseKind TUK);
// FixItLoc = possible correct location for the attributes
void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clear();
}
void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clearListOnly();
}
void DiagnoseProhibitedAttributes(const SourceRange &Range,
SourceLocation FixItLoc);
// Forbid C++11 and C2x attributes that appear on certain syntactic locations
// which standard permits but we don't supported yet, for example, attributes
// appertain to decl specifiers.
void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
unsigned DiagID);
/// Skip C++11 and C2x attributes and return the end location of the
/// last one.
/// \returns SourceLocation() if there are no attributes.
SourceLocation SkipCXX11Attributes();
/// Diagnose and skip C++11 and C2x attributes that appear in syntactic
/// locations where attributes are not allowed.
void DiagnoseAndSkipCXX11Attributes();
/// Parses syntax-generic attribute arguments for attributes which are
/// known to the implementation, and adds them to the given ParsedAttributes
/// list with the given attribute syntax. Returns the number of arguments
/// parsed for the attribute.
unsigned
ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseGNUAttributes(Declarator &D,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute)) {
ParsedAttributes attrs(AttrFactory);
SourceLocation endLoc;
ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute))
ParseGNUAttributes(attrs, endLoc, LateAttrs);
}
void ParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr,
Declarator *D = nullptr);
void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax, Declarator *D);
IdentifierLoc *ParseIdentifierLoc();
unsigned
ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseCXX11Attributes(Declarator &D) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrs(AttrFactory);
SourceLocation endLoc;
ParseCXX11Attributes(attrs, &endLoc);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrsWithRange(AttrFactory);
ParseCXX11Attributes(attrsWithRange, endLoc);
attrs.takeAllFrom(attrsWithRange);
}
}
void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *endLoc = nullptr,
bool OuterMightBeMessageSend = false) {
if (standardAttributesAllowed() &&
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
ParseCXX11Attributes(attrs, endLoc);
}
void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
SourceLocation *EndLoc = nullptr);
void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *EndLoc = nullptr);
/// Parses a C++11 (or C2x)-style attribute argument list. Returns true
/// if this results in adding an attribute to the ParsedAttributes list.
bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc);
IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
ParseMicrosoftAttributes(attrs, endLoc);
}
void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
void ParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr);
void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr) {
const auto &LO = getLangOpts();
if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
ParseMicrosoftDeclSpecs(Attrs, End);
}
void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr);
bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs);
void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
SourceLocation SkipExtendedMicrosoftTypeAttributes();
void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
/// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
/// or higher.
/// \return false if error happens.
bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
if (getLangOpts().OpenCL)
return ParseOpenCLUnrollHintAttribute(Attrs);
return true;
}
/// Parses opencl_unroll_hint attribute.
/// \return false if error happens.
bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
VersionTuple ParseVersionTuple(SourceRange &Range);
void ParseAvailabilityAttribute(IdentifierInfo &Availability,
SourceLocation AvailabilityLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
Optional<AvailabilitySpec> ParseAvailabilitySpec();
ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
SourceLocation Loc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
SourceLocation ObjCBridgeRelatedLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseSwiftNewtypeAttribute(IdentifierInfo &SwiftNewtype,
SourceLocation SwiftNewtypeLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void
ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
void ParseTypeofSpecifier(DeclSpec &DS);
SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
void ParseAtomicSpecifier(DeclSpec &DS);
ExprResult ParseAlignArgument(SourceLocation Start,
SourceLocation &EllipsisLoc);
void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
SourceLocation *endLoc = nullptr);
void ParsePtrauthQualifier(ParsedAttributes &Attrs);
VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
return isCXX11VirtSpecifier(Tok);
}
void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
SourceLocation FriendLoc);
bool isCXX11FinalKeyword() const;
/// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
/// enter a new C++ declarator scope and exit it when the function is
/// finished.
class DeclaratorScopeObj {
Parser &P;
CXXScopeSpec &SS;
bool EnteredScope;
bool CreatedScope;
public:
DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
: P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
void EnterDeclaratorScope() {
assert(!EnteredScope && "Already entered the scope!");
assert(SS.isSet() && "C++ scope was not set!");
CreatedScope = true;
P.EnterScope(0); // Not a decl scope.
if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
EnteredScope = true;
}
~DeclaratorScopeObj() {
if (EnteredScope) {
assert(SS.isSet() && "C++ scope was cleared ?");
P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
}
if (CreatedScope)
P.ExitScope();
}
};
/// ParseDeclarator - Parse and verify a newly-initialized declarator.
void ParseDeclarator(Declarator &D);
/// A function that parses a variant of direct-declarator.
typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
void ParseDeclaratorInternal(Declarator &D,
DirectDeclParseFunction DirectDeclParser);
enum AttrRequirements {
AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
AR_GNUAttributesParsed = 1 << 1,
AR_CXX11AttributesParsed = 1 << 2,
AR_DeclspecAttributesParsed = 1 << 3,
AR_AllAttributesParsed = AR_GNUAttributesParsed |
AR_CXX11AttributesParsed |
AR_DeclspecAttributesParsed,
AR_VendorAttributesParsed = AR_GNUAttributesParsed |
AR_DeclspecAttributesParsed
};
void ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
bool AtomicAllowed = true, bool IdentifierRequired = false,
Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
void ParseDirectDeclarator(Declarator &D);
void ParseDecompositionDeclarator(Declarator &D);
void ParseParenDeclarator(Declarator &D);
void ParseFunctionDeclarator(Declarator &D,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker,
bool IsAmbiguous,
bool RequiresArg = false);
void InitCXXThisScopeForDeclaratorIfRelevant(
const Declarator &D, const DeclSpec &DS,
llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope);
bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc);
bool isFunctionDeclaratorIdentifierList();
void ParseFunctionDeclaratorIdentifierList(
Declarator &D,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
void ParseParameterDeclarationClause(
DeclaratorContext DeclaratorContext,
ParsedAttributes &attrs,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
SourceLocation &EllipsisLoc);
void ParseBracketDeclarator(Declarator &D);
void ParseMisplacedBracketDeclarator(Declarator &D);
//===--------------------------------------------------------------------===//
// C++ 7: Declarations [dcl.dcl]
/// The kind of attribute specifier we have found.
enum CXX11AttributeKind {
/// This is not an attribute specifier.
CAK_NotAttributeSpecifier,
/// This should be treated as an attribute-specifier.
CAK_AttributeSpecifier,
/// The next tokens are '[[', but this is not an attribute-specifier. This
/// is ill-formed by C++11 [dcl.attr.grammar]p6.
CAK_InvalidAttributeSpecifier
};
CXX11AttributeKind
isCXX11AttributeSpecifier(bool Disambiguate = false,
bool OuterMightBeMessageSend = false);
void DiagnoseUnexpectedNamespace(NamedDecl *Context);
DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
SourceLocation &DeclEnd,
SourceLocation InlineLoc = SourceLocation());
struct InnerNamespaceInfo {
SourceLocation NamespaceLoc;
SourceLocation InlineLoc;
SourceLocation IdentLoc;
IdentifierInfo *Ident;
};
using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
unsigned int index, SourceLocation &InlineLoc,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker);
Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
Decl *ParseExportDeclaration();
DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
Decl *ParseUsingDirective(DeclaratorContext Context,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
ParsedAttributes &attrs);
struct UsingDeclarator {
SourceLocation TypenameLoc;
CXXScopeSpec SS;
UnqualifiedId Name;
SourceLocation EllipsisLoc;
void clear() {
TypenameLoc = EllipsisLoc = SourceLocation();
SS.clear();
Name.clear();
}
};
bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
const ParsedTemplateInfo &TemplateInfo,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
AccessSpecifier AS = AS_none);
Decl *ParseAliasDeclarationAfterDeclarator(
const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
SourceLocation AliasLoc, IdentifierInfo *Alias,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// C++ 9: classes [class] and C structs/unions.
bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, bool EnteringContext,
DeclSpecContext DSC,
ParsedAttributesWithRange &Attributes);
void SkipCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
unsigned TagType,
Decl *TagDecl);
void ParseCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
ParsedAttributesWithRange &Attrs,
unsigned TagType,
Decl *TagDecl);
ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
SourceLocation &EqualLoc);
bool
ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
VirtSpecifiers &VS,
ExprResult &BitfieldSize,
LateParsedAttrList &LateAttrs);
void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
VirtSpecifiers &VS);
DeclGroupPtrTy ParseCXXClassMemberDeclaration(
AccessSpecifier AS, ParsedAttributes &Attr,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
DeclSpec::TST TagType, Decl *Tag);
void ParseConstructorInitializer(Decl *ConstructorDecl);
MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
Decl *ThisDecl);
//===--------------------------------------------------------------------===//
// C++ 10: Derived classes [class.derived]
TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
SourceLocation &EndLocation);
void ParseBaseClause(Decl *ClassDecl);
BaseResult ParseBaseSpecifier(Decl *ClassDecl);
AccessSpecifier getAccessSpecifierIfPresent() const;
bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Id,
bool AssumeTemplateId);
bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Result);
//===--------------------------------------------------------------------===//
// OpenMP: Directives and clauses.
/// Parse clauses for '#pragma omp declare simd'.
DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
CachedTokens &Toks,
SourceLocation Loc);
/// Parse a property kind into \p TIProperty for the selector set \p Set and
/// selector \p Selector.
void parseOMPTraitPropertyKind(OMPTraitInfo::OMPTraitProperty &TIProperty,
llvm::omp::TraitSet Set,
llvm::omp::TraitSelector Selector,
llvm::StringMap<SourceLocation> &Seen);
/// Parse a selector kind into \p TISelector for the selector set \p Set.
void parseOMPTraitSelectorKind(OMPTraitInfo::OMPTraitSelector &TISelector,
llvm::omp::TraitSet Set,
llvm::StringMap<SourceLocation> &Seen);
/// Parse a selector set kind into \p TISet.
void parseOMPTraitSetKind(OMPTraitInfo::OMPTraitSet &TISet,
llvm::StringMap<SourceLocation> &Seen);
/// Parses an OpenMP context property.
void parseOMPContextProperty(OMPTraitInfo::OMPTraitSelector &TISelector,
llvm::omp::TraitSet Set,
llvm::StringMap<SourceLocation> &Seen);
/// Parses an OpenMP context selector.
void parseOMPContextSelector(OMPTraitInfo::OMPTraitSelector &TISelector,
llvm::omp::TraitSet Set,
llvm::StringMap<SourceLocation> &SeenSelectors);
/// Parses an OpenMP context selector set.
void parseOMPContextSelectorSet(OMPTraitInfo::OMPTraitSet &TISet,
llvm::StringMap<SourceLocation> &SeenSets);
/// Parses OpenMP context selectors.
bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
/// Parse clauses for '#pragma omp declare variant'.
void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
SourceLocation Loc);
/// Parse clauses for '#pragma omp declare target'.
DeclGroupPtrTy ParseOMPDeclareTargetClauses();
/// Parse '#pragma omp end declare target'.
void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
SourceLocation Loc);
/// Parses declarative OpenMP directives.
DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified,
Decl *TagDecl = nullptr);
/// Parse 'omp declare reduction' construct.
DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
/// Parses initializer for provided omp_priv declaration inside the reduction
/// initializer.
void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
/// Parses 'omp declare mapper' directive.
DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
/// Parses variable declaration in 'omp declare mapper' directive.
TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
DeclarationName &Name,
AccessSpecifier AS = AS_none);
/// Parses simple list of variables.
///
/// \param Kind Kind of the directive.
/// \param Callback Callback function to be called for the list elements.
/// \param AllowScopeSpecifier true, if the variables can have fully
/// qualified names.
///
bool ParseOpenMPSimpleVarList(
OpenMPDirectiveKind Kind,
const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
Callback,
bool AllowScopeSpecifier);
/// Parses declarative or executable directive.
///
/// \param StmtCtx The context in which we're parsing the directive.
StmtResult
ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx);
/// Parses clause of kind \a CKind for directive of a kind \a Kind.
///
/// \param DKind Kind of current directive.
/// \param CKind Kind of current clause.
/// \param FirstClause true, if this is the first clause of a kind \a CKind
/// in current directive.
///
OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind CKind, bool FirstClause);
/// Parses clause with a single expression of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses simple clause of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
/// Parses clause with a single expression and an additional argument
/// of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses clause without any additional arguments.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
/// Parses clause with the list of variables of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind Kind, bool ParseOnly);
public:
/// Parses simple expression in parens for single-expression clauses of OpenMP
/// constructs.
/// \param RLoc Returned location of right paren.
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
bool IsAddressOfOperand = false);
/// Data used for parsing list of variables in OpenMP clauses.
struct OpenMPVarListDataTy {
Expr *TailExpr = nullptr;
SourceLocation ColonLoc;
SourceLocation RLoc;
CXXScopeSpec ReductionOrMapperIdScopeSpec;
DeclarationNameInfo ReductionOrMapperId;
int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
///< lastprivate clause.
SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers>
MapTypeModifiers;
SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers>
MapTypeModifiersLoc;
bool IsMapTypeImplicit = false;
SourceLocation DepLinMapLastLoc;
};
/// Parses clauses with list.
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
SmallVectorImpl<Expr *> &Vars,
OpenMPVarListDataTy &Data);
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
bool AllowDestructorName,
bool AllowConstructorName,
bool AllowDeductionGuide,
ParsedType ObjectType,
SourceLocation *TemplateKWLoc,
UnqualifiedId &Result);
/// Parses the mapper modifier in map, to, and from clauses.
bool parseMapperModifier(OpenMPVarListDataTy &Data);
/// Parses map-type-modifiers in map clause.
/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
/// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
bool parseMapTypeModifiers(OpenMPVarListDataTy &Data);
private:
//===--------------------------------------------------------------------===//
// C++ 14: Templates [temp]
// C++ 14.1: Template Parameters [temp.param]
Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS);
Decl *ParseSingleDeclarationAfterTemplate(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
bool ParseTemplateParameters(unsigned Depth,
SmallVectorImpl<NamedDecl *> &TemplateParams,
SourceLocation &LAngleLoc,
SourceLocation &RAngleLoc);
bool ParseTemplateParameterList(unsigned Depth,
SmallVectorImpl<NamedDecl*> &TemplateParams);
TPResult isStartOfTemplateTypeParameter();
NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
bool isTypeConstraintAnnotation();
bool TryAnnotateTypeConstraint();
NamedDecl *
ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position);
void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
SourceLocation CorrectLoc,
bool AlreadyHasEllipsis,
bool IdentifierHasName);
void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
Declarator &D);
// C++ 14.3: Template arguments [temp.arg]
typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
bool ConsumeLastToken,
bool ObjCGenericList);
bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
SourceLocation &LAngleLoc,
TemplateArgList &TemplateArgs,
SourceLocation &RAngleLoc);
bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &TemplateName,
bool AllowTypeAnnotation = true,
bool TypeConstraint = false);
void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
bool IsClassName = false);
bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
ParsedTemplateArgument ParseTemplateTemplateArgument();
ParsedTemplateArgument ParseTemplateArgument();
Decl *ParseExplicitInstantiation(DeclaratorContext Context,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
// C++2a: Template, concept definition [temp]
Decl *
ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// Modules
DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl);
Decl *ParseModuleImport(SourceLocation AtLoc);
bool parseMisplacedModuleImport();
bool tryParseMisplacedModuleImport() {
tok::TokenKind Kind = Tok.getKind();
if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
Kind == tok::annot_module_include)
return parseMisplacedModuleImport();
return false;
}
bool ParseModuleName(
SourceLocation UseLoc,
SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
bool IsImport);
//===--------------------------------------------------------------------===//
// C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
ExprResult ParseTypeTrait();
/// Parse the given string as a type.
///
/// This is a dangerous utility function currently employed only by API notes.
/// It is not a general entry-point for safely parsing types from strings.
///
/// \param typeStr The string to be parsed as a type.
/// \param context The name of the context in which this string is being
/// parsed, which will be used in diagnostics.
/// \param includeLoc The location at which this parse was triggered.
TypeResult parseTypeFromString(StringRef typeStr, StringRef context,
SourceLocation includeLoc);
//===--------------------------------------------------------------------===//
// Embarcadero: Arary and Expression Traits
ExprResult ParseArrayTypeTrait();
ExprResult ParseExpressionTrait();
ExprResult ParseBuiltinPtrauthTypeDiscriminator();
//===--------------------------------------------------------------------===//
// Preprocessor code-completion pass-through
void CodeCompleteDirective(bool InConditional) override;
void CodeCompleteInConditionalExclusion() override;
void CodeCompleteMacroName(bool IsDefinition) override;
void CodeCompletePreprocessorExpression() override;
void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
unsigned ArgumentIndex) override;
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
void CodeCompleteNaturalLanguage() override;
class GNUAsmQualifiers {
unsigned Qualifiers = AQ_unspecified;
public:
enum AQ {
AQ_unspecified = 0,
AQ_volatile = 1,
AQ_inline = 2,
AQ_goto = 4,
};
static const char *getQualifierName(AQ Qualifier);
bool setAsmQualifier(AQ Qualifier);
inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
inline bool isInline() const { return Qualifiers & AQ_inline; };
inline bool isGoto() const { return Qualifiers & AQ_goto; }
};
bool isGCCAsmStatement(const Token &TokAfterAsm) const;
bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
};
} // end namespace clang
#endif
|
matrix.h | #ifndef TMS_SUBMOD_MATRIX_H
#define TMS_SUBMOD_MATRIX_H
#include <random>
#include <list>
#include "mkl.h"
#include <assert.h>
#include <iomanip>
#include "../perf/perf.h"
#include "../perf_log.h"
#include "../util.h"
template<class DT> class Vector;
template<class DT>
class Matrix
{
//protected:
public:
DT * _values;
int64_t _m;
int64_t _n;
int64_t _rs;
int64_t _cs;
int64_t _base_m;
int64_t _base_n;
bool _mem_manage;
//public:
//
// Constructors
//
Matrix(int64_t m, int64_t n) : _m(m), _n(n), _rs(1), _cs(m), _base_m(m), _base_n(n), _mem_manage(true)
{
const int ret = posix_memalign((void **) &_values, 4096, _m * _n * sizeof(DT));
if (ret != 0) {
std::cout << "Could not allocate memory for Matrix. Exiting ..." << std::endl;
exit(1);
}
}
Matrix(DT* values, int64_t m, int64_t n, int64_t rs, int64_t cs, int64_t base_m, int64_t base_n, bool mem_manage) :
_values(values), _m(m), _n(n), _rs(rs), _cs(cs), _base_m(base_m), _base_n(base_n), _mem_manage(mem_manage)
{ }
Matrix(DT* values, int64_t m, int64_t n, int64_t rs, int64_t cs) :
_values(values), _m(m), _n(n), _rs(rs), _cs(cs), _base_m(m), _base_n(n), _mem_manage(false)
{ }
~Matrix()
{
if(_mem_manage){
free(_values);
}
}
Matrix& operator=(Matrix&& A) {
_m = A._m;
_m = A._n;
_rs = A._rs;
_cs = A._cs;
_base_m = A._m;
_base_n = A._n;
_mem_manage = A._mem_manage;
_values = A._values;
A._values = nullptr;
};
Matrix(Matrix&& A) :
_values(A._values),
_m(A._m), _n(A._n),
_rs(A._rs), _cs(A._cs),
_base_m(A._base_m), _base_n(A._base_n),
_mem_manage(A._mem_manage)
{
A._values = nullptr;
}
Matrix& operator=(const Matrix& A)
{
_m = A._m;
_m = A._n;
_base_m = _m;
_base_n = _n;
if(A._cs == 1) {
_cs = 1;
_rs = _n;
} else {
_rs = 1;
_cs = _m;
}
_mem_manage = true;
const int ret = posix_memalign((void **) &_values, 4096, _m * _n * sizeof(DT));
if (ret != 0) {
std::cout << "Could not allocate memory for Matrix. Exiting ..." << std::endl;
exit(1);
}
this->copy(A);
}
Matrix(const Matrix& A) :
_m(A._m), _n(A._n), _base_m(_m), _base_n(_n), _mem_manage(true)
{
if(A._cs == 1) {
_cs = 1;
_rs = _n;
} else {
_rs = 1;
_cs = _m;
}
_mem_manage = true;
const int ret = posix_memalign((void **) &_values, 4096, _m * _n * sizeof(DT));
if (ret != 0) {
std::cout << "Could not allocate memory for Matrix. Exiting ..." << std::endl;
exit(1);
}
this->copy(A);
}
void realloc(int64_t m, int64_t n) {
//Can only reallocate "base object"
assert(_mem_manage == true);
assert(m >= _m && n >= _n);
assert(_base_m >= _m && _base_n >= _n);
//Allocate new array
DT* array;
const int ret = posix_memalign((void **) &array, 4096, m * n * sizeof(DT));
if (ret != 0) {
std::cout << "Could not allocate memory for Matrix. Exiting ..." << std::endl;
exit(1);
}
//Copy old array over
Matrix<DT> tmp(array, m, n, 1, m, m, n, false);
auto tmp_partition = tmp.submatrix(0,0,_m,_n);
tmp_partition.copy(*this);
//Free old array
free(_values);
//Setup fields
_values = array;
_m = m;
_n = n;
_rs = 1;
_cs = m;
_base_m = m;
_base_n = n;
}
int64_t height() const
{
return _m;
}
int64_t width() const
{
return _n;
}
DT& operator() (int64_t row, int64_t col)
{
assert(row < _m && col < _n && "Matrix index out of bounds");
return _values[row * _rs + col * _cs];
}
DT operator() (int64_t row, int64_t col) const
{
assert(row < _m && col < _n && "Matrix index out of bounds");
return _values[row * _rs + col * _cs];
}
DT* lea (int64_t row, int64_t col)
{
assert(row < _m && col < _n && "Matrix index out of bounds");
return &_values[row * _rs + col * _cs];
}
const DT* lea (int64_t row, int64_t col) const
{
assert(row < _m && col < _n && "Matrix index out of bounds");
return &_values[row * _rs + col * _cs];
}
//
// Acquiring submatrices, subvectors
//
Matrix<DT> submatrix(int64_t row, int64_t col, int64_t mc, int64_t nc)
{
assert(row < _m && col < _n && "Matrix index out of bounds.");
auto height = std::min(mc, _m - row);
auto width = std::min(nc, _n - col);
return Matrix<DT>(lea(row,col), height, width, _rs, _cs, _m, _n, false);
}
Vector<DT> subrow(int64_t row, int64_t col, int64_t nc)
{
assert(row < _m && col < _n && "Matrix index out of bounds.");
auto width = std::min(nc, _n - col);
return Vector<DT>(&_values[row*_rs + col*_cs], width, _n, _cs, false);
}
Vector<DT> subrow(int64_t row)
{
assert(row < _m && "Matrix index out of bounds.");
return Vector<DT>(&_values[row*_rs], _n, _n, _cs, false);
}
Vector<DT> subcol(int64_t row, int64_t col, int64_t mc)
{
assert(row < _m && col < _n && "Matrix index out of bounds.");
auto height = std::min(mc, _m - row);
return Vector<DT>(&_values[row*_rs + col*_cs], height, _m, _rs, false);
}
Vector<DT> subcol(int64_t col)
{
assert(col < _n && "Matrix index out of bounds.");
return Vector<DT>(&_values[col*_cs], _m, _m, _rs, false);
}
const Matrix<DT> submatrix(int64_t row, int64_t col, int64_t mc, int64_t nc) const
{
assert(row < _m && col < _n && "Matrix index out of bounds.");
auto height = std::min(mc, _m - row);
auto width = std::min(nc, _n - col);
return Matrix<DT>(&_values[row*_rs + col*_cs], height, width, _rs, _cs, _m, _n, false);
}
const Vector<DT> subrow(int64_t row, int64_t col, int64_t nc) const
{
assert(row < _m && col < _n && "Matrix index out of bounds.");
auto width = std::min(nc, _n - col);
return Vector<DT>(&_values[row*_rs + col*_cs], width, _n, _cs, false);
}
const Vector<DT> subrow(int64_t row) const
{
assert(row < _m && "Matrix index out of bounds.");
return Vector<DT>(&_values[row*_rs], _n, _n, _cs, false);
}
const Vector<DT> subcol(int64_t row, int64_t col, int64_t mc) const
{
assert(row < _m && col < _n && "Matrix index out of bounds.");
auto height = std::min(mc, _m - row);
return Vector<DT>(&_values[row*_rs + col*_cs], height, _m, _rs, false);
}
const Vector<DT> subcol(int64_t col) const
{
assert(col < _n && "Matrix index out of bounds.");
return Vector<DT>(&_values[col*_cs], _m, _m, _rs, false);
}
//
// Routines for setting elements of the matrix
//
void set_all(DT alpha) {
#pragma omp parallel for
for(int64_t j = 0; j < _n; j++) {
for(int64_t i = 0; i < _m; i++) {
(*this)(i,j) = alpha;
}
}
}
template<class RNG, class DIST>
void fill_rand(RNG &gen, DIST &dist) {
for(int64_t j = 0; j < _n; j++) {
for(int64_t i = 0; i < _m; i++) {
(*this)(i,j) = dist(gen);
}
}
}
void fill_rand() {
std::random_device rd;
std::mt19937 gen{rd()};
std::normal_distribution<> normal(0.0, 1.0);
this->fill_rand(gen, normal);
}
void set_diagonal(DT alpha) {
#pragma omp parallel for
for(int64_t i = 0; i < std::min(_m, _n); i++) {
(*this)(i,i) = alpha;
}
}
void set_subdiagonal(DT alpha) {
#pragma omp parallel for
for(int64_t i = 0; i < _m; i++) {
for(int64_t j = 0; j < i && j < _n; j++) {
(*this)(i,j) = alpha;
}
}
}
void copy(const Matrix<DT>& other)
{
assert(_m == other._m && _n == other._n);
#pragma omp parallel for
for(int j = 0; j < _n; j++) {
for(int i = 0; i < _m; i++) {
(*this)(i,j) = other(i,j);
}
}
}
void copy_permute_rc(const Matrix<DT>& other, const std::vector<int64_t>& p)
{
assert(_m == other._m && _n == other._n);
#pragma omp parallel for
for(int j = 0; j < _n; j++) {
for(int i = 0; i < _m; i++) {
(*this)(i,j) = other(p[i],p[j]);
}
}
}
void copy_upper_tri(const Matrix<DT>& other)
{
assert(_m == other._m && _n == other._n);
assert(_m == _n);
#pragma omp parallel for
for(int j = 0; j < _n; j++) {
for(int i = 0; i <= j; i++) {
(*this)(i,j) = other(i,j);
}
}
}
//
// Simple computational routines
//
void axpby(DT alpha, const Matrix<DT>& other, DT beta)
{
assert(_m == other._m && _n == other._n);
for(int i = 0; i < _m; i++) {
for(int j = 0; j < _n; j++) {
(*this)(i,j) = beta * (*this)(i,j) + alpha * other(i,j);
}
}
}
DT fro_norm() const
{
DT fro_nrm = 0.0;
for(int i = 0; i < _m; i++) {
for(int j = 0; j < _n; j++) {
fro_nrm += (*this)(i,j)*(*this)(i,j);
}
}
return sqrt(fro_nrm);
}
void transpose()
{
std::swap(_m, _n);
std::swap(_rs, _cs);
std::swap(_base_m, _base_n);
}
Matrix<DT> transposed()
{
return Matrix<DT>(_values, _n, _m, _cs, _rs, _base_n, _base_m, false);
}
const Matrix<DT> transposed() const
{
return Matrix<DT>(_values, _n, _m, _cs, _rs, _base_n, _base_m, false);
}
void print(std::string name) const
{
std::cout << name << std::endl;
for(int i = 0; i < _m; i++) {
for(int j = 0; j < _n; j++) {
std::cout << std::left << std::setprecision(5) << std::setw(12) << (*this)(i,j);
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void print() const
{
for(int i = 0; i < _m; i++) {
for(int j = 0; j < _n; j++) {
std::cout << std::left << std::setprecision(5) << std::setw(12) << (*this)(i,j);
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void enlarge_m(int64_t m_inc)
{
assert(_m + m_inc <= _base_m && "Cannot add row to matrix.");
_m += m_inc;
}
void enlarge_n(int64_t n_inc)
{
assert(_n + n_inc <= _base_n && "Cannot add colum to matrix.");
_n += n_inc;
}
//
// BLAS, LAPACK routines
//
void mvm(DT, const Vector<DT>&, DT, Vector<DT>&) const
{
std::cout << "Gemv not implemented for datatype" << std::endl;
exit(1);
}
void trsv(CBLAS_UPLO, Vector<DT>&) const
{
std::cout << "Trsv not implemented for datatype" << std::endl;
exit(1);
}
void trsm(CBLAS_UPLO, CBLAS_SIDE, Matrix<DT>&) const
{
std::cout << "Trsv not implemented for datatype" << std::endl;
exit(1);
}
void mmm(DT, const Matrix<DT>&, const Matrix<DT>&, DT)
{
std::cout << "Gemm not implemented for datatype" << std::endl;
exit(1);
}
void syrk(CBLAS_UPLO, DT, const Matrix<DT>&, DT)
{
std::cout << "Syrk not implemented for datatype" << std::endl;
exit(1);
}
void qr(Vector<DT>&)
{
std::cout << "QR factorization not implemented for datatype" << std::endl;
exit(1);
}
void chol(char)
{
std::cout << "Cholesky factorization not implemented for datatype" << std::endl;
exit(1);
}
void apply_q(Vector<DT>&, Matrix<DT>&) const
{
std::cout << "Applying Q from qr factorization not implemented for datatype" << std::endl;
exit(1);
}
void tpqr(Matrix<DT>&, Matrix<DT>&, int64_t, int64_t)
{
std::cout << "TPQR factorization not implemented for datatype" << std::endl;
exit(1);
}
void apply_tpq(Matrix<DT>&, Matrix<DT>&, const Matrix<DT>&, int64_t, int64_t, Matrix<DT>&) const
{
std::cout << "Applying TPQ not implemented for datatype" << std::endl;
exit(1);
}
//
// Routines related to removing columns of a matrix
//
void trap_qr(Vector<DT>& t, int64_t l)
{
assert(_n + l >= _m && "Nonconformal trap_qr");
assert( t._len >= std::min(_m, _n) && "Cannot perform trap qr.");
for(int64_t i = 0; i < _n; i++) {
t(i) = house_gen(l, &_values[i*_rs + i*_cs], _rs);
if(i+1 < _n){
house_apply(l, _n-i-1, &_values[i*_rs + i*_cs], _rs, t(i), &_values[i*_rs + (i+1)*_cs], _rs, _cs);
}
}
}
void apply_trap_q(Matrix<DT>& A, const Vector<DT>& t, int64_t l) const
{
assert(_n + l >= _m && "Nonconformal apply_trap_q");
assert(t._len >= std::min(_m, _n) && "Cannot apply q from trap qr.");
assert(_cs == 1 || _rs == 1 && "Only row or column major trap_qr supported");
for(int64_t i = 0; i < _n; i++) {
house_apply(l, A.width(), &_values[i*_rs + i*_cs], _rs, t(i), &A._values[i*A._rs], A._rs, A._cs);
}
}
void remove_col(int64_t col) {
std::list<int64_t> tmp;
tmp.push_back(col);
remove_cols(tmp);
}
void remove_cols(const std::list<int64_t>& cols_to_remove)
{
int64_t start, end;
start = rdtsc();
int64_t n_removed = 1;
for(auto iter = cols_to_remove.begin(); iter != cols_to_remove.end(); iter++) {
int64_t block_begin = *iter - (n_removed - 1);
int64_t block_end = _n - n_removed;
if(std::next(iter,1) != cols_to_remove.end()) {
block_end = *std::next(iter,1) - n_removed;
}
for(int64_t i = block_begin; i < block_end; i++) {
auto col_to_overwrite = this->subcol(i);
const auto col_to_copy = this->subcol(i + n_removed);
col_to_overwrite.copy(col_to_copy);
}
n_removed++;
}
this->enlarge_n(-cols_to_remove.size());
end = rdtsc();
PerfLog::get().log_total("REMOVE COLS BYTES", 2 * _m * _n);
PerfLog::get().log_total("REMOVE COLS TIME", end - start);
}
void remove_cols_trap(const std::list<int64_t>& cols_to_remove)
{
int64_t n_removed = 1;
for(auto iter = cols_to_remove.begin(); iter != cols_to_remove.end(); iter++) {
int64_t block_begin = *iter - (n_removed - 1);
int64_t block_end = _n - n_removed;
if(std::next(iter,1) != cols_to_remove.end()) {
block_end = *std::next(iter,1) - n_removed;
}
for(int64_t i = block_begin; i < block_end; i++) {
auto col_to_overwrite = this->subcol(0, i, std::min(i + n_removed + 1, _m));
const auto col_to_copy = this->subcol(0, i + n_removed, std::min(i + n_removed + 1, _m));
col_to_overwrite.copy(col_to_copy);
}
n_removed++;
}
this->enlarge_n(-cols_to_remove.size());
}
void remove_cols_trap_oop(Matrix<DT>& dest, const std::list<int64_t>& cols_to_remove) const
{
int64_t n_removed = 1;
for(auto iter = cols_to_remove.begin(); iter != cols_to_remove.end(); iter++) {
int64_t block_begin = *iter - (n_removed - 1);
int64_t block_end = _n - n_removed;
if(std::next(iter,1) != cols_to_remove.end()) {
block_end = *std::next(iter,1) - n_removed;
}
for(int64_t i = block_begin; i < block_end; i++) {
auto col_to_overwrite = dest.subcol(0, i, std::min(i + n_removed + 1, _m));
const auto col_to_copy = this->subcol(0, i + n_removed, std::min(i + n_removed + 1, _m));
col_to_overwrite.copy(col_to_copy);
}
n_removed++;
}
dest.enlarge_n(-cols_to_remove.size());
}
void shift_trapezoid_up(int64_t dest_m_coord, int64_t dest_n_coord, int64_t nc, int64_t h, int64_t y_dist)
{
if(_rs == 1) {
int64_t end_n = std::min(_n, dest_n_coord + nc);
for(int64_t j = dest_n_coord; j < end_n; j++) {
int64_t end_m = std::min(_m - y_dist, dest_m_coord + j + h);
#pragma omp parallel for
for(int64_t i = dest_m_coord; i < end_m; i++) {
_values[i*_rs + j*_cs] = _values[(i+y_dist)*_rs + j*_cs];
}
}
} else {
int64_t end_m = std::min(_m - y_dist, dest_m_coord + nc + h);
int64_t end_n = std::min(_n, dest_n_coord + nc);
#pragma omp parallel for
for(int64_t i = dest_m_coord; i < end_m; i++) {
int64_t start_n = std::min(i - dest_m_coord - h, (int64_t) 0);
for(int64_t j = dest_n_coord + start_n; j < end_n; j++) {
_values[i*_rs + j*_cs] = _values[(i + y_dist)*_rs + j*_cs];
}
}
}
}
void shift_trapezoid_left(int64_t dest_m_coord, int64_t dest_n_coord, int64_t nc, int64_t h, int64_t x_dist)
{
if(_rs == 1) {
int64_t end_n = std::min(_n - x_dist, dest_n_coord + nc);
for(int64_t j = dest_n_coord; j < end_n; j++) {
int64_t end_m = std::min(_m, dest_m_coord + j + h);
#pragma omp parallel for
for(int64_t i = dest_m_coord; i < end_m; i++) {
_values[i*_rs + j*_cs] = _values[i*_rs + (j + x_dist)*_cs];
}
}
} else {
int64_t end_m = std::min(_m, dest_m_coord + nc + h);
int64_t end_n = std::min(_n - x_dist, dest_n_coord + nc);
#pragma omp parallel for
for(int64_t i = dest_m_coord; i < end_m; i++) {
int64_t start_n = std::min(i-dest_m_coord - h, (int64_t)0);
for(int64_t j = dest_n_coord + start_n; j < end_n; j++) {
_values[i*_rs + j*_cs] = _values[i*_rs + (j + x_dist)*_cs];
}
}
}
}
void shift_triangle_left(int64_t dest_m_coord, int64_t dest_n_coord, int64_t nc, int64_t x_dist)
{
DT* src = lea(dest_m_coord, dest_n_coord + x_dist);
DT* dest = lea(dest_m_coord, dest_n_coord);
if(_rs == 1) {
int64_t N = std::min(nc, _n - x_dist - dest_n_coord);
for(int64_t j = 0; j < N; j++) {
int64_t M = std::min(j+1, _m - dest_m_coord);
#pragma omp parallel for
for(int64_t i = 0; i < M; i++) {
dest[i*_rs + j*_cs] = src[i*_rs + j*_cs];
src[i*_rs + j*_cs] = 0.0;
}
}
} else {
int64_t M = std::min(nc, _m - dest_m_coord);
#pragma omp parallel for
for(int64_t i = 0; i < M; i++) {
int64_t N = std::min(nc, _n - dest_n_coord - x_dist);
for(int64_t j = i; j < N; j++) {
dest[i*_rs + j*_cs] = src[i*_rs + j*_cs];
}
}
}
}
void shift_triangle_up(int64_t dest_m_coord, int64_t dest_n_coord, int64_t nc, int64_t y_dist)
{
DT* src = lea(dest_m_coord + y_dist, dest_n_coord);
DT* dest = lea(dest_m_coord, dest_n_coord);
if(_rs == 1) {
int64_t N = std::min(nc, _n - dest_n_coord);
#pragma omp parallel for
for(int64_t j = 0; j < N; j++) {
int64_t M = std::min(j+1, _m - dest_m_coord - y_dist);
for(int64_t i = 0; i < M; i++) {
dest[i*_rs + j*_cs] = src[i*_rs + j*_cs];
//if(i+y_dist >= M) src[i*_rs + j*_cs] = 0.0;
src[i*_rs + j*_cs] = 0.0;
}
}
} else {
int64_t M = std::min(nc, _m - dest_m_coord - y_dist);
for(int64_t i = 0; i < M; i++) {
int64_t N = std::min(nc, _n - dest_n_coord);
#pragma omp parallel for
for(int64_t j = i; j < N; j++) {
dest[i*_rs + j*_cs] = src[i*_rs + j*_cs];
}
}
}
}
void shift_dense_left(int64_t dest_m_coord, int64_t dest_n_coord, int64_t mc, int64_t nc, int64_t x_dist)
{
int64_t end_n = std::min(_n - x_dist, dest_n_coord + nc);
int64_t end_m = std::min(_m, dest_m_coord + mc);
if(_rs == 1) {
for(int64_t j = dest_n_coord; j < end_n; j++) {
#pragma omp parallel for
for(int64_t i = dest_m_coord; i < end_m; i++) {
_values[i*_rs + j*_cs] = _values[i*_rs + (j + x_dist)*_cs];
_values[i*_rs + (j + x_dist)*_cs] = 0;
}
}
} else {
#pragma omp parallel for
for(int64_t i = dest_m_coord; i < end_m; i++) {
for(int64_t j = dest_n_coord; j < end_n; j++) {
_values[i*_rs + j*_cs] = _values[i*_rs + (j + x_dist)*_cs];
}
}
}
}
void shift_dense_up(int64_t dest_m_coord, int64_t dest_n_coord, int64_t mc, int64_t nc, int64_t y_dist)
{
int64_t end_n = std::min(_n, dest_n_coord + nc);
int64_t end_m = std::min(_m - y_dist, dest_m_coord + mc);
if(_rs == 1) {
#pragma omp parallel for
for(int64_t j = dest_n_coord; j < end_n; j++) {
for(int64_t i = dest_m_coord; i < end_m; i++) {
_values[i*_rs + j*_cs] = _values[(i+y_dist)*_rs + j*_cs];
_values[(i+ y_dist)*_rs + j*_cs] = 0;
}
}
} else {
for(int64_t i = dest_m_coord; i < end_m; i++) {
#pragma omp parallel for
for(int64_t j = dest_n_coord; j < end_n; j++) {
_values[i*_rs + j*_cs] = _values[(i + y_dist)*_rs + j*_cs];
}
}
}
}
//Delete columns of the matrix and permute rows (to be annihilated) into V
void remove_cols_permute_rows_in_place(const std::list<int64_t>& cols_to_remove, Matrix<DT>& V)
{
int64_t cols_removed = 1;
for(auto j_iter = cols_to_remove.begin(); j_iter != cols_to_remove.end(); j_iter++) {
//trap_begin and trap_end represent the start and end of the trapezoid after shifting it.
int64_t source_j_begin = *j_iter + 1;
if(source_j_begin == _n) break;
int64_t source_j_end = _n;
if(std::next(j_iter,1) != cols_to_remove.end()) {
source_j_end = *std::next(j_iter,1);
}
int64_t dest_j_begin = source_j_begin - cols_removed;
//Size of the triangular matrix along diagonal
int64_t trap_n = source_j_end - source_j_begin;
//Early exit conditions
if(source_j_begin == source_j_end) {
cols_removed++;
continue;
}
//Copy blocks above diagonal, copy rows to annihilate
int64_t rows_permuted = 0;
int64_t source_i_begin = 0;
for(auto i_iter = cols_to_remove.begin(); i_iter != std::next(j_iter,1); i_iter++) {
int64_t dest_i_begin = source_i_begin - rows_permuted;
//Copy the row to annihilate into the V matrix
auto r = this->subrow(*i_iter, source_j_begin, trap_n);
auto v = V.subrow(rows_permuted, dest_j_begin, trap_n);
v.copy(r);
//Shift block up and to the left
this->shift_dense_left(source_i_begin, dest_j_begin, *i_iter - source_i_begin, trap_n, cols_removed);
if(rows_permuted > 0)
this->shift_dense_up(dest_i_begin, dest_j_begin, *i_iter - source_i_begin, trap_n, rows_permuted);
source_i_begin = *i_iter + 1;
rows_permuted++;
}
//Shift triangle along diagonal up and to the left
this->shift_triangle_up(dest_j_begin, source_j_begin, trap_n, cols_removed);
this->shift_triangle_left(dest_j_begin, dest_j_begin, trap_n, cols_removed);
cols_removed++;
}
this->enlarge_n(-cols_to_remove.size());
this->enlarge_m(-cols_to_remove.size());
}
void remove_cols_permute_rows_out_of_place(Matrix<DT>& dest, const std::list<int64_t>& cols_to_remove, Matrix<DT>& V) const
{
if(cols_to_remove.size() == 0) {
dest.copy_upper_tri(*this);
}
//Copy initial triangle
auto src_tri = this->submatrix(0, 0, cols_to_remove.front(), cols_to_remove.front());
auto dest_tri = dest.submatrix(0, 0, cols_to_remove.front(), cols_to_remove.front());
dest_tri.copy_upper_tri(src_tri);
int64_t cols_removed = 1;
for(auto j_iter = cols_to_remove.begin(); j_iter != cols_to_remove.end(); j_iter++) {
int64_t source_j_begin = *j_iter + 1;
if(source_j_begin == _n) break;
int64_t source_j_end = _n;
if(std::next(j_iter,1) != cols_to_remove.end()) {
source_j_end = *std::next(j_iter,1);
}
int64_t dest_j_begin = source_j_begin - cols_removed;
//Size of the triangular matrix along diagonal
int64_t trap_n = source_j_end - source_j_begin;
//Early exit conditions
if(source_j_begin == source_j_end) {
cols_removed++;
continue;
}
//Copy blocks above diagonal, copy rows to annihilate
int64_t rows_permuted = 0;
int64_t source_i_begin = 0;
for(auto i_iter = cols_to_remove.begin(); i_iter != std::next(j_iter,1); i_iter++) {
int64_t dest_i_begin = source_i_begin - rows_permuted;
//Copy the row to annihilate into the V matrix
auto r = this->subrow(*i_iter, source_j_begin, trap_n);
auto v = V.subrow(rows_permuted, dest_j_begin, trap_n);
v.copy(r);
//Copy block
auto src_blk = this->submatrix(source_i_begin, source_j_begin, *i_iter - source_i_begin, trap_n);
auto dest_blk = dest.submatrix(dest_i_begin, dest_j_begin, *i_iter - source_i_begin, trap_n);
dest_blk.copy(src_blk);
source_i_begin = *i_iter + 1;
rows_permuted++;
}
//Copy triangle along diagonal
auto src_tri = this->submatrix(source_j_begin, source_j_begin, trap_n, trap_n);
auto dest_tri = dest.submatrix(dest_j_begin, dest_j_begin, trap_n, trap_n);
dest_tri.copy_upper_tri(src_tri);
cols_removed++;
}
dest.enlarge_n(-cols_to_remove.size());
dest.enlarge_m(-cols_to_remove.size());
}
//Remove columns and rows beforehand, and use tpqr to annihilate rows, task parallel version
//ws must be at least nb by n
void remove_cols_incremental_qr_tasks_kressner(Matrix<DT>& dest, const std::list<int64_t>& cols_to_remove, Matrix<DT>& T, Matrix<DT>& V, int64_t task_size, int64_t nb, Matrix<DT>& ws) const
{
int64_t start, end;
start = rdtsc();
//Delete columns and permute rows into the V matrix
this->remove_cols_permute_rows_out_of_place(dest, cols_to_remove, V);
//Partition the matrix according to the positions of the columns to be removed
int64_t n_removed = 1;
for(auto iter = cols_to_remove.begin(); iter != cols_to_remove.end(); iter++) {
//trap_begin and trap_end represent the start and end of the trapezoid after shifting it.
int64_t trap_begin = *iter + 1 - n_removed;
int64_t trap_end = dest.width();
if(std::next(iter,1) != cols_to_remove.end())
trap_end = *std::next(iter,1) - n_removed;
int64_t trap_n = trap_end - trap_begin;
//Early exit conditions
if(trap_begin == trap_end) {
n_removed++;
continue;
}
#pragma omp parallel
#pragma omp single nowait
{
for(int64_t i = 0; i < trap_n; i += task_size) {
int64_t block_m = std::min(task_size, trap_n - i);
int64_t block_begin = trap_begin + i;
//Factorization
#pragma omp task depend(inout: i)
{
auto V1 = V.submatrix(0, block_begin, n_removed, block_m);
auto T1 = T.submatrix(0, block_begin, nb, block_m);
auto R11 = dest.submatrix(block_begin, block_begin, block_m, block_m);
auto ws1 = ws.submatrix(0, block_begin, nb, block_m);
R11.tpqr(V1, T1, 0, nb);
}
//Apply Q to the rest of the matrix
for(int64_t j = block_begin + block_m; j < dest.width(); j += task_size) {
int64_t block_n = std::min(task_size, dest.width() - j);
#pragma omp task depend(in:i) //depend(inout:j)
{
auto V1 = V.submatrix(0, block_begin, n_removed, block_m);
auto T1 = T.submatrix(0, block_begin, nb, block_m);
auto R12 = dest.submatrix(block_begin, j, block_m, block_n);
auto V2 = V.submatrix(0, j, n_removed, block_n);
auto ws2 = ws.submatrix(0, j, ws.height(), block_n);
V1.apply_tpq(R12, V2, T1, 0, nb, ws2);
}
}
}
}
n_removed++;
}
end = rdtsc();
end++;
PerfLog::get().log_total("REMOVE COLS QR BYTES", 2 * _m * _n);
PerfLog::get().log_total("REMOVE COLS QR TIME", end - start);
}
void remove_cols_incremental_qr_kressner(Matrix<DT>& dest, const std::list<int64_t>& cols_to_remove, Matrix<DT>& T, Matrix<DT>& Vin, int64_t nb, Matrix<DT>& ws) const
{
int64_t start, end;
start = rdtsc();
Matrix<DT> V = Vin.submatrix(0,0,Vin.height(), this->width() - cols_to_remove.size());
//Delete columns and permute rows into the V matrix
this->remove_cols_permute_rows_out_of_place(dest, cols_to_remove, V);
//First partition the matrix according to the positions of the columns to be removed
int64_t n_removed = 1;
for(auto iter = cols_to_remove.begin(); iter != cols_to_remove.end(); iter++) {
//trap_begin and trap_end represent the start and end of the trapezoid after shifting it.
int64_t trap_begin = *iter + 1 - n_removed;
int64_t trap_end = dest.width();
if(std::next(iter,1) != cols_to_remove.end())
trap_end = *std::next(iter,1) - n_removed;
int64_t trap_n = trap_end - trap_begin;
//Early exit conditions
if(trap_begin == trap_end) {
n_removed++;
continue;
}
//TPQR along the diagonal
auto V1 = V.submatrix(0, trap_begin, n_removed, trap_n);
auto R11 = dest.submatrix(trap_begin, trap_begin, trap_n, trap_n);
auto T1 = T.submatrix(0, trap_begin, T.height(), trap_n);
R11.tpqr(V1, T1, 0, nb);
//Apply Q to the rest of matrix
int64_t trail_begin = trap_end;
if (trail_begin < dest.width()) {
auto R12 = dest.submatrix(trap_begin, trail_begin, trap_n, dest.width() - trail_begin);
auto V2 = V.submatrix(0, trail_begin, n_removed, dest.width() - trail_begin);
V1.apply_tpq(R12, V2, T1, 0, nb, ws);
}
n_removed++;
}
end = rdtsc();
PerfLog::get().log_total("REMOVE COLS QR BYTES", 2 * _m * _n);
PerfLog::get().log_total("REMOVE COLS QR TIME", end - start);
}
void remove_cols_incremental_qr_householder(const std::list<int64_t>& cols_to_remove, Vector<DT>& t)
{
int64_t start, end;
start = rdtsc();
//First remove the columns.
this->remove_cols_trap(cols_to_remove);
//Second pass.
//Use trapezoidal QR factorization to clean up elements below the diagonal
//Partition the matrix by panels based on the columns there were removed
int64_t n_removed = 1;
for(auto iter = cols_to_remove.begin(); iter != cols_to_remove.end(); iter++) {
int64_t block_begin = *iter - (n_removed - 1);
if(block_begin == _n) break;
int64_t block_end = _n;
if(std::next(iter,1) != cols_to_remove.end()) {
block_end = *std::next(iter,1) - n_removed;
}
int64_t m = block_end - block_begin + n_removed;
int64_t n = block_end - block_begin;
auto R11 = this->submatrix(block_begin, block_begin, m, n);
auto t1 = t.subvector(block_begin, n);
R11.trap_qr(t1, n_removed + 1);
if(block_end < _n) {
auto R12 = this->submatrix(block_begin, block_end, m, _n - block_end);
R11.apply_trap_q(R12, t1, n_removed + 1);
}
n_removed++;
}
this->enlarge_m(-cols_to_remove.size());
end = rdtsc();
PerfLog::get().log_total("REMOVE COLS QR BYTES", 2 * _m * _n);
PerfLog::get().log_total("REMOVE COLS QR TIME", end - start);
}
//Use givens rotations to annihilate the element below each diagonal element
void annihilate_subdiag_givens(Matrix<DT>& T)
{
for(int64_t i = 0; i < _n && i < _m-1; i++) {
//1. figure out Givens rotation to annihilate element below diagonal.
rotg(lea(i,i), lea(i+1,i), T.lea(0,i), T.lea(1,i));
//2. Trailing update of Givens rotation
if(i+1 < _n)
rot(_n-(i+1), lea(i,i+1), _cs, lea(i+1,i+1), _cs, T(0,i), T(1,i));
}
}
void apply_givens_rots(Matrix<DT>& T)
{
for(int64_t i = 0; i < _m-1; i++) {
rot(_n, lea(i,0), _cs, lea(i+1,0), _cs, T(0,i), T(1,i));
}
}
void remove_column_iqr_givens(int64_t column, Matrix<DT>& T, int64_t nb)
{
//First shift dense block above diagonal and to the right of the column removed
//to the left by one.
for(int i = 0; i < _m; i++) (*this)(i,column) = 0;
shift_dense_left(0, column, column, _n-column, 1);
//Proceed along the diagonal by blocks
for(int64_t i = column; i+1 < _n; i += nb)
{
//Partition the matrix
auto R11 = this->submatrix(i, i+1, nb+1, nb);
auto T1 = T.submatrix(0, i+1, 2, nb+1);
//Annihilate subdiagonal elements and shift left
R11.annihilate_subdiag_givens(T1);
shift_triangle_left(i, i, nb, 1);
//Trailing update
for(int64_t j = i + nb; j+1 < _n; j += nb) {
auto R12 = this->submatrix(i, j+1, nb+1, nb);
R12.apply_givens_rots(T1);
shift_dense_left(i, j, nb, nb, 1);
}
}
this->enlarge_m(-1);
this->enlarge_n(-1);
}
};
template<>
void Matrix<double>::mvm(double alpha, const Vector<double>& x, double beta, Vector<double>& y) const;
template<>
void Matrix<double>::trsv(CBLAS_UPLO uplo, Vector<double>& x) const;
template<>
void Matrix<double>::trsm(CBLAS_UPLO uplo, CBLAS_SIDE side, Matrix<double>& X) const;
template<>
void Matrix<double>::mmm(double alpha, const Matrix<double>& A, const Matrix<double>& B, double beta);
template<>
void Matrix<double>::syrk(CBLAS_UPLO uplo, double alpha, const Matrix<double>& A, double beta);
template<>
void Matrix<double>::qr(Vector<double>& t);
template<>
void Matrix<double>::chol(char uplo);
template<>
void Matrix<float>::chol(char uplo);
template<>
void Matrix<double>::tpqr(Matrix<double>& B, Matrix<double>& T, int64_t l_in, int64_t nb_in);
template<>
void Matrix<double>::apply_tpq(Matrix<double>& A, Matrix<double>& B, const Matrix<double>& T, int64_t l_in, int64_t nb_in, Matrix<double>& ws) const;
template<>
void Matrix<float>::mvm(float alpha, const Vector<float>& x, float beta, Vector<float>& y) const;
template<>
void Matrix<float>::trsv(CBLAS_UPLO uplo, Vector<float>& x) const;
template<>
void Matrix<float>::trsm(CBLAS_UPLO uplo, CBLAS_SIDE side, Matrix<float>& X) const;
template<>
void Matrix<float>::mmm(float alpha, const Matrix<float>& A, const Matrix<float>& B, float beta);
template<>
void Matrix<float>::syrk(CBLAS_UPLO uplo, float alpha, const Matrix<float>& A, float beta);
template<>
void Matrix<float>::qr(Vector<float>& t);
//Use tpqrt to annihilate rectangle above the triangle.
//Then stores the reflectors in that block
//TODO: handle row-major
template<>
void Matrix<float>::tpqr(Matrix<float>& B, Matrix<float>& T, int64_t l_in, int64_t nb_in);
template<>
void Matrix<float>::apply_tpq(Matrix<float>& A, Matrix<float>& B, const Matrix<float>& T, int64_t l_in, int64_t nb_in, Matrix<float>& ws) const;
#endif
|
GB_binop__min_uint16.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__min_uint16
// A.*B function (eWiseMult): GB_AemultB__min_uint16
// A*D function (colscale): GB_AxD__min_uint16
// D*A function (rowscale): GB_DxB__min_uint16
// C+=B function (dense accum): GB_Cdense_accumB__min_uint16
// C+=b function (dense accum): GB_Cdense_accumb__min_uint16
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__min_uint16
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__min_uint16
// C=scalar+B GB_bind1st__min_uint16
// C=scalar+B' GB_bind1st_tran__min_uint16
// C=A+scalar GB_bind2nd__min_uint16
// C=A'+scalar GB_bind2nd_tran__min_uint16
// C type: uint16_t
// A type: uint16_t
// B,b type: uint16_t
// BinaryOp: cij = GB_IMIN (aij, bij)
#define GB_ATYPE \
uint16_t
#define GB_BTYPE \
uint16_t
#define GB_CTYPE \
uint16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint16_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = GB_IMIN (x, y) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MIN || GxB_NO_UINT16 || GxB_NO_MIN_UINT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB_Cdense_ewise3_accum__min_uint16
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__min_uint16
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__min_uint16
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__min_uint16
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint16_t
uint16_t bwork = (*((uint16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__min_uint16
(
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
uint16_t *GB_RESTRICT Cx = (uint16_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__min_uint16
(
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
uint16_t *GB_RESTRICT Cx = (uint16_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__min_uint16
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__min_uint16
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__min_uint16
(
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
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t x = (*((uint16_t *) x_input)) ;
uint16_t *Bx = (uint16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t bij = Bx [p] ;
Cx [p] = GB_IMIN (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__min_uint16
(
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 ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t aij = Ax [p] ;
Cx [p] = GB_IMIN (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint16_t aij = Ax [pA] ; \
Cx [pC] = GB_IMIN (x, aij) ; \
}
GrB_Info GB_bind1st_tran__min_uint16
(
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 \
uint16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t x = (*((const uint16_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint16_t aij = Ax [pA] ; \
Cx [pC] = GB_IMIN (aij, y) ; \
}
GrB_Info GB_bind2nd_tran__min_uint16
(
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
uint16_t y = (*((const uint16_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
2d_array_ptr_v1.c | #include <stdlib.h>
#include <omp.h>
int main()
{
int** arr = malloc(sizeof(int*) * 2);
arr[0] = malloc(sizeof(int) * 2);
arr[1] = malloc(sizeof(int) * 2);
#pragma omp parallel
{
arr[0][0] = 0;
arr[0][1] = 1;
arr[1][0] = 2;
arr[1][1] = 3;
printf("[%d, %d]\n[%d, %d]\n", arr[0][0], arr[0][1], arr[1][0], arr[1][1]);
}
free(arr[0]);
free(arr[1]);
free(arr);
}
|
GB_unaryop__lnot_uint32_uint64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_uint32_uint64
// op(A') function: GB_tran__lnot_uint32_uint64
// C type: uint32_t
// A type: uint64_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
uint32_t z = (uint32_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_LNOT || GxB_NO_UINT32 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_uint32_uint64
(
uint32_t *restrict Cx,
const uint64_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_uint32_uint64
(
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
|
rwalk.c | #include "rwalk.h"
#include <omp.h>
#include <stdlib.h>
void random_walk(int const* starts, int const* ptr, int const* neighs, int n, int num_walks,
int num_steps, int seed, int nthread, float restart_prop, int* walks) {
if (nthread > 0) {
omp_set_num_threads(nthread);
}
#pragma omp parallel
{
int thread_num = omp_get_thread_num();
unsigned int private_seed = (unsigned int)(seed + thread_num);
#pragma omp for
for (int i = 0; i < n; i++) {
int offset, num_neighs;
for (int walk = 0; walk < num_walks; walk++) {
// int curr = i;
int curr = starts[i];
offset = i * num_walks * (num_steps + 1) + walk * (num_steps + 1);
walks[offset] = starts[i];
for (int step = 0; step < num_steps; step++) {
num_neighs = ptr[curr + 1] - ptr[curr];
if((restart_prop > 0) && (rand_r(&private_seed) / (double)RAND_MAX < restart_prop)){
curr = starts[i];
} else {
if (num_neighs > 0) {
curr = neighs[ptr[curr] + (rand_r(&private_seed) % num_neighs)];
}
}
walks[offset + step + 1] = curr;
}
}
}
}
}
|
GB_binop__second_fc64.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__second_fc64)
// A.*B function (eWiseMult): GB (_AemultB_08__second_fc64)
// A.*B function (eWiseMult): GB (_AemultB_02__second_fc64)
// A.*B function (eWiseMult): GB (_AemultB_04__second_fc64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__second_fc64)
// A*D function (colscale): GB (_AxD__second_fc64)
// D*A function (rowscale): GB (_DxB__second_fc64)
// C+=B function (dense accum): GB (_Cdense_accumB__second_fc64)
// C+=b function (dense accum): GB (_Cdense_accumb__second_fc64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_fc64)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// A pattern? 1
// B type: GxB_FC64_t
// B pattern? 0
// BinaryOp: cij = bij
#define GB_ATYPE \
GxB_FC64_t
#define GB_BTYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_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) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
GxB_FC64_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
GxB_FC64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = y ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
1
// 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_SECOND || GxB_NO_FC64 || GxB_NO_SECOND_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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__second_fc64)
(
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__second_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
{
#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__second_fc64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type GxB_FC64_t
GxB_FC64_t bwork = (*((GxB_FC64_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__second_fc64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *restrict Cx = (GxB_FC64_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__second_fc64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *restrict Cx = (GxB_FC64_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__second_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 is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
GxB_FC64_t alpha_scalar ;
GxB_FC64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC64_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC64_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__second_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_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__second_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_04__second_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_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__second_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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *Cx = (GxB_FC64_t *) 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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
GxB_FC64_t bij = GBX (Bx, p, false) ;
Cx [p] = bij ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
GxB_FC64_t *Cx = (GxB_FC64_t *) 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 ;
; ;
Cx [p] = y ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// 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 = GBX (Ax, pA, false) ; \
Cx [pC] = aij ; \
}
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = y ; \
}
GrB_Info GB ((none))
(
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
#endif
|
844.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 parallel for private(i, j) collapse(#P12) schedule(#P9, #P11) num_threads(#P11)
for (i = 1; i < _PB_NI - 1; ++i)
{
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;
}
|
XSHA_fmt_plug.c | /*
* This file is part of John the Ripper password cracker,
* Copyright (c) 2008,2011 by Solar Designer
*
* Intrinsics support added by magnum 2011.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_XSHA;
#elif FMT_REGISTERS_H
john_register_one(&fmt_XSHA);
#else
#include <string.h>
#include "arch.h"
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1)
#ifdef _OPENMP
static unsigned int omp_t = 1;
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 128
#endif
#endif
#endif
#include "simd-intrinsics.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#include "sha.h"
#include "johnswap.h"
#include "memdbg.h"
#define FORMAT_LABEL "xsha"
#define FORMAT_NAME "Mac OS X 10.4 - 10.6"
#define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 51
#define CIPHERTEXT_LENGTH 48
#define BINARY_SIZE 20
#define BINARY_ALIGN 4
#define SALT_SIZE 4
#define SALT_ALIGN 4
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT NBKEYS
#define MAX_KEYS_PER_CRYPT NBKEYS
#define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32*4 ) //for endianity conversion
#else
#define MIN_KEYS_PER_CRYPT 1
#ifdef _OPENMP
#define MAX_KEYS_PER_CRYPT (0x200 * 3)
#else
#define MAX_KEYS_PER_CRYPT 0x100
#endif
#endif
static struct fmt_tests tests[] = {
{"12345678F9083C7F66F46A0A102E4CC17EC08C8AF120571B", "abc"},
{"12345678EB8844BFAF2A8CBDD587A37EF8D4A290680D5818", "azertyuiop1"},
{"3234C32AAA335FD20E3F95870E5851BDBE942B79CE4FDD92", "azertyuiop2"},
{"01295B67659E95F32931CEDB3BA50289E2826AF3D5A1422F", "apple"},
{"0E6A48F765D0FFFFF6247FA80D748E615F91DD0C7431E4D9", "macintosh"},
{"A320163F1E6DB42C3949F7E232888ACC7DB7A0A17E493DBA", "test"},
{"743777471285CB3566886D4821D556E475E0DF9234308B22", "123"},
{"474379622BD7B9F84BD6E4BB52ABF9D01705EFB0A2426655", "passWOrd"},
{"597A523666A10C534495DB6333CF7EBA70C1A578CADE11A3", ""},
{NULL}
};
#ifdef SIMD_COEF_32
static ARCH_WORD_32 (*saved_key);
static ARCH_WORD_32 (*crypt_key);
static ARCH_WORD_32 cur_salt;
#else
static char saved_key[MAX_KEYS_PER_CRYPT][PLAINTEXT_LENGTH + 1];
static int saved_len[MAX_KEYS_PER_CRYPT];
static SHA_CTX ctx_salt;
static ARCH_WORD_32 crypt_out[MAX_KEYS_PER_CRYPT][5];
#endif
static void init(struct fmt_main *self)
{
#ifdef SIMD_COEF_32
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt = omp_t * NBKEYS;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt = omp_t * NBKEYS;
#endif
saved_key = mem_calloc_align(self->params.max_keys_per_crypt,
SHA_BUF_SIZ * 4, MEM_ALIGN_SIMD);
crypt_key = mem_calloc_align(self->params.max_keys_per_crypt,
BINARY_SIZE, MEM_ALIGN_SIMD);
#endif
}
static void done(void)
{
#ifdef SIMD_COEF_32
MEM_FREE(crypt_key);
MEM_FREE(saved_key);
#endif
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *pos;
/* Require uppercase hex digits (assume ASCII) */
pos = ciphertext;
while (atoi16[ARCH_INDEX(*pos)] != 0x7F && *pos < 'a')
pos++;
return !*pos && pos - ciphertext == CIPHERTEXT_LENGTH;
}
static void *get_binary(char *ciphertext)
{
static unsigned char *out;
char *p;
int i;
if (!out)
out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD);
p = ciphertext + 8;
for (i = 0; i < BINARY_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
#ifdef SIMD_COEF_32
alter_endianity(out, BINARY_SIZE);
#endif
return out;
}
static void *get_salt(char *ciphertext)
{
static unsigned int outbuf[SALT_SIZE / sizeof(int)];
unsigned char *out = (unsigned char*)outbuf;
char *p;
int i;
p = ciphertext;
for (i = 0; i < SALT_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
#ifdef SIMD_COEF_32
alter_endianity(out, SALT_SIZE);
#endif
return out;
}
#ifdef SIMD_COEF_32
static int get_hash_0(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_0;
}
static int get_hash_1(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_1;
}
static int get_hash_2(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_2;
}
static int get_hash_3(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_3;
}
static int get_hash_4(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_4;
}
static int get_hash_5(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_5;
}
static int get_hash_6(int index)
{
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*5] & PH_MASK_6;
}
#else
static int get_hash_0(int index)
{
return crypt_out[index][0] & PH_MASK_0;
}
static int get_hash_1(int index)
{
return crypt_out[index][0] & PH_MASK_1;
}
static int get_hash_2(int index)
{
return crypt_out[index][0] & PH_MASK_2;
}
static int get_hash_3(int index)
{
return crypt_out[index][0] & PH_MASK_3;
}
static int get_hash_4(int index)
{
return crypt_out[index][0] & PH_MASK_4;
}
static int get_hash_5(int index)
{
return crypt_out[index][0] & PH_MASK_5;
}
static int get_hash_6(int index)
{
return crypt_out[index][0] & PH_MASK_6;
}
#endif
static int salt_hash(void *salt)
{
return *(ARCH_WORD_32 *)salt & (SALT_HASH_SIZE - 1);
}
static void set_salt(void *salt)
{
#ifdef SIMD_COEF_32
cur_salt = *(ARCH_WORD_32*)salt;
#else
SHA1_Init(&ctx_salt);
SHA1_Update(&ctx_salt, salt, SALT_SIZE);
#endif
}
static void set_key(char *key, int index)
{
#ifdef SIMD_COEF_32
#if ARCH_ALLOWS_UNALIGNED
const ARCH_WORD_32 *wkey = (ARCH_WORD_32*)key;
#else
char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint32_t));
const ARCH_WORD_32 *wkey = (uint32_t*)(is_aligned(key, sizeof(uint32_t)) ?
key : strcpy(buf_aligned, key));
#endif
ARCH_WORD_32 *keybuffer = &saved_key[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32 + SIMD_COEF_32];
ARCH_WORD_32 *keybuf_word = keybuffer;
unsigned int len;
ARCH_WORD_32 temp;
len = 4;
while((temp = *wkey++) & 0xff) {
if (!(temp & 0xff00))
{
*keybuf_word = JOHNSWAP((temp & 0xff) | (0x80 << 8));
len++;
goto key_cleaning;
}
if (!(temp & 0xff0000))
{
*keybuf_word = JOHNSWAP((temp & 0xffff) | (0x80 << 16));
len+=2;
goto key_cleaning;
}
if (!(temp & 0xff000000))
{
*keybuf_word = JOHNSWAP(temp | (0x80U << 24));
len+=3;
goto key_cleaning;
}
*keybuf_word = JOHNSWAP(temp);
len += 4;
keybuf_word += SIMD_COEF_32;
}
*keybuf_word = 0x80000000;
key_cleaning:
keybuf_word += SIMD_COEF_32;
while(*keybuf_word) {
*keybuf_word = 0;
keybuf_word += SIMD_COEF_32;
}
keybuffer[14*SIMD_COEF_32] = len << 3;
#else
int length = strlen(key);
if (length > PLAINTEXT_LENGTH)
length = PLAINTEXT_LENGTH;
saved_len[index] = length;
memcpy(saved_key[index], key, length);
#endif
}
static char *get_key(int index)
{
#ifdef SIMD_COEF_32
unsigned int i,s;
static char out[PLAINTEXT_LENGTH + 1];
s = ((unsigned int *)saved_key)[15*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] >> 3;
for(i = 0; i < (s - SALT_SIZE); i++)
out[i] = ((char*)saved_key)[ GETPOS((i + SALT_SIZE), index) ];
out[i] = 0;
return (char *) out;
#else
saved_key[index][saved_len[index]] = 0;
return saved_key[index];
#endif
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
#ifdef SIMD_COEF_32
int i = 0;
#if defined(_OPENMP)
#pragma omp parallel for
for (i=0; i < omp_t; i++) {
#endif
unsigned int *in = &saved_key[i*NBKEYS*SHA_BUF_SIZ];
unsigned int *out = &crypt_key[i*NBKEYS*BINARY_SIZE/4];
unsigned int j;
for (j=0; j < NBKEYS; j++)
in[(j&(SIMD_COEF_32-1)) + j/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = cur_salt;
SIMDSHA1body(in, out, NULL, SSEi_MIXED_IN);
#if defined(_OPENMP)
}
#endif
#else
int i;
#ifdef _OPENMP
#pragma omp parallel for default(none) private(i) shared(ctx_salt, saved_key, saved_len, crypt_out)
#endif
for (i = 0; i < count; i++) {
SHA_CTX ctx;
memcpy(&ctx, &ctx_salt, sizeof(ctx));
SHA1_Update(&ctx, saved_key[i], saved_len[i]);
SHA1_Final((unsigned char *)(crypt_out[i]), &ctx);
}
#endif
return count;
}
static int cmp_all(void *binary, int count)
{
#ifdef SIMD_COEF_32
unsigned int x,y=0;
#ifdef _OPENMP
for(;y<SIMD_PARA_SHA1*omp_t;y++)
#else
for(;y<SIMD_PARA_SHA1;y++)
#endif
for(x=0;x<SIMD_COEF_32;x++)
{
if( ((ARCH_WORD_32 *)binary)[0] == ((ARCH_WORD_32 *)crypt_key)[x+y*SIMD_COEF_32*5] )
return 1;
}
return 0;
#else
ARCH_WORD_32 b0 = *(ARCH_WORD_32 *)binary;
int i;
for (i = 0; i < count; i++) {
if (b0 != crypt_out[i][0])
continue;
if (!memcmp(binary, crypt_out[i], BINARY_SIZE))
return 1;
}
return 0;
#endif
}
static int cmp_one(void *binary, int index)
{
#ifdef SIMD_COEF_32
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
if( ((ARCH_WORD_32 *)binary)[0] != ((ARCH_WORD_32 *)crypt_key)[x+y*SIMD_COEF_32*5] )
return 0;
if( ((ARCH_WORD_32 *)binary)[1] != ((ARCH_WORD_32 *)crypt_key)[x+y*SIMD_COEF_32*5+SIMD_COEF_32] )
return 0;
if( ((ARCH_WORD_32 *)binary)[2] != ((ARCH_WORD_32 *)crypt_key)[x+y*SIMD_COEF_32*5+2*SIMD_COEF_32] )
return 0;
if( ((ARCH_WORD_32 *)binary)[3] != ((ARCH_WORD_32 *)crypt_key)[x+y*SIMD_COEF_32*5+3*SIMD_COEF_32] )
return 0;
if( ((ARCH_WORD_32 *)binary)[4] != ((ARCH_WORD_32 *)crypt_key)[x+y*SIMD_COEF_32*5+4*SIMD_COEF_32] )
return 0;
return 1;
#else
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
#endif
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_XSHA = {
{
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_OMP | FMT_OMP_BAD | FMT_CASE | FMT_8_BIT,
{ NULL },
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
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
displacement_lagrangemultiplier_mixed_frictional_contact_criteria.h | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H)
#define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H
/* System includes */
/* External includes */
/* Project includes */
#include "utilities/table_stream_utility.h"
#include "utilities/color_utilities.h"
#include "solving_strategies/convergencecriterias/convergence_criteria.h"
#include "custom_utilities/active_set_utilities.h"
#include "custom_utilities/contact_utilities.h"
#include "utilities/constraint_utilities.h"
namespace Kratos
{
///@addtogroup ContactStructuralMechanicsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@name Kratos Classes
///@{
/**
* @class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
* @ingroup ContactStructuralMechanicsApplication
* @brief Convergence criteria for contact problems
* @details This class implements a convergence control based on nodal displacement and
* lagrange multiplier values. The error is evaluated separately for each of them, and
* relative and absolute tolerances for both must be specified.
* @author Vicente Mataix Ferrandiz
*/
template< class TSparseSpace,
class TDenseSpace >
class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
: public ConvergenceCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria );
/// Local Flags
KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT );
KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT );
KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED );
KRATOS_DEFINE_LOCAL_FLAG( PURE_SLIP );
KRATOS_DEFINE_LOCAL_FLAG( INITIAL_RESIDUAL_IS_SET );
/// The base class definition (and it subclasses)
typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
/// The sparse space used
typedef TSparseSpace SparseSpaceType;
/// The r_table stream definition TODO: Replace by logger
typedef TableStreamUtility::Pointer TablePrinterPointerType;
/// The index type definition
typedef std::size_t IndexType;
/// The key type definition
typedef std::size_t KeyType;
/// The epsilon tolerance definition
static constexpr double Tolerance = std::numeric_limits<double>::epsilon();
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor.
* @param DispRatioTolerance Relative tolerance for displacement residual error
* @param DispAbsTolerance Absolute tolerance for displacement residual error
* @param LMRatioTolerance Relative tolerance for lagrange multiplier residual error
* @param LMAbsTolerance Absolute tolerance for lagrange multiplier residual error
* @param NormalTangentRatio Ratio between the normal and tangent that will accepted as converged
* @param EnsureContact To check if the contact is lost
* @param pTable The pointer to the output r_table
* @param PrintingOutput If the output is going to be printed in a txt file
*/
explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria(
const TDataType DispRatioTolerance,
const TDataType DispAbsTolerance,
const TDataType LMNormalRatioTolerance,
const TDataType LMNormalAbsTolerance,
const TDataType LMTangentStickRatioTolerance,
const TDataType LMTangentStickAbsTolerance,
const TDataType LMTangentSlipRatioTolerance,
const TDataType LMTangentSlipAbsTolerance,
const TDataType NormalTangentRatio,
const bool EnsureContact = false,
const bool PureSlip = false,
const bool PrintingOutput = false
)
: BaseType()
{
// Set local flags
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, EnsureContact);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, PrintingOutput);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, PureSlip);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
// The displacement residual
mDispRatioTolerance = DispRatioTolerance;
mDispAbsTolerance = DispAbsTolerance;
// The normal contact residual
mLMNormalRatioTolerance = LMNormalRatioTolerance;
mLMNormalAbsTolerance = LMNormalAbsTolerance;
// The tangent contact residual
mLMTangentStickRatioTolerance = LMTangentStickRatioTolerance;
mLMTangentStickAbsTolerance = LMTangentStickAbsTolerance;
mLMTangentSlipRatioTolerance = LMTangentSlipRatioTolerance;
mLMTangentSlipAbsTolerance = LMTangentSlipAbsTolerance;
// We get the ratio between the normal and tangent that will accepted as converged
mNormalTangentRatio = NormalTangentRatio;
}
/**
* @brief Default constructor (parameters)
* @param ThisParameters The configuration parameters
*/
explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( Parameters ThisParameters = Parameters(R"({})"))
: BaseType()
{
// The default parameters
Parameters default_parameters = Parameters(R"(
{
"ensure_contact" : false,
"pure_slip" : false,
"print_convergence_criterion" : false,
"residual_relative_tolerance" : 1.0e-4,
"residual_absolute_tolerance" : 1.0e-9,
"contact_displacement_relative_tolerance" : 1.0e-4,
"contact_displacement_absolute_tolerance" : 1.0e-9,
"frictional_stick_contact_displacement_relative_tolerance" : 1.0e-4,
"frictional_stick_contact_residual_relative_tolerance" : 1.0e-9,
"frictional_slip_contact_displacement_relative_tolerance" : 1.0e-4,
"frictional_slip_contact_residual_relative_tolerance" : 1.0e-9,
"ratio_normal_tangent_threshold" : 1.0e-4
})" );
ThisParameters.ValidateAndAssignDefaults(default_parameters);
// The displacement residual
mDispRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble();
mDispAbsTolerance = ThisParameters["residual_absolute_tolerance"].GetDouble();
// The normal contact solution
mLMNormalRatioTolerance = ThisParameters["contact_displacement_relative_tolerance"].GetDouble();
mLMNormalAbsTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble();
// The tangent contact solution
mLMTangentStickRatioTolerance = ThisParameters["frictional_stick_contact_displacement_relative_tolerance"].GetDouble();
mLMTangentStickAbsTolerance = ThisParameters["frictional_stick_contact_residual_relative_tolerance"].GetDouble();
mLMTangentSlipRatioTolerance = ThisParameters["frictional_slip_contact_displacement_relative_tolerance"].GetDouble();
mLMTangentSlipAbsTolerance = ThisParameters["frictional_slip_contact_residual_relative_tolerance"].GetDouble();
// We get the ratio between the normal and tangent that will accepted as converged
mNormalTangentRatio = ThisParameters["ratio_normal_tangent_threshold"].GetDouble();
// Set local flags
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, ThisParameters["pure_slip"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
}
//* Copy constructor.
DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria const& rOther )
:BaseType(rOther)
,mOptions(rOther.mOptions)
,mDispRatioTolerance(rOther.mDispRatioTolerance)
,mDispAbsTolerance(rOther.mDispAbsTolerance)
,mDispInitialResidualNorm(rOther.mDispInitialResidualNorm)
,mDispCurrentResidualNorm(rOther.mDispCurrentResidualNorm)
,mLMNormalRatioTolerance(rOther.mLMNormalRatioTolerance)
,mLMNormalAbsTolerance(rOther.mLMNormalAbsTolerance)
,mLMTangentStickRatioTolerance(rOther.mLMTangentStickRatioTolerance)
,mLMTangentStickAbsTolerance(rOther.mLMTangentStickAbsTolerance)
,mLMTangentSlipRatioTolerance(rOther.mLMTangentSlipRatioTolerance)
,mLMTangentSlipAbsTolerance(rOther.mLMTangentSlipAbsTolerance)
,mNormalTangentRatio(rOther.mNormalTangentRatio)
{
}
/// Destructor.
~DisplacementLagrangeMultiplierMixedFrictionalContactCriteria() override = default;
///@}
///@name Operators
///@{
/**
* @brief Compute relative and absolute error.
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
* @return true if convergence is achieved, false otherwise
*/
bool PostCriteria(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
if (SparseSpaceType::Size(rb) != 0) { //if we are solving for something
// Getting process info
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Initialize
TDataType disp_residual_solution_norm = 0.0, normal_lm_solution_norm = 0.0, normal_lm_increase_norm = 0.0, tangent_lm_stick_solution_norm = 0.0, tangent_lm_slip_solution_norm = 0.0, tangent_lm_stick_increase_norm = 0.0, tangent_lm_slip_increase_norm = 0.0;
IndexType disp_dof_num(0),lm_dof_num(0),lm_stick_dof_num(0),lm_slip_dof_num(0);
// The nodes array
auto& r_nodes_array = rModelPart.Nodes();
// First iterator
const auto it_dof_begin = rDofSet.begin();
// Auxiliar values
std::size_t dof_id = 0;
TDataType residual_dof_value = 0.0, dof_value = 0.0, dof_incr = 0.0;
// The number of active dofs
const std::size_t number_active_dofs = rb.size();
// Loop over Dofs
#pragma omp parallel for firstprivate(dof_id, residual_dof_value, dof_value, dof_incr) reduction(+:disp_residual_solution_norm,normal_lm_solution_norm,normal_lm_increase_norm,disp_dof_num,lm_dof_num, lm_stick_dof_num, lm_slip_dof_num)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = it_dof_begin + i;
dof_id = it_dof->EquationId();
// Check dof id is solved
if (dof_id < number_active_dofs) {
if (mActiveDofs[dof_id]) {
const auto& r_curr_var = it_dof->GetVariable();
if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_X) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
dof_value = it_dof->GetSolutionStepValue(0);
dof_incr = rDx[dof_id];
const double mu = it_node->GetValue(FRICTION_COEFFICIENT);
if (mu < std::numeric_limits<double>::epsilon()) {
normal_lm_solution_norm += std::pow(dof_value, 2);
normal_lm_increase_norm += std::pow(dof_incr, 2);
} else {
const double normal_x = it_node->FastGetSolutionStepValue(NORMAL_X);
const TDataType normal_dof_value = dof_value * normal_x;
const TDataType normal_dof_incr = dof_incr * normal_x;
normal_lm_solution_norm += std::pow(normal_dof_value, 2);
normal_lm_increase_norm += std::pow(normal_dof_incr, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_stick_dof_num;
}
}
++lm_dof_num;
} else if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
dof_value = it_dof->GetSolutionStepValue(0);
dof_incr = rDx[dof_id];
const double mu = it_node->GetValue(FRICTION_COEFFICIENT);
if (mu < std::numeric_limits<double>::epsilon()) {
normal_lm_solution_norm += std::pow(dof_value, 2);
normal_lm_increase_norm += std::pow(dof_incr, 2);
} else {
const double normal_y = it_node->FastGetSolutionStepValue(NORMAL_Y);
const TDataType normal_dof_value = dof_value * normal_y;
const TDataType normal_dof_incr = dof_incr * normal_y;
normal_lm_solution_norm += std::pow(normal_dof_value, 2);
normal_lm_increase_norm += std::pow(normal_dof_incr, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_stick_dof_num;
}
}
++lm_dof_num;
} else if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
dof_value = it_dof->GetSolutionStepValue(0);
dof_incr = rDx[dof_id];
const double mu = it_node->GetValue(FRICTION_COEFFICIENT);
if (mu < std::numeric_limits<double>::epsilon()) {
normal_lm_solution_norm += std::pow(dof_value, 2);
normal_lm_increase_norm += std::pow(dof_incr, 2);
} else {
const double normal_z = it_node->FastGetSolutionStepValue(NORMAL_Z);
const TDataType normal_dof_value = dof_value * normal_z;
const TDataType normal_dof_incr = dof_incr * normal_z;
normal_lm_solution_norm += std::pow(normal_dof_value, 2);
normal_lm_increase_norm += std::pow(normal_dof_incr, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_stick_dof_num;
}
}
++lm_dof_num;
} else { // We will assume is displacement dof
residual_dof_value = rb[dof_id];
disp_residual_solution_norm += residual_dof_value * residual_dof_value;
++disp_dof_num;
}
}
}
}
if(normal_lm_increase_norm < Tolerance) normal_lm_increase_norm = 1.0;
if(tangent_lm_stick_increase_norm < Tolerance) tangent_lm_stick_increase_norm = 1.0;
if(tangent_lm_slip_increase_norm < Tolerance) tangent_lm_slip_increase_norm = 1.0;
KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm < Tolerance) << "ERROR::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl;
mDispCurrentResidualNorm = disp_residual_solution_norm;
const TDataType normal_lm_ratio = std::sqrt(normal_lm_increase_norm/normal_lm_solution_norm);
const TDataType tangent_lm_slip_ratio = tangent_lm_slip_solution_norm > Tolerance ? std::sqrt(tangent_lm_slip_increase_norm/tangent_lm_slip_solution_norm) : 0.0;
const TDataType tangent_lm_stick_ratio = tangent_lm_stick_solution_norm > Tolerance ? std::sqrt(tangent_lm_stick_increase_norm/tangent_lm_stick_solution_norm) : 0.0;
const TDataType normal_lm_abs = std::sqrt(normal_lm_increase_norm)/static_cast<TDataType>(lm_dof_num);
const TDataType tangent_lm_stick_abs = lm_stick_dof_num > 0 ? std::sqrt(tangent_lm_stick_increase_norm)/ static_cast<TDataType>(lm_stick_dof_num) : 0.0;
const TDataType tangent_lm_slip_abs = lm_slip_dof_num > 0 ? std::sqrt(tangent_lm_slip_increase_norm)/ static_cast<TDataType>(lm_slip_dof_num) : 0.0;
const TDataType normal_tangent_stick_ratio = tangent_lm_stick_abs/normal_lm_abs;
const TDataType normal_tangent_slip_ratio = tangent_lm_slip_abs/normal_lm_abs;
TDataType residual_disp_ratio;
// We initialize the solution
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET)) {
mDispInitialResidualNorm = (disp_residual_solution_norm < Tolerance) ? 1.0 : disp_residual_solution_norm;
residual_disp_ratio = 1.0;
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, true);
}
// We calculate the ratio of the displacements
residual_disp_ratio = mDispCurrentResidualNorm/mDispInitialResidualNorm;
// We calculate the absolute norms
TDataType residual_disp_abs = mDispCurrentResidualNorm/disp_dof_num;
// We print the results // TODO: Replace for the new log
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
std::cout.precision(4);
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_stick_ratio << mLMTangentStickRatioTolerance << tangent_lm_stick_abs << mLMTangentSlipAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentStickAbsTolerance;
} else {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentSlipAbsTolerance;
}
} else {
std::cout.precision(4);
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) {
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("MIXED CONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << residual_disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << residual_disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tNORMAL LAGRANGE MUL: RATIO = ") << normal_lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMNormalRatioTolerance << BOLDFONT(" ABS = ") << normal_lm_abs << BOLDFONT(" EXP.ABS = ") << mLMNormalAbsTolerance << std::endl;
KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << BOLDFONT(" STICK LAGRANGE MUL:\tRATIO = ") << tangent_lm_stick_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentStickRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_stick_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentStickAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT(" SLIP LAGRANGE MUL:\tRATIO = ") << tangent_lm_slip_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentSlipRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_slip_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentSlipAbsTolerance << std::endl;
} else {
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "MIXED CONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tDISPLACEMENT: RATIO = " << residual_disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << residual_disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tNORMAL LAGRANGE MUL: RATIO = " << normal_lm_ratio << " EXP.RATIO = " << mLMNormalRatioTolerance << " ABS = " << normal_lm_abs << " EXP.ABS = " << mLMNormalAbsTolerance << std::endl;
KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << " STICK LAGRANGE MUL:\tRATIO = " << tangent_lm_stick_ratio << " EXP.RATIO = " << mLMTangentStickRatioTolerance << " ABS = " << tangent_lm_stick_abs << " EXP.ABS = " << mLMTangentStickAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << " SLIP LAGRANGE MUL:\tRATIO = " << tangent_lm_slip_ratio << " EXP.RATIO = " << mLMTangentSlipRatioTolerance << " ABS = " << tangent_lm_slip_abs << " EXP.ABS = " << mLMTangentSlipAbsTolerance << std::endl;
}
}
}
// NOTE: Here we don't include the tangent counter part
r_process_info[CONVERGENCE_RATIO] = (residual_disp_ratio > normal_lm_ratio) ? residual_disp_ratio : normal_lm_ratio;
r_process_info[RESIDUAL_NORM] = (normal_lm_abs > mLMNormalAbsTolerance) ? normal_lm_abs : mLMNormalAbsTolerance;
// We check if converged
const bool disp_converged = (residual_disp_ratio <= mDispRatioTolerance || residual_disp_abs <= mDispAbsTolerance);
const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm < Tolerance) ? true : (normal_lm_ratio <= mLMNormalRatioTolerance || normal_lm_abs <= mLMNormalAbsTolerance) && (tangent_lm_stick_ratio <= mLMTangentStickRatioTolerance || tangent_lm_stick_abs <= mLMTangentStickAbsTolerance || normal_tangent_stick_ratio <= mNormalTangentRatio) && (tangent_lm_slip_ratio <= mLMTangentSlipRatioTolerance || tangent_lm_slip_abs <= mLMTangentSlipAbsTolerance || normal_tangent_slip_ratio <= mNormalTangentRatio);
if ( disp_converged && lm_converged ) {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
r_table << BOLDFONT(FGRN(" Achieved"));
else
r_table << "Achieved";
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FGRN("achieved")) << std::endl;
else
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is achieved" << std::endl;
}
}
return true;
} else {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
r_table << BOLDFONT(FRED(" Not achieved"));
else
r_table << "Not achieved";
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FRED(" not achieved")) << std::endl;
else
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is not achieved" << std::endl;
}
}
return false;
}
} else // In this case all the displacements are imposed!
return true;
}
/**
* @brief This function initialize the convergence criteria
* @param rModelPart Reference to the ModelPart containing the contact problem. (unused)
*/
void Initialize( ModelPart& rModelPart) override
{
BaseType::mConvergenceCriteriaIsInitialized = true;
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
r_table.AddColumn("DP RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
r_table.AddColumn("N.LM RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
r_table.AddColumn("STI. RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
}
r_table.AddColumn("SLIP RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
r_table.AddColumn("CONVERGENCE", 15);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, true);
}
}
/**
* @brief This function initializes the solution step
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
*/
void InitializeSolutionStep(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
// Initialize flags
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
// Filling mActiveDofs when MPC exist
ConstraintUtilities::ComputeActiveDofs(rModelPart, mActiveDofs, rDofSet);
}
/**
* @brief This function finalizes the non-linear iteration
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual + reactions)
*/
void FinalizeNonLinearIteration(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
// Calling base criteria
BaseType::FinalizeNonLinearIteration(rModelPart, rDofSet, rA, rDx, rb);
// The current process info
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
r_process_info.SetValue(ACTIVE_SET_COMPUTED, false);
}
///@}
///@name Operations
///@{
///@}
///@name Acces
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
Flags mOptions; /// Local flags
TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement residual
TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement residual
TDataType mDispInitialResidualNorm; /// The reference norm of the displacement residual
TDataType mDispCurrentResidualNorm; /// The current norm of the displacement residual
TDataType mLMNormalRatioTolerance; /// The ratio threshold for the norm of the LM (normal)
TDataType mLMNormalAbsTolerance; /// The absolute value threshold for the norm of the LM (normal)
TDataType mLMTangentStickRatioTolerance; /// The ratio threshold for the norm of the LM (tangent-stick)
TDataType mLMTangentStickAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent-stick)
TDataType mLMTangentSlipRatioTolerance; /// The ratio threshold for the norm of the LM (tangent-slip)
TDataType mLMTangentSlipAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent-slip)
TDataType mNormalTangentRatio; /// The ratio to accept a non converged tangent component in case
std::vector<bool> mActiveDofs; /// This vector contains the dofs that are active
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Unaccessible methods
///@{
///@}
}; // Kratos DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
///@name Local flags creation
///@{
/// Local Flags
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_ENSURE_CONTACT(Kratos::Flags::Create(0, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PRINTING_OUTPUT(Kratos::Flags::Create(1, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_TABLE_IS_INITIALIZED(Kratos::Flags::Create(2, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PURE_SLIP(Kratos::Flags::Create(3));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PURE_SLIP(Kratos::Flags::Create(3, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4, false));
}
#endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H */
|
spgemm-petsc.c | #include <petscmat.h>
#include "omp.h"
static char help[] = "help yourself!";
int
main (int argc, char **argv)
{
Mat A, B, C;
PetscViewer fd;
PetscInt m, n;
MatInfo info;
double nnz;
int niters;
PetscInitialize(&argc, &argv, (char*)0, help);
int nthds, np;
MPI_Comm_size(MPI_COMM_WORLD, &np);
#pragma omp parallel
{
nthds = omp_get_num_threads();
}
niters = atoi(argv[4]);
PetscPrintf(PETSC_COMM_WORLD, "np %d nthds %d\n", np, nthds);
double read_mat_beg = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "reading matrix %s (A)\n", argv[1]);
PetscViewerBinaryOpen(PETSC_COMM_WORLD, argv[1] ,FILE_MODE_READ, &fd);
MatCreate(PETSC_COMM_WORLD, &A);
MatSetType(A, MATMPIAIJ);
MatLoad(A, fd);
PetscViewerDestroy(&fd);
MatGetSize(A, &m, &n);
MatGetInfo(A, MAT_GLOBAL_SUM, &info);
PetscPrintf(PETSC_COMM_WORLD, "A matrix size %d %d %lld\n",
m, n, (long long int)info.nz_used);
PetscPrintf(PETSC_COMM_WORLD, "reading matrix %s (B)\n", argv[2]);
PetscViewerBinaryOpen(PETSC_COMM_WORLD, argv[2] ,FILE_MODE_READ, &fd);
MatCreate(PETSC_COMM_WORLD, &B);
MatSetType(B, MATMPIAIJ);
MatLoad(B, fd);
PetscViewerDestroy(&fd);
MatGetSize(B, &m, &n);
MatGetInfo(B, MAT_GLOBAL_SUM, &info);
PetscPrintf(PETSC_COMM_WORLD, "B matrix size %d %d %lld\n",
m, n, (long long int)info.nz_used);
double read_mat_end = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "Performing SpGEMM\n");
int i;
double start_time = MPI_Wtime();
for (i = 0; i < niters; ++i)
{
MatMatMult(A, B, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &C);
}
double end_time = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "IO %lf spgemm %lf\n",
read_mat_end-read_mat_beg,
(end_time-start_time)/niters);
MatGetSize(C, &m, &n);
MatGetInfo(C, MAT_GLOBAL_SUM, &info);
PetscPrintf(PETSC_COMM_WORLD, "C matrix size %d %d %lld\n",
m, n, (long long int)info.nz_used);
/* PetscPrintf(PETSC_COMM_WORLD, "Writing the output matrix\n"); */
/* PetscViewerBinaryOpen(PETSC_COMM_WORLD, argv[3], FILE_MODE_WRITE, &fd); */
/* MatView(C, fd); */
MatDestroy(&A);
MatDestroy(&B);
MatDestroy(&C);
PetscFinalize();
return 0;
}
|
Shell_sort.h | // Copyright 2021 Streltsova Yana
#ifndef MODULES_TASK_2_STRELTSOVA_Y_SHELL_SORT_SHELL_SORT_H_
#define MODULES_TASK_2_STRELTSOVA_Y_SHELL_SORT_SHELL_SORT_H_
#include <omp.h>
#include <utility>
#include <vector>
std::vector<int> getRandomVectorInt(int sz);
std::vector<double> getRandomVectorDouble(int sz);
template< typename T >
std::vector<T> shell_sort_sequential(const std::vector<T>& vec) {
std::vector<T> result(vec);
int d = 4;
while (d > 0) {
for (size_t i = 0; i < result.size(); i++) {
for (size_t j = i + d; j < result.size(); j += d) {
if (result[i] > result[j])
std::swap(result[i], result[j]);
}
}
d /= 2;
}
return result;
}
template< typename T >
std::vector<T> shell_sort_parallel(const std::vector<T>& vec) {
if (vec.size() < 1000)
return shell_sort_sequential(vec);
std::vector<T> result(vec);
int d = 4;
while (d > 0) {
omp_set_num_threads(d);
#pragma omp parallel
{
int tid = omp_get_thread_num();
for (size_t i = tid; i < result.size(); i += d)
for (size_t j = i + d; j < result.size(); j += d) {
if (result[i] > result[j])
std::swap(result[i], result[j]);
}
}
d /= 2;
}
return result;
}
#endif // MODULES_TASK_2_STRELTSOVA_Y_SHELL_SORT_SHELL_SORT_H_
|
multipleCBQuantizedLQPFeatures.h | /*
Copyright (c) 2013, Sibt ul Hussain <sibt.ul.hussain at gmail dot com>
All rights reserved.
Released under BSD License
-------------------------
For license terms please see license.lic
*/
#ifndef MULTIPLECBQUANTIZEDLQPFEATURES_H_
#define MULTIPLECBQUANTIZEDLQPFEATURES_H_
#include "encodedPatchFeatures.h"
#include "omp.h"
/// LQP Quantization, Features are quantized against each cell codebook
class MultipleCBQuantizeLQPFeatures: public EncodedPatchFeatures {
public:
MultipleCBQuantizeLQPFeatures(const LBPParams &lbpparam, UINT width_,
UINT height_, UINT nplevels, ProcessImage &pim_,
const PatchParams& pparam) :
EncodedPatchFeatures(lbpparam, width_, height_, nplevels, pim_, pparam) {
// Histogram Parameters
delete codeinfo;
codeinfo = NULL; // to be used for dellocation of memory
char tvar[2525];
string patchtype = PatchParams::GetPatchType(ptype);
ostringstream oss;
oss << "MCBQ-CI-Pos" << patchtype << "-" << patchsize << "-"
<< ncenters;
cifilename = oss.str();
oss.str("");
oss << "MCBQ-CB-Pos" << patchtype << "-" << patchsize << "-"
<< ncenters;
cbfilename = oss.str();
// for negative side lqp
oss.str("");
oss << "MCBQ-CI-Neg" << patchtype << "-" << patchsize << "-"
<< ncenters;
ncifilename = oss.str();
oss.str("");
oss << "MCBQ-CB-Neg" << patchtype << "-" << patchsize << "-"
<< ncenters;
ncbfilename = oss.str();
switch (cbtype) {
case CBT_PosCropNegSampled:
case CBT_PosPyramidNegSampled:
case CBT_MultiClass:
ncbs = 2;
featdim = ncbs * ncenters;
break;
case CBT_ConstantPosCellNeg:
case CBT_PosCellNeg:
case CBT_PosCellNegSep:
case CBT_ConstantPosCellNegSingleQuantization: // see the inherited class MultipleCBQuantizeLQPFeaturesHistogram
// featdim = ncenters * 2;/*dim of each cell because it is mapped against its own codebook &-ve cb*/
// only doing this during returning the features to classifiers, while doing computation
// each cell is quantized against all the codebooks., so featdim for each cell is
ncbs = cwidth * cheight + 1;
featdim = ncenters * ncbs;
case CBT_CellQuantizeAll: /// cell quantization doing against all the cells codebooks
ncbs = cwidth * cheight;
featdim = ncenters * ncbs; // each cell is quantized against all the codebooks
}
UINT *npmult = pparam.npmult;
pcbooks.resize(ncbs, 0); /*Only LTP based CodeBooks are implemented...*/
if (petype == PET_SplitLTP) {
ncbooks.resize(ncbs, 0); /*Only LTP based CodeBooks are implemented...*/
featdim = featdim * 2;
for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter =
ncbooks.begin(); iter != pcbooks.end(); ++iter, ++niter) {
*iter = new ComputeCodeLBP(ltplevels, npoints * npmult[ptype],
ncenters, softq, meanp, pparam.pcount);
*niter = new ComputeCodeLBP(ltplevels, npoints * npmult[ptype],
ncenters, softq, meanp, pparam.pcount);
}
} else {
for (vector<ComputeCode*>::iterator iter = pcbooks.begin(); iter
!= pcbooks.end(); ++iter)
*iter = new ComputeCodeLTP(ltplevels, npoints * npmult[ptype],
ncenters, softq, meanp, pparam.pcount);
}
nwinsampled = cbparams->nwinsampled;
//
//----------------- Print Parameter Info -----------
cout << "\n ----------------- Mulitple CB Encoded Parameter Info "
"----------- " << endl << "Number of CodeBooks = " << ncbs << endl
<< " Feature Dim = " << featdim << endl << " CodeBookFileName"
<< cbfilename << endl << " Number of Window Sampled ="
<< nwinsampled
<< "\n--------------------------------------------\n";
}
// GetDim returns the size of feature in a window without considering offset...
virtual ~MultipleCBQuantizeLQPFeatures() {
for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter =
ncbooks.begin(); iter != pcbooks.end(); ++iter, ++niter) {
delete *iter;
delete *niter;
}
}
virtual UINT GetDim(UINT width_, UINT height_) const {
return GetFeatDim(width_, height_);
}
virtual UINT GetHOGDim(UINT width_, UINT height_) const {
return 0;
}
virtual UINT GetLBPDim(UINT width_, UINT height_) const {
return GetFeatDim(width_, height_);;
}
virtual UINT GetFoldedLBPDim(UINT width_, UINT height_) const {
return GetFeatDim(width_, height_);;
}
virtual UINT GetFoldedHOGDim(UINT width_, UINT height_) const {
return 0;
}
virtual UINT GetFoldedDim(UINT width_, UINT height_) const {
return GetFeatDim(width_, height_);
}
virtual void InitalizeMaps(Image &, PyramidType);
virtual void InitalizeMaps(Image &image);
virtual void InitalizeMaps(Pyramid & pyobj_, PyramidType);
virtual void GetFeatures(UINT, int, int, int, int, vector<REAL>&);
virtual void GetFeatures(UINT, int, int, int, int, REAL*);
virtual void GetFoldedFeatures(UINT, int, int, int, int, vector<REAL>&);
virtual void GetFoldedFeatures(UINT, int, int, int, int, REAL*);
virtual UINT GetInitIndex() {
return sspace == DoubleRes ? pyobj.GetInitIndex() : 0;
}
virtual void PadFeatureMap(UINT index, UINT padx, UINT pady);
virtual void DotProduct(UINT index, UINT width, UINT height, vector<REAL>&,
Store&response);
virtual void DotProduct(UINT index, UINT width, UINT height, REAL *filter,
Store&);
void ComputeLTPMap(Image &image, LBPMap *tpmap, LBPMap *tnmap);
void ComputeLBPFeatures(Image& imgref, UINT index, UINT winstride,
UINT tlbpstride);
void ComputeLBPFeatures(Image& imgref, vector<REAL> &features, UINT cxbmax,
UINT cybmax, UINT winstride, UINT tlbpstride);
void ComputeSplitLBPFeatures(Image& imgref, vector<REAL> &features,
UINT cxbmax, UINT cybmax, UINT winstride, UINT tlbpstride);
/*****Test Code ****/
// All the inputs are in Pixels .....
void ExtractPosCodeInfo(Image&image, vector<Coord>& ainfo);
void ExtractNegCodeInfo(Image&image);
void ExtractCodeInfo(Image &image, LBPMap *map, ComputeCode *cbook);
void GenerateCodeBookInfo(LBPMap *map, UINT xmin, UINT ymin,
ComputeCode* cbook); // for a single code book
void GenerateCodeBookInfo(LBPMap *map, UINT xmin, UINT ymin,
vector<ComputeCode*> & cbook); // for complete codebook
// void GenerateCodeBookInfo(Image & image, ComputeCode * cbook);
void GenerateCodeBookInfo(LBPMap *pmap, LBPMap *nmap, UINT xmin, UINT ymin);
bool ExistPosCodeInfo() {
UINT count = 1;
for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter =
ncbooks.begin(); iter != pcbooks.end(); ++iter, ++niter) {
ostringstream oss;
oss << cifilename << "-" << count << ".txt";
if (!(*iter)->ExistCodeBook(oss.str()))
return false;
oss.str("");
oss << ncifilename << "-" << count << ".txt";
if (!(*niter)->ExistCodeBook(oss.str()))
return false;
}
return true;
}
bool ExistPosCodeBook() {
UINT count = 1;
for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter =
ncbooks.begin(); iter != pcbooks.end(); ++iter, ++count, ++niter) {
ostringstream oss;
oss << cbfilename << "-" << count << ".txt";
if (!(*iter)->ExistCodeBook(oss.str()))
return false;
oss.str("");
oss << ncbfilename << "-" << count << ".txt";
if (!(*niter)->ExistCodeBook(oss.str()))
return false;
}
return true;
}
virtual void GenerateCodeBook() {
if (ExistPosCodeBook())
return;
if (cbparams->cbtype == CBT_NegativeThenPosCrop) { // first generate the negative code book
// and use it as initialization for the +ve cell based codebooks
string cifname = cifilename + "Neg";
ExtractNegCBInfo(cifname);
ConstructNegCodeBook(NULL);
REAL *ncluster = new REAL[ncenters
* pcbooks[ncbs - 1]->GetCodeLength()];
pcbooks[ncbs - 1]->CopyClusters(ncluster);
// ExtractPosCodeInfo();
ExtractPosCBInfo();
ConstructPosCodeBook(ncluster);
} else if (cbparams->cbtype == CBT_CellQuantizeAll) {
if (!ExistPosCodeInfo()) {
vector<string> imnames;
ParseListFile(cbparams->vimgfname, imnames);
Image image;
for (UINT i = 0; i < imnames.size(); ++i) {
cout << "\n Processing Image # = " << (i + 1) << " "
<< imnames[i];
image.read(imnames[i]);
ExtractImageCodeInfo(image);
}
}
ConstructPosCodeBook(NULL);
} else {
ExtractPosCBInfo();
ConstructPosCodeBook(NULL);
ExtractNegCBInfo(cifilename);
ConstructNegCodeBook(NULL);
}
}
void ExtractImageCodeInfo(Image &image) {
LBPMap pmap[3], nmap[3];
ExtractCodeBookInfo(image, pmap, nmap, false, true);
UINT offset = GetMaxFeatureOffset(), minoffset = GetFeaturesOffset(),
doffset = offset - minoffset;
GenerateCodeBookInfo(pmap, nmap, doffset, doffset);
image.flop(); // flipped image
cout << " ------ Processing Flipped Version ";
ExtractCodeBookInfo(image, pmap, nmap, false, true);
GenerateCodeBookInfo(pmap, nmap, doffset, doffset);
}
void ExtractPosCBInfo() {
if (ExistPosCodeInfo())
return;
ClassInfo *ocinfo = cbparams->ocinfo;
if (cbtype == CBT_PosPyramid || cbtype == CBT_PosPyramidNegSampled) {
sspace = SingleRes;
SetPyramidInterval(5);
} else
sspace = NoPyramid; /*if to use local space pyramid*/
cout << "\n Using Scale Space = " << GetPyramidType(sspace) << endl;
string imname;
Image image;
vector<Coord> vcoord;// to contain the flipped features coordinates
ocinfo->ResetCounter();
UINT count = 0;
while (ocinfo->GetNextImageAnnotation(imname, vcoord)) {
image.read(imname);
cout << "Image " << ++count << ". Number of Annotations = "
<< vcoord.size() << endl;
ExtractPosCodeInfo(image, vcoord);
}
}
void ExtractNegCBInfo(const string &cifn) {
ostringstream oss;
oss << cifn << "-" << ncbs << ".txt";
if (pcbooks[ncbs - 1]->ExistCodeInfo(oss.str()))
return;
sspace = SingleRes;
SetPyramidInterval(2);
vector<string> imnames;
if (cbtype == CBT_Complete)/*Use complete validation set*/
ParseListFile(cbparams->vimgfname, imnames);
else
ParseListFile(cbparams->nimgfname, imnames);
Image image;
for (UINT i = 0; i < imnames.size(); ++i) {
cout << " Processing Image # = " << (i + 1) << " " << imnames[i]
<< endl;
image.read(imnames[i]);
ExtractNegCodeInfo(image);
}
}
void ConstructPosCodeBook(REAL *initclusters) {
char ci[2000], cb[2000];
UINT nclusrounds = cbparams->nclusrounds;
ClusteringDistanceMetric dmetric = cbparams->dmetric;
if (ExistPosCodeBook())
return;
#pragma omp parallel for
for (UINT count = 0; count < pcbooks.size(); ++count) {
ostringstream ciss, cbss;
ciss << cifilename << "-" << count + 1 << ".txt";
cbss << cbfilename << "-" << count + 1 << ".txt";
long initime = time(0);
pcbooks[count]->GenerateCodeBook(ciss.str(), cbss.str(), dmetric,
nclusrounds, initclusters);
cout << " \n Time Taken For Positive Code Book Number " << count
<< "Generation =" << time(0) - initime << endl << flush;
}
#pragma omp parallel for
for (UINT count = 0; count < pcbooks.size(); ++count) {
ostringstream ciss, cbss;
ciss << ncifilename << "-" << count + 1 << ".txt";
cbss << ncbfilename << "-" << count + 1 << ".txt";
long initime = time(0);
ncbooks[count]->GenerateCodeBook(ciss.str(), cbss.str(), dmetric,
nclusrounds, initclusters);
cout << " \n Time Taken For Negative Code Book Number " << count
<< "Generation =" << time(0) - initime << endl << flush;
}
}
void ConstructNegCodeBook(REAL *initclusters) {
char ci[2000], cb[2000];
UINT count = ncbs, nclusrounds = cbparams->nclusrounds;
ClusteringDistanceMetric dmetric = cbparams->dmetric;
ostringstream ciss, cbss;
ciss << cifilename << "-" << count << ".txt";
cbss << cbfilename << "-" << count << ".txt";
long initime = time(0);
pcbooks[count - 1]->GenerateCodeBook(ciss.str(), cbss.str(), dmetric,
nclusrounds, initclusters);
cout << " \n Time Taken For Code Book Number " << count
<< "Generation =" << time(0) - initime << endl << flush;
}
private:
UINT GetFeatDim(UINT width_, UINT height_) const {
return (width_ / cellsize) * (height_ / cellsize) * featdim;
}
protected:
UINT featdim; /// single cell feature dimension
vector<ComputeCode*> pcbooks, ncbooks;
UINT ncbs;
string imgfname;
};
#endif
|
serialized.c | // RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
// UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8
#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;
}
|
GB_binop__pair_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__pair_int64)
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__pair_int64)
// C+=b function (dense accum): GB (_Cdense_accumb__pair_int64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_int64)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: int64_t
// A type: int64_t
// B,b type: int64_t
// BinaryOp: cij = 1
#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) \
;
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
;
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = 1 ;
// 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_PAIR || GxB_NO_INT64 || GxB_NO_PAIR_INT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__pair_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__pair_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__pair_int64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int64_t
int64_t bwork = (*((int64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__pair_int64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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 ;
; ;
Cx [p] = 1 ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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 ;
; ;
Cx [p] = 1 ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = 1 ; \
}
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = 1 ; \
}
GrB_Info GB ((none))
(
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
#endif
|
GeometryConverter.h | /* -*-c++-*- IfcQuery www.ifcquery.com
*
MIT License
Copyright (c) 2017 Fabian Gerold
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 <unordered_set>
#include <ifcpp/model/BasicTypes.h>
#include <ifcpp/model/BuildingModel.h>
#include <ifcpp/model/StatusCallback.h>
#include <ifcpp/IFC4/include/IfcCurtainWall.h>
#include <ifcpp/IFC4/include/IfcGloballyUniqueId.h>
#include <ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h>
#include <ifcpp/IFC4/include/IfcRelAggregates.h>
#include <ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h>
#include <ifcpp/IFC4/include/IfcRelDefinesByProperties.h>
#include <ifcpp/IFC4/include/IfcSpace.h>
#include <ifcpp/IFC4/include/IfcWindow.h>
#include "IncludeCarveHeaders.h"
#include "GeometryInputData.h"
#include "RepresentationConverter.h"
#include "CSG_Adapter.h"
class GeometryConverter : public StatusCallback
{
protected:
shared_ptr<BuildingModel> m_ifc_model;
shared_ptr<GeometrySettings> m_geom_settings;
shared_ptr<RepresentationConverter> m_representation_converter;
std::map<std::string, shared_ptr<ProductShapeData> > m_product_shape_data;
std::map<std::string, shared_ptr<BuildingObject> > m_map_outside_spatial_structure;
double m_recent_progress = 0;
double m_csg_eps = 1.5e-05;
std::map<int, std::vector<shared_ptr<StatusCallback::Message> > > m_messages;
#ifdef ENABLE_OPENMP
Mutex m_writelock_messages;
#endif
public:
// getters and setters
shared_ptr<BuildingModel>& getBuildingModel() { return m_ifc_model; }
shared_ptr<RepresentationConverter>& getRepresentationConverter() { return m_representation_converter; }
shared_ptr<GeometrySettings>& getGeomSettings() { return m_geom_settings; }
std::map<std::string, shared_ptr<ProductShapeData> >& getShapeInputData() { return m_product_shape_data; }
std::map<std::string, shared_ptr<BuildingObject> >& getObjectsOutsideSpatialStructure() { return m_map_outside_spatial_structure; }
GeometryConverter( shared_ptr<BuildingModel>& ifc_model )
{
m_ifc_model = ifc_model;
m_geom_settings = shared_ptr<GeometrySettings>( new GeometrySettings() );
resetNumVerticesPerCircle();
shared_ptr<UnitConverter>& unit_converter = m_ifc_model->getUnitConverter();
m_representation_converter = shared_ptr<RepresentationConverter>( new RepresentationConverter( m_geom_settings, unit_converter ) );
// redirect all messages to this->messageTarget
m_ifc_model->setMessageTarget( this );
m_representation_converter->setMessageTarget( this );
}
virtual ~GeometryConverter() {}
void resetModel()
{
progressTextCallback( L"Unloading model, cleaning up memory..." );
clearInputCache();
m_recent_progress = 0.0;
m_ifc_model->clearCache();
m_ifc_model->clearIfcModel();
progressTextCallback( L"Unloading model done" );
progressValueCallback( 0.0, "parse" );
#ifdef _DEBUG
GeomDebugDump::clearMeshsetDump();
#endif
}
void clearInputCache()
{
m_product_shape_data.clear();
m_map_outside_spatial_structure.clear();
m_representation_converter->clearCache();
m_messages.clear();
}
void resetNumVerticesPerCircle()
{
m_geom_settings->resetNumVerticesPerCircle();
}
void setCsgEps(double eps)
{
m_csg_eps = eps;
}
void setModel( shared_ptr<BuildingModel> model )
{
if( m_ifc_model )
{
m_ifc_model->unsetMessageCallBack();
}
clearInputCache();
m_ifc_model = model;
m_representation_converter->clearCache();
m_representation_converter->setUnitConverter( m_ifc_model->getUnitConverter() );
m_ifc_model->setMessageTarget( this );
}
void resolveProjectStructure( shared_ptr<ProductShapeData>& product_data )
{
if( !product_data )
{
return;
}
if( product_data->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def( product_data->m_ifc_object_definition );
product_data->m_added_to_spatial_structure = true;
const std::vector<weak_ptr<IfcRelAggregates> >& vec_IsDecomposedBy = ifc_object_def->m_IsDecomposedBy_inverse;
for( size_t ii = 0; ii < vec_IsDecomposedBy.size(); ++ii )
{
const weak_ptr<IfcRelAggregates>& rel_aggregates_weak_ptr = vec_IsDecomposedBy[ii];
if( rel_aggregates_weak_ptr.expired() )
{
continue;
}
shared_ptr<IfcRelAggregates> rel_aggregates( rel_aggregates_weak_ptr );
if( rel_aggregates )
{
const std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = rel_aggregates->m_RelatedObjects;
for( size_t jj = 0; jj < vec_related_objects.size(); ++jj )
{
const shared_ptr<IfcObjectDefinition>& related_obj_def = vec_related_objects[jj];
if( related_obj_def )
{
std::string related_guid;
if (related_obj_def->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
related_guid = converterX.to_bytes(related_obj_def->m_GlobalId->m_value);
}
auto it_product_map = m_product_shape_data.find(related_guid);
if( it_product_map != m_product_shape_data.end() )
{
shared_ptr<ProductShapeData>& related_product_shape = it_product_map->second;
if( related_product_shape )
{
product_data->addChildProduct( related_product_shape, product_data );
resolveProjectStructure( related_product_shape );
}
}
}
}
}
}
shared_ptr<IfcSpatialStructureElement> spatial_ele = dynamic_pointer_cast<IfcSpatialStructureElement>(ifc_object_def);
if( spatial_ele )
{
const std::vector<weak_ptr<IfcRelContainedInSpatialStructure> >& vec_contains = spatial_ele->m_ContainsElements_inverse;
for( size_t ii = 0; ii < vec_contains.size(); ++ii )
{
const weak_ptr<IfcRelContainedInSpatialStructure>& rel_contained_weak_ptr = vec_contains[ii];
if( rel_contained_weak_ptr.expired() )
{
continue;
}
shared_ptr<IfcRelContainedInSpatialStructure> rel_contained( rel_contained_weak_ptr );
if( rel_contained )
{
const std::vector<shared_ptr<IfcProduct> >& vec_related_elements = rel_contained->m_RelatedElements;
for( size_t jj = 0; jj < vec_related_elements.size(); ++jj )
{
const shared_ptr<IfcProduct>& related_product = vec_related_elements[jj];
if( related_product )
{
std::string related_guid;
if (related_product->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
related_guid = converterX.to_bytes(related_product->m_GlobalId->m_value);
}
auto it_product_map = m_product_shape_data.find(related_guid);
if( it_product_map != m_product_shape_data.end() )
{
shared_ptr<ProductShapeData>& related_product_shape = it_product_map->second;
if( related_product_shape )
{
product_data->addChildProduct( related_product_shape, product_data );
resolveProjectStructure( related_product_shape );
}
}
}
}
}
}
}
// TODO: handle IfcRelAssignsToProduct
}
void readAppearanceFromPropertySet( const shared_ptr<IfcPropertySet>& prop_set, shared_ptr<ProductShapeData>& product_shape )
{
if( !prop_set )
{
return;
}
for( auto& ifc_property : prop_set->m_HasProperties )
{
if( !ifc_property )
{
continue;
}
shared_ptr<IfcSimpleProperty> simple_property = dynamic_pointer_cast<IfcSimpleProperty>(ifc_property);
if( simple_property )
{
// ENTITY IfcSimpleProperty ABSTRACT SUPERTYPE OF(ONEOF( IfcPropertyBoundedValue, IfcPropertyEnumeratedValue, IfcPropertyListValue,
// IfcPropertyReferenceValue, IfcPropertySingleValue, IfcPropertyTableValue))
shared_ptr<IfcIdentifier> property_name = simple_property->m_Name;
std::wstring name_str = property_name->m_value;
if( name_str.compare( L"LayerName" ) == 0 )
{
// TODO: implement layers
}
shared_ptr<IfcText> description = simple_property->m_Description;
shared_ptr<IfcPropertySingleValue> property_single_value = dynamic_pointer_cast<IfcPropertySingleValue>(simple_property);
if( property_single_value )
{
//shared_ptr<IfcValue>& nominal_value = property_single_value->m_NominalValue; //optional
//shared_ptr<IfcUnit>& unit = property_single_value->m_Unit; //optional
}
continue;
}
shared_ptr<IfcComplexProperty> complex_property = dynamic_pointer_cast<IfcComplexProperty>(ifc_property);
if( complex_property )
{
if( !complex_property->m_UsageName ) continue;
if( complex_property->m_UsageName->m_value.compare( L"Color" ) == 0 )
{
vec4 vec_color;
m_representation_converter->getStylesConverter()->convertIfcComplexPropertyColor( complex_property, vec_color );
shared_ptr<AppearanceData> appearance_data( new AppearanceData( -1 ) );
if( !appearance_data )
{
throw OutOfMemoryException( __FUNC__ );
}
appearance_data->m_apply_to_geometry_type = AppearanceData::GEOM_TYPE_ANY;
appearance_data->m_color_ambient.setColor( vec_color );
appearance_data->m_color_diffuse.setColor( vec_color );
appearance_data->m_color_specular.setColor( vec_color );
appearance_data->m_shininess = 35.f;
product_shape->addAppearance( appearance_data );
}
}
}
}
/*\brief method convertGeometry: Creates geometry for Carve from previously loaded BuildingModel model.
**/
void convertGeometry()
{
progressTextCallback( L"Creating geometry..." );
progressValueCallback( 0, "geometry" );
m_product_shape_data.clear();
m_map_outside_spatial_structure.clear();
m_representation_converter->clearCache();
if( !m_ifc_model )
{
return;
}
shared_ptr<ProductShapeData> ifc_project_data;
std::vector<shared_ptr<IfcObjectDefinition> > vec_object_defs;
double length_to_meter_factor = 1.0;
if( m_ifc_model->getUnitConverter() )
{
length_to_meter_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor();
}
carve::setEpsilon( m_csg_eps );
const std::map<int, shared_ptr<BuildingEntity> >& map_entities = m_ifc_model->getMapIfcEntities();
for( auto it = map_entities.begin(); it != map_entities.end(); ++it )
{
shared_ptr<BuildingEntity> obj = it->second;
shared_ptr<IfcObjectDefinition> object_def = dynamic_pointer_cast<IfcObjectDefinition>(obj);
if( object_def )
{
vec_object_defs.push_back( object_def );
}
}
// create geometry for for each IfcProduct independently, spatial structure will be resolved later
std::map<std::string, shared_ptr<ProductShapeData> >* map_products_ptr = &m_product_shape_data;
const int num_products = (int)vec_object_defs.size();
#ifdef ENABLE_OPENMP
Mutex writelock_map;
Mutex writelock_ifc_project;
#pragma omp parallel firstprivate(num_products) shared(map_products_ptr)
{
// time for one product may vary significantly, so schedule not so many
#pragma omp for schedule(dynamic,40)
#endif
for( int i = 0; i < num_products; ++i )
{
shared_ptr<IfcObjectDefinition> ifc_object_def = vec_object_defs[i];
const int entity_id = ifc_object_def->m_entity_id;
std::string guid;
if (ifc_object_def->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
guid = converterX.to_bytes(ifc_object_def->m_GlobalId->m_value);
}
shared_ptr<ProductShapeData> product_geom_input_data( new ProductShapeData( entity_id ) );
product_geom_input_data->m_ifc_object_definition = ifc_object_def;
std::stringstream thread_err;
if( !m_geom_settings->getRenderObjectFilter()(ifc_object_def) )
{
// geometry will be created in method subtractOpenings
continue;
}
else if( dynamic_pointer_cast<IfcProject>(ifc_object_def) )
{
#ifdef ENABLE_OPENMP
ScopedLock scoped_lock( writelock_ifc_project );
#endif
ifc_project_data = product_geom_input_data;
}
try
{
convertIfcProductShape( product_geom_input_data );
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
thread_err << e.what();
}
catch( carve::exception& e )
{
thread_err << e.str();
}
catch( std::exception& e )
{
thread_err << e.what();
}
catch( ... )
{
thread_err << "undefined error, product id " << entity_id;
}
{
#ifdef ENABLE_OPENMP
ScopedLock scoped_lock( writelock_map );
#endif
map_products_ptr->insert( std::make_pair( guid, product_geom_input_data ) );
if( thread_err.tellp() > 0 )
{
messageCallback( thread_err.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
}
}
// progress callback
double progress = (double)i / (double)num_products;
if( progress - m_recent_progress > 0.02 )
{
#ifdef ENABLE_OPENMP
if( omp_get_thread_num() == 0 )
#endif
{
// leave 10% of progress to openscenegraph internals
progressValueCallback( progress*0.9, "geometry" );
m_recent_progress = progress;
}
}
}
#ifdef ENABLE_OPENMP
} // implicit barrier
#endif
// subtract openings in related objects, such as IFCBUILDINGELEMENTPART connected to a window through IFCRELAGGREGATES
for( auto it = map_products_ptr->begin(); it != map_products_ptr->end(); ++it )
{
shared_ptr<ProductShapeData> product_geom_input_data = it->second;
try
{
subtractOpeningsInRelatedObjects(product_geom_input_data);
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
messageCallback(e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "");
}
catch( carve::exception& e )
{
messageCallback(e.str(), StatusCallback::MESSAGE_TYPE_ERROR, "");
}
catch( std::exception& e )
{
messageCallback(e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "");
}
catch( ... )
{
messageCallback("undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__);
}
}
try
{
// now resolve spatial structure
if( ifc_project_data )
{
resolveProjectStructure( ifc_project_data );
}
// check if there are entities that are not in spatial structure
for( auto it_product_shapes = m_product_shape_data.begin(); it_product_shapes != m_product_shape_data.end(); ++it_product_shapes )
{
shared_ptr<ProductShapeData> product_shape = it_product_shapes->second;
if( !product_shape )
{
continue;
}
if( !product_shape->m_added_to_spatial_structure )
{
if( !product_shape->m_ifc_object_definition.expired() )
{
shared_ptr<IfcObjectDefinition> ifc_product( product_shape->m_ifc_object_definition );
shared_ptr<IfcFeatureElementSubtraction> opening = dynamic_pointer_cast<IfcFeatureElementSubtraction>(ifc_product);
if( !m_geom_settings->getRenderObjectFilter()(ifc_product) )
{
continue;
}
std::string guid;
if (ifc_product->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
guid = converterX.to_bytes(ifc_product->m_GlobalId->m_value);
}
m_map_outside_spatial_structure[guid] = ifc_product;
}
}
}
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
}
catch( std::exception& e )
{
messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
}
catch( ... )
{
messageCallback( "undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
}
m_representation_converter->getProfileCache()->clearProfileCache();
progressTextCallback( L"Loading file done" );
progressValueCallback( 1.0, "geometry" );
}
//\brief method convertIfcProduct: Creates geometry objects (meshset with connected vertex-edge-face graph) from an IfcProduct object
// caution: when using OpenMP, this method runs in parallel threads, so every write access to member variables needs a write lock
void convertIfcProductShape( shared_ptr<ProductShapeData>& product_shape )
{
if( product_shape->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def( product_shape->m_ifc_object_definition );
shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def);
if( !ifc_product )
{
return;
}
if( !ifc_product->m_Representation )
{
return;
}
double length_factor = 1.0;
if( m_ifc_model )
{
if( m_ifc_model->getUnitConverter() )
{
length_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor();
}
}
// evaluate IFC geometry
shared_ptr<IfcProductRepresentation>& product_representation = ifc_product->m_Representation;
std::vector<shared_ptr<IfcRepresentation> >& vec_representations = product_representation->m_Representations;
for( size_t i_representations = 0; i_representations < vec_representations.size(); ++i_representations )
{
const shared_ptr<IfcRepresentation>& representation = vec_representations[i_representations];
if( !representation )
{
continue;
}
try
{
shared_ptr<RepresentationData> representation_data( new RepresentationData() );
m_representation_converter->convertIfcRepresentation( representation, representation_data );
product_shape->m_vec_representations.push_back( representation_data );
representation_data->m_parent_product = product_shape;
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
}
catch( std::exception& e )
{
messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
}
}
// IfcProduct has an ObjectPlacement that can be local or global
product_shape->m_object_placement = ifc_product->m_ObjectPlacement;
if( ifc_product->m_ObjectPlacement )
{
// IfcPlacement2Matrix follows related placements in case of local coordinate systems
std::unordered_set<IfcObjectPlacement*> placement_already_applied;
m_representation_converter->getPlacementConverter()->convertIfcObjectPlacement( ifc_product->m_ObjectPlacement, product_shape, placement_already_applied, false );
}
// handle openings
std::vector<shared_ptr<ProductShapeData> > vec_opening_data;
const shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>(ifc_product);
if( ifc_element )
{
m_representation_converter->subtractOpenings(ifc_element, product_shape);
}
// Fetch the IFCProduct relationships
if( ifc_product->m_IsDefinedBy_inverse.size() > 0 )
{
std::vector<weak_ptr<IfcRelDefinesByProperties> >& vec_IsDefinedBy_inverse = ifc_product->m_IsDefinedBy_inverse;
for( size_t i = 0; i < vec_IsDefinedBy_inverse.size(); ++i )
{
shared_ptr<IfcRelDefinesByProperties> rel_def( vec_IsDefinedBy_inverse[i] );
shared_ptr<IfcPropertySetDefinitionSelect> relating_property_definition_select = rel_def->m_RelatingPropertyDefinition;
if( relating_property_definition_select )
{
// TYPE IfcPropertySetDefinitionSelect = SELECT (IfcPropertySetDefinition ,IfcPropertySetDefinitionSet);
shared_ptr<IfcPropertySetDefinition> property_set_def = dynamic_pointer_cast<IfcPropertySetDefinition>(relating_property_definition_select);
if( property_set_def )
{
shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>(property_set_def);
if( property_set )
{
readAppearanceFromPropertySet( property_set, product_shape );
}
continue;
}
shared_ptr<IfcPropertySetDefinitionSet> property_set_def_set = dynamic_pointer_cast<IfcPropertySetDefinitionSet>(relating_property_definition_select);
if( property_set_def_set )
{
std::vector<shared_ptr<IfcPropertySetDefinition> >& vec_propterty_set_def = property_set_def_set->m_vec;
std::vector<shared_ptr<IfcPropertySetDefinition> >::iterator it_property_set_def;
for( it_property_set_def = vec_propterty_set_def.begin(); it_property_set_def != vec_propterty_set_def.end(); ++it_property_set_def )
{
shared_ptr<IfcPropertySetDefinition> property_set_def2 = (*it_property_set_def);
if( property_set_def2 )
{
shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>(property_set_def2);
if( property_set )
{
readAppearanceFromPropertySet( property_set, product_shape );
}
}
}
continue;
}
}
}
}
}
void subtractOpeningsInRelatedObjects(shared_ptr<ProductShapeData>& product_shape)
{
if( product_shape->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def(product_shape->m_ifc_object_definition);
shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>(ifc_object_def);
if( !ifc_element )
{
return;
}
if( ifc_element->m_HasOpenings_inverse.size() == 0 )
{
return;
}
// collect aggregated objects
const std::vector<weak_ptr<IfcRelAggregates> >& vec_decomposed_by = ifc_element->m_IsDecomposedBy_inverse;
for( auto& decomposed_by : vec_decomposed_by )
{
if( decomposed_by.expired() )
{
continue;
}
shared_ptr<IfcRelAggregates> decomposed_by_aggregates(decomposed_by);
std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = decomposed_by_aggregates->m_RelatedObjects;
for( auto& related_object : vec_related_objects )
{
if( !related_object )
{
continue;
}
std::string guid;
if (related_object->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
guid = converterX.to_bytes(related_object->m_GlobalId->m_value);
auto it_find_related_shape = m_product_shape_data.find(guid);
if( it_find_related_shape != m_product_shape_data.end() )
{
shared_ptr<ProductShapeData>& related_product_shape = it_find_related_shape->second;
m_representation_converter->subtractOpenings(ifc_element, related_product_shape);
}
}
}
}
}
virtual void messageTarget( void* ptr, shared_ptr<StatusCallback::Message> m )
{
GeometryConverter* myself = (GeometryConverter*)ptr;
if( myself )
{
if( m->m_entity )
{
#ifdef ENABLE_OPENMP
ScopedLock lock( myself->m_writelock_messages );
#endif
// make sure that the same message for one entity does not appear several times
const int entity_id = m->m_entity->m_entity_id;
auto it = myself->m_messages.find( entity_id );
if( it != myself->m_messages.end() )
{
std::vector<shared_ptr<StatusCallback::Message> >& vec_message_for_entity = it->second;
for( size_t i = 0; i < vec_message_for_entity.size(); ++i )
{
shared_ptr<StatusCallback::Message>& existing_message = vec_message_for_entity[i];
if( existing_message->m_message_text.compare( m->m_message_text ) == 0 )
{
// same message for same entity is already there, so ignore message
return;
}
}
vec_message_for_entity.push_back( m );
}
else
{
std::vector<shared_ptr<StatusCallback::Message> >& vec = myself->m_messages.insert( std::make_pair( entity_id, std::vector<shared_ptr<StatusCallback::Message> >() ) ).first->second;
vec.push_back( m );
}
}
myself->messageCallback( m );
}
}
};
|
test5.c | void bar();
void foo() {
0;
#pragma omp barrier
1;
#pragma omp barrier
2;
#pragma omp barrier
3;
}
void foobar() {
4;
#pragma omp barrier
5;
#pragma omp barrier
6;
#pragma omp barrier
7;
}
int main() {
#pragma omp parallel
{
8;
switch (9) {
case 1:
10;
bar();
11;
break;
case 2:
13;
foo();
14;
break;
default:
15;
foobar();
16;
break;
}
17;
}
}
|
csr_matvec.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*/
/******************************************************************************
*
* Matvec functions for hypre_CSRMatrix class.
*
*****************************************************************************/
#include "seq_mv.h"
#include <assert.h>
/*--------------------------------------------------------------------------
* hypre_CSRMatrixMatvec
*--------------------------------------------------------------------------*/
static void start_slice(){
__asm__ __volatile__ ("");
}
static void end_slice(){
__asm__ __volatile__ ("");
}
/* y[offset:end] = alpha*A[offset:end,:]*x + beta*b[offset:end] */
HYPRE_Int
hypre_CSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha,
hypre_CSRMatrix *A,
hypre_Vector *x,
HYPRE_Complex beta,
hypre_Vector *b,
hypre_Vector *y,
HYPRE_Int offset )
{
start_slice();
#ifdef HYPRE_PROFILE
HYPRE_Real time_begin = hypre_MPI_Wtime();
#endif
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin;
#endif
HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
HYPRE_Int *A_i = hypre_CSRMatrixI(A) + offset;
HYPRE_Int *A_j = hypre_CSRMatrixJ(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A) - offset;
HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A);
/*HYPRE_Int num_nnz = hypre_CSRMatrixNumNonzeros(A);*/
HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A);
HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A);
HYPRE_Complex *x_data = hypre_VectorData(x);
HYPRE_Complex *b_data = hypre_VectorData(b) + offset;
HYPRE_Complex *y_data = hypre_VectorData(y) + offset;
HYPRE_Int x_size = hypre_VectorSize(x);
HYPRE_Int b_size = hypre_VectorSize(b) - offset;
HYPRE_Int y_size = hypre_VectorSize(y) - offset;
HYPRE_Int num_vectors = hypre_VectorNumVectors(x);
HYPRE_Int idxstride_y = hypre_VectorIndexStride(y);
HYPRE_Int vecstride_y = hypre_VectorVectorStride(y);
/*HYPRE_Int idxstride_b = hypre_VectorIndexStride(b);
HYPRE_Int vecstride_b = hypre_VectorVectorStride(b);*/
HYPRE_Int idxstride_x = hypre_VectorIndexStride(x);
HYPRE_Int vecstride_x = hypre_VectorVectorStride(x);
HYPRE_Complex temp, tempx;
HYPRE_Int i, j, jj;
HYPRE_Int m;
HYPRE_Real xpar=0.7;
HYPRE_Int ierr = 0;
hypre_Vector *x_tmp = NULL;
/*---------------------------------------------------------------------
* Check for size compatibility. Matvec returns ierr = 1 if
* length of X doesn't equal the number of columns of A,
* ierr = 2 if the length of Y doesn't equal the number of rows
* of A, and ierr = 3 if both are true.
*
* Because temporary vectors are often used in Matvec, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
hypre_assert( num_vectors == hypre_VectorNumVectors(y) );
hypre_assert( num_vectors == hypre_VectorNumVectors(b) );
if (num_cols != x_size)
ierr = 1;
if (num_rows != y_size || num_rows != b_size)
ierr = 2;
if (num_cols != x_size && (num_rows != y_size || num_rows != b_size))
ierr = 3;
/*-----------------------------------------------------------------------
* Do (alpha == 0.0) computation - RDF: USE MACHINE EPS
*-----------------------------------------------------------------------*/
if (alpha == 0.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows*num_vectors; i++)
y_data[i] = beta*b_data[i];
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin;
#endif
return ierr;
}
if (x == y)
{
x_tmp = hypre_SeqVectorCloneDeep(x);
x_data = hypre_VectorData(x_tmp);
}
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
temp = beta / alpha;
/* use rownnz pointer to do the A*x multiplication when num_rownnz is smaller than num_rows */
if (num_rownnz < xpar*(num_rows) || num_vectors > 1)
{
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
if (temp != 1.0)
{
if (temp == 0.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows*num_vectors; i++)
y_data[i] = 0.0;
}
else
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows*num_vectors; i++)
y_data[i] = b_data[i]*temp;
}
}
else
{
for (i = 0; i < num_rows*num_vectors; i++)
y_data[i] = b_data[i];
}
/*-----------------------------------------------------------------
* y += A*x
*-----------------------------------------------------------------*/
if (num_rownnz < xpar*(num_rows))
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jj,m,tempx) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rownnz; i++)
{
m = A_rownnz[i];
/*
* for (jj = A_i[m]; jj < A_i[m+1]; jj++)
* {
* j = A_j[jj];
* y_data[m] += A_data[jj] * x_data[j];
* } */
if ( num_vectors==1 )
{
tempx = 0;
for (jj = A_i[m]; jj < A_i[m+1]; jj++)
tempx += A_data[jj] * x_data[A_j[jj]];
y_data[m] += tempx;
}
else
for ( j=0; j<num_vectors; ++j )
{
tempx = 0;
for (jj = A_i[m]; jj < A_i[m+1]; jj++)
tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ];
y_data[ j*vecstride_y + m*idxstride_y] += tempx;
}
}
}
else // num_vectors > 1
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jj,tempx) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
{
for (j = 0; j < num_vectors; ++j)
{
tempx = 0;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ];
}
y_data[ j*vecstride_y + i*idxstride_y ] += tempx;
}
}
}
/*-----------------------------------------------------------------
* y = alpha*y
*-----------------------------------------------------------------*/
if (alpha != 1.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows*num_vectors; i++)
y_data[i] *= alpha;
}
}
else
{ // JSP: this is currently the only path optimized
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,jj,tempx)
#endif
{
HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A);
HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A);
hypre_assert(iBegin <= iEnd);
hypre_assert(iBegin >= 0 && iBegin <= num_rows);
hypre_assert(iEnd >= 0 && iEnd <= num_rows);
if (0 == temp)
{
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++)
{
tempx = 0.0;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x
else if (-1 == alpha)
{
for (i = iBegin; i < iEnd; i++)
{
tempx = 0.0;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x
else
{
for (i = iBegin; i < iEnd; i++)
{
tempx = 0.0;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha*tempx;
}
} // y = alpha*A*x
} // temp == 0
else if (-1 == temp) // beta == -alpha
{
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++)
{
tempx = -b_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x - y
else if (-1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++)
{
tempx = b_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x + y
else
{
for (i = iBegin; i < iEnd; i++)
{
tempx = -b_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha*tempx;
}
} // y = alpha*(A*x - y)
} // temp == -1
else if (1 == temp)
{
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++)
{
tempx = b_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x + y
else if (-1 == alpha)
{
for (i = iBegin; i < iEnd; i++)
{
tempx = -b_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x - y
else
{
for (i = iBegin; i < iEnd; i++)
{
tempx = b_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha*tempx;
}
} // y = alpha*(A*x + y)
}
else
{
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++)
{
tempx = b_data[i]*temp;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x + temp*y
else if (-1 == alpha)
{
for (i = iBegin; i < iEnd; i++)
{
tempx = -b_data[i]*temp;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x - temp*y
else
{
for (i = iBegin; i < iEnd; i++)
{
tempx = b_data[i]*temp;
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha*tempx;
}
} // y = alpha*(A*x + temp*y)
} // temp != 0 && temp != -1 && temp != 1
} // omp parallel
}
if (x == y) hypre_SeqVectorDestroy(x_tmp);
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin;
#endif
end_slice();
return ierr;
}
HYPRE_Int
hypre_CSRMatrixMatvec( HYPRE_Complex alpha,
hypre_CSRMatrix *A,
hypre_Vector *x,
HYPRE_Complex beta,
hypre_Vector *y )
{
return hypre_CSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y, 0);
}
/*--------------------------------------------------------------------------
* hypre_CSRMatrixMatvecT
*
* This version is using a different (more efficient) threading scheme
* Performs y <- alpha * A^T * x + beta * y
*
* From Van Henson's modification of hypre_CSRMatrixMatvec.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_CSRMatrixMatvecT( HYPRE_Complex alpha,
hypre_CSRMatrix *A,
hypre_Vector *x,
HYPRE_Complex beta,
hypre_Vector *y )
{
start_slice();
HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
HYPRE_Int *A_i = hypre_CSRMatrixI(A);
HYPRE_Int *A_j = hypre_CSRMatrixJ(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A);
HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A);
HYPRE_Complex *x_data = hypre_VectorData(x);
HYPRE_Complex *y_data = hypre_VectorData(y);
HYPRE_Int x_size = hypre_VectorSize(x);
HYPRE_Int y_size = hypre_VectorSize(y);
HYPRE_Int num_vectors = hypre_VectorNumVectors(x);
HYPRE_Int idxstride_y = hypre_VectorIndexStride(y);
HYPRE_Int vecstride_y = hypre_VectorVectorStride(y);
HYPRE_Int idxstride_x = hypre_VectorIndexStride(x);
HYPRE_Int vecstride_x = hypre_VectorVectorStride(x);
HYPRE_Complex temp;
HYPRE_Complex *y_data_expand;
HYPRE_Int my_thread_num = 0, offset = 0;
HYPRE_Int i, j, jv, jj;
HYPRE_Int num_threads;
HYPRE_Int ierr = 0;
hypre_Vector *x_tmp = NULL;
/*---------------------------------------------------------------------
* 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.
*--------------------------------------------------------------------*/
hypre_assert( num_vectors == hypre_VectorNumVectors(y) );
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;
/*-----------------------------------------------------------------------
* Do (alpha == 0.0) computation - RDF: USE MACHINE EPS
*-----------------------------------------------------------------------*/
if (alpha == 0.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols*num_vectors; i++)
y_data[i] *= beta;
return ierr;
}
if (x == y)
{
x_tmp = hypre_SeqVectorCloneDeep(x);
x_data = hypre_VectorData(x_tmp);
}
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
temp = beta / alpha;
if (temp != 1.0)
{
if (temp == 0.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols*num_vectors; i++)
y_data[i] = 0.0;
}
else
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols*num_vectors; i++)
y_data[i] *= temp;
}
}
/*-----------------------------------------------------------------
* y += A^T*x
*-----------------------------------------------------------------*/
num_threads = hypre_NumThreads();
if (num_threads > 1)
{
y_data_expand = hypre_CTAlloc(HYPRE_Complex, num_threads*y_size);
if ( num_vectors==1 )
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,jj,j,my_thread_num,offset)
#endif
{
my_thread_num = hypre_GetThreadNum();
offset = y_size*my_thread_num;
#ifdef HYPRE_USING_OPENMP
#pragma omp for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
{
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
j = A_j[jj];
y_data_expand[offset + j] += A_data[jj] * x_data[i];
}
}
/* implied barrier (for threads)*/
#ifdef HYPRE_USING_OPENMP
#pragma omp for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < y_size; i++)
{
for (j = 0; j < num_threads; j++)
{
y_data[i] += y_data_expand[j*y_size + i];
}
}
} /* end parallel threaded region */
}
else
{
/* multiple vector case is not threaded */
for (i = 0; i < num_rows; i++)
{
for ( jv=0; jv<num_vectors; ++jv )
{
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
j = A_j[jj];
y_data[ j*idxstride_y + jv*vecstride_y ] +=
A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x];
}
}
}
}
hypre_TFree(y_data_expand);
}
else
{
for (i = 0; i < num_rows; i++)
{
if ( num_vectors==1 )
{
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
j = A_j[jj];
y_data[j] += A_data[jj] * x_data[i];
}
}
else
{
for ( jv=0; jv<num_vectors; ++jv )
{
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
{
j = A_j[jj];
y_data[ j*idxstride_y + jv*vecstride_y ] +=
A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x ];
}
}
}
}
}
/*-----------------------------------------------------------------
* y = alpha*y
*-----------------------------------------------------------------*/
if (alpha != 1.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols*num_vectors; i++)
y_data[i] *= alpha;
}
if (x == y) hypre_SeqVectorDestroy(x_tmp);
end_slice();
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_CSRMatrixMatvec_FF
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_CSRMatrixMatvec_FF( HYPRE_Complex alpha,
hypre_CSRMatrix *A,
hypre_Vector *x,
HYPRE_Complex beta,
hypre_Vector *y,
HYPRE_Int *CF_marker_x,
HYPRE_Int *CF_marker_y,
HYPRE_Int fpt )
{
HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
HYPRE_Int *A_i = hypre_CSRMatrixI(A);
HYPRE_Int *A_j = hypre_CSRMatrixJ(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A);
HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A);
HYPRE_Complex *x_data = hypre_VectorData(x);
HYPRE_Complex *y_data = hypre_VectorData(y);
HYPRE_Int x_size = hypre_VectorSize(x);
HYPRE_Int y_size = hypre_VectorSize(y);
HYPRE_Complex temp;
HYPRE_Int i, jj;
HYPRE_Int ierr = 0;
/*---------------------------------------------------------------------
* Check for size compatibility. Matvec returns ierr = 1 if
* length of X doesn't equal the number of columns of A,
* ierr = 2 if the length of Y doesn't equal the number of rows
* of A, and ierr = 3 if both are true.
*
* Because temporary vectors are often used in Matvec, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
if (num_cols != x_size)
ierr = 1;
if (num_rows != y_size)
ierr = 2;
if (num_cols != x_size && num_rows != y_size)
ierr = 3;
/*-----------------------------------------------------------------------
* Do (alpha == 0.0) computation - RDF: USE MACHINE EPS
*-----------------------------------------------------------------------*/
if (alpha == 0.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt) y_data[i] *= beta;
return ierr;
}
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
temp = beta / alpha;
if (temp != 1.0)
{
if (temp == 0.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt) y_data[i] = 0.0;
}
else
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt) y_data[i] *= temp;
}
}
/*-----------------------------------------------------------------
* y += A*x
*-----------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,jj) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
{
if (CF_marker_x[i] == fpt)
{
temp = y_data[i];
for (jj = A_i[i]; jj < A_i[i+1]; jj++)
if (CF_marker_y[A_j[jj]] == fpt) temp += A_data[jj] * x_data[A_j[jj]];
y_data[i] = temp;
}
}
/*-----------------------------------------------------------------
* y = alpha*y
*-----------------------------------------------------------------*/
if (alpha != 1.0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt) y_data[i] *= alpha;
}
return ierr;
}
|
GB_binop__hypot_fp32.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__hypot_fp32
// A.*B function (eWiseMult): GB_AemultB__hypot_fp32
// A*D function (colscale): (none)
// D*A function (rowscale): (node)
// C+=B function (dense accum): GB_Cdense_accumB__hypot_fp32
// C+=b function (dense accum): GB_Cdense_accumb__hypot_fp32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__hypot_fp32
// C=scalar+B GB_bind1st__hypot_fp32
// C=scalar+B' GB_bind1st_tran__hypot_fp32
// C=A+scalar GB_bind2nd__hypot_fp32
// C=A'+scalar GB_bind2nd_tran__hypot_fp32
// C type: float
// A type: float
// B,b type: float
// BinaryOp: cij = hypotf (aij, bij)
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
float
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
float bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
float t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
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 = hypotf (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_HYPOT || GxB_NO_FP32 || GxB_NO_HYPOT_FP32)
//------------------------------------------------------------------------------
// 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__hypot_fp32
(
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__hypot_fp32
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__hypot_fp32
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type float
float bwork = (*((float *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info (none)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *GB_RESTRICT Cx = (float *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info (node)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *GB_RESTRICT Cx = (float *) 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__hypot_fp32
(
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__hypot_fp32
(
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__hypot_fp32
(
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
float *Cx = (float *) Cx_output ;
float x = (*((float *) x_input)) ;
float *Bx = (float *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float bij = Bx [p] ;
Cx [p] = hypotf (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__hypot_fp32
(
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 ;
float *Cx = (float *) Cx_output ;
float *Ax = (float *) Ax_input ;
float y = (*((float *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
Cx [p] = hypotf (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) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = hypotf (x, aij) ; \
}
GrB_Info GB_bind1st_tran__hypot_fp32
(
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 \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
float
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = hypotf (aij, y) ; \
}
GrB_Info GB_bind2nd_tran__hypot_fp32
(
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
float y = (*((const float *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__isne_uint16.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__isne_uint16
// A.*B function (eWiseMult): GB_AemultB__isne_uint16
// A*D function (colscale): GB_AxD__isne_uint16
// D*A function (rowscale): GB_DxB__isne_uint16
// C+=B function (dense accum): GB_Cdense_accumB__isne_uint16
// C+=b function (dense accum): GB_Cdense_accumb__isne_uint16
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isne_uint16
// C=scalar+B GB_bind1st__isne_uint16
// C=scalar+B' GB_bind1st_tran__isne_uint16
// C=A+scalar GB_bind2nd__isne_uint16
// C=A'+scalar GB_bind2nd_tran__isne_uint16
// C type: uint16_t
// A type: uint16_t
// B,b type: uint16_t
// BinaryOp: cij = (aij != bij)
#define GB_ATYPE \
uint16_t
#define GB_BTYPE \
uint16_t
#define GB_CTYPE \
uint16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint16_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
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_ISNE || GxB_NO_UINT16 || GxB_NO_ISNE_UINT16)
//------------------------------------------------------------------------------
// 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__isne_uint16
(
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__isne_uint16
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__isne_uint16
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint16_t
uint16_t bwork = (*((uint16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__isne_uint16
(
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
uint16_t *GB_RESTRICT Cx = (uint16_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__isne_uint16
(
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
uint16_t *GB_RESTRICT Cx = (uint16_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__isne_uint16
(
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__isne_uint16
(
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__isne_uint16
(
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
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t x = (*((uint16_t *) x_input)) ;
uint16_t *Bx = (uint16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_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__isne_uint16
(
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 ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_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) \
{ \
uint16_t aij = Ax [pA] ; \
Cx [pC] = (x != aij) ; \
}
GrB_Info GB_bind1st_tran__isne_uint16
(
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 \
uint16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t x = (*((const uint16_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint16_t aij = Ax [pA] ; \
Cx [pC] = (aij != y) ; \
}
GrB_Info GB_bind2nd_tran__isne_uint16
(
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
uint16_t y = (*((const uint16_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#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] = 4;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
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(1,ceild(24*t2-Nz+9,4)),3*t1+1),6*t1-6*t2+2);t3<=min(min(min(floord(4*Nt+Ny-9,4),floord(12*t1+Ny+15,4)),floord(24*t2+Ny+11,4)),floord(24*t1-24*t2+Nz+Ny+13,4));t3++) {
for (t4=max(max(max(max(0,ceild(3*t1-3*t2-62,64)),ceild(3*t1-126,128)),ceild(24*t2-Nz-499,512)),ceild(4*t3-Ny-499,512));t4<=min(min(min(min(floord(4*Nt+Nx-9,512),floord(12*t1+Nx+15,512)),floord(24*t2+Nx+11,512)),floord(4*t3+Nx-9,512)),floord(24*t1-24*t2+Nz+Nx+13,512));t4++) {
for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(512*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),t3-1),128*t4+126);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=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) {
lbv=max(512*t4,4*t5+4);
ubv=min(512*t4+511,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((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;
}
|
3d7pt_var.c | /*
* 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] = 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<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
#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] = coef[0][i][j][k] * A[t%2][i ][j ][k ] +
coef[1][i][j][k] * A[t%2][i-1][j ][k ] +
coef[2][i][j][k] * A[t%2][i ][j-1][k ] +
coef[3][i][j][k] * A[t%2][i ][j ][k-1] +
coef[4][i][j][k] * A[t%2][i+1][j ][k ] +
coef[5][i][j][k] * A[t%2][i ][j+1][k ] +
coef[6][i][j][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, "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;
}
|
comm.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Copyright (c) 2015 by Contributors
*/
#ifndef MXNET_KVSTORE_COMM_H_
#define MXNET_KVSTORE_COMM_H_
#include <dmlc/omp.h>
#include <string>
#include <algorithm>
#include <utility>
#include <limits>
#include <vector>
#include <tuple>
#include <thread>
#include "mxnet/ndarray.h"
#include "../ndarray/ndarray_function.h"
#include "../operator/tensor/sparse_retain-inl.h"
namespace mxnet {
namespace kvstore {
/**
* \brief multiple device commmunication
*/
class Comm {
public:
Comm() {
pinned_ctx_ = Context::CPUPinned(0);
}
virtual ~Comm() { }
/**
* \brief init key with the data shape and storage shape
*/
virtual void Init(int key, const NDArrayStorageType stype,
const TShape& shape, int dtype = mshadow::kFloat32) = 0;
/**
* \brief returns src[0] + .. + src[src.size()-1]
*/
virtual const NDArray& Reduce(
int key, const std::vector<NDArray>& src, int priority) = 0;
/**
* \brief copy from src to dst[i] for every i
*/
virtual void Broadcast(
int key, const NDArray& src,
const std::vector<NDArray*> dst, int priority) = 0;
/**
* \brief broadcast src to dst[i] with target row_ids for every i
* \param dst a list of destination row_sparse NDArray and its target row_ids to broadcast,
where the row_ids are expected to be unique and sorted
* \param use_copy if set to true, directly copy src to dst[i] without looking up the
provided row_ids
*/
virtual void BroadcastRowSparse(int key, const NDArray& src,
const std::vector<std::pair<NDArray*, NDArray>>& dst,
const bool use_copy,
const int priority) = 0;
/**
* \brief return a pinned contex
*/
Context pinned_ctx() const {
return pinned_ctx_;
}
protected:
Context pinned_ctx_;
};
/**
* \brief an implemention of Comm that first copy data to CPU memeory, and then
* reduce there
*/
class CommCPU : public Comm {
public:
CommCPU() {
nthread_reduction_ = dmlc::GetEnv("MXNET_KVSTORE_REDUCTION_NTHREADS", 4);
bigarray_bound_ = dmlc::GetEnv("MXNET_KVSTORE_BIGARRAY_BOUND", 1000 * 1000);
// TODO(junwu) delete the following data member, now for benchmark only
is_serial_push_ = dmlc::GetEnv("MXNET_KVSTORE_SERIAL_PUSH", 0);
}
virtual ~CommCPU() { }
void Init(int key, const NDArrayStorageType stype, const TShape& shape,
int type = mshadow::kFloat32) override {
if (stype == kDefaultStorage) {
merge_buf_[key].merged = NDArray(shape, pinned_ctx_, false, type);
} else {
merge_buf_[key].merged = NDArray(stype, shape, pinned_ctx_, true, type);
}
}
const NDArray& Reduce(int key, const std::vector<NDArray>& src,
int priority) override {
auto& buf = merge_buf_[key];
// avoid extra copy for single device, but it may bring problems for
// abnormal usage of kvstore
if (src.size() == 1) {
if (src[0].storage_type() == kDefaultStorage) {
return src[0];
} else { // if sparse and only one GPU, always update weight on CPU
CopyFromTo(src[0], &buf.merged, priority);
return buf.merged;
}
}
if (buf.merged.storage_type() == kDefaultStorage) {
std::vector<Engine::VarHandle> const_vars(src.size() - 1);
std::vector<NDArray> reduce(src.size());
CopyFromTo(src[0], &buf.merged, priority);
reduce[0] = buf.merged;
if (buf.copy_buf.empty()) {
buf.copy_buf.resize(src.size()-1);
for (size_t j = 0; j < src.size() - 1; ++j) {
// allocate NDArray based on storage type
buf.copy_buf[j] = NDArray(
src[0].shape(), pinned_ctx_, false, src[0].dtype());
}
}
for (size_t i = 1; i < src.size(); ++i) {
CopyFromTo(src[i], &(buf.copy_buf[i-1]), priority);
reduce[i] = buf.copy_buf[i-1];
const_vars[i-1] = reduce[i].var();
}
Engine::Get()->PushAsync(
[reduce, this](RunContext rctx, Engine::CallbackOnComplete on_complete) {
ReduceSumCPU(reduce);
on_complete();
}, Context::CPU(), const_vars, {reduce[0].var()},
FnProperty::kCPUPrioritized, priority, PROFILER_MESSAGE("KVStoreReduce"));
} else {
// buf.merged is a sparse ndarray.
std::vector<Engine::VarHandle> const_vars(src.size());
std::vector<NDArray> reduce(src.size());
if (buf.copy_buf.empty()) {
buf.copy_buf.resize(src.size());
for (size_t j = 0; j < src.size(); ++j) {
buf.copy_buf[j] = NDArray(
src[0].storage_type(), src[0].shape(), pinned_ctx_, true, src[0].dtype());
}
}
for (size_t i = 0; i < src.size(); ++i) {
CopyFromTo(src[i], &(buf.copy_buf[i]), priority);
reduce[i] = buf.copy_buf[i];
const_vars[i] = reduce[i].var();
}
auto result = buf.merged;
Engine::Get()->PushAsync(
[reduce, result, this](RunContext rctx, Engine::CallbackOnComplete on_complete) {
NDArray out = result;
Resource rsc = ResourceManager::Get()->Request(rctx.ctx,
ResourceRequest(ResourceRequest::kTempSpace));
is_serial_push_?
ReduceSumCPUExSerial(reduce, &out)
: mxnet::ndarray::ElementwiseSum(rctx.get_stream<cpu>(), rsc, reduce, &out);
on_complete();
}, Context::CPU(), const_vars, {result.var()},
FnProperty::kCPUPrioritized, priority, PROFILER_MESSAGE("KVStoreReduce"));
}
return buf.merged;
}
void Broadcast(int key, const NDArray& src,
const std::vector<NDArray*> dst, int priority) override {
int mask = src.ctx().dev_mask();
if (mask == Context::kCPU) {
for (auto d : dst) CopyFromTo(src, d, priority);
} else {
// first copy data to cpu, then broadcast
auto& buf = merge_buf_[key];
CopyFromTo(src, &buf.merged, priority);
for (auto d : dst) CopyFromTo(buf.merged, d, priority);
}
}
void BroadcastRowSparse(int key, const NDArray& src,
const std::vector<std::pair<NDArray*, NDArray>>& dst,
const bool use_copy,
const int priority) override {
using namespace mshadow;
CHECK_EQ(src.storage_type(), kRowSparseStorage)
<< "BroadcastRowSparse expects row-sparse src NDArray";
CHECK_EQ(src.ctx().dev_mask(), Context::kCPU)
<< "BroadcastRowSparse with src on gpu context not supported";
for (size_t i = 0; i < dst.size(); ++i) {
NDArray* out = dst[i].first;
NDArray row_id = dst[i].second;
if (use_copy) {
CopyFromTo(src, out, priority);
} else {
CHECK_EQ(out->storage_type(), kRowSparseStorage)
<< "BroadcastRowSparse expects row_sparse dst NDArray";
CHECK_EQ(row_id.ctx().dev_mask(), Context::kCPU)
<< "BroadcastRowSparse with row_indices on gpu context not supported";
// retain according to unique indices
const bool use_sparse_retain = (src.shape()[0] != src.storage_shape()[0])
|| (row_id.dtype() != out->aux_type(rowsparse::kIdx))
|| (out->ctx().dev_mask() != Context::kGPU);
if (use_sparse_retain) { // use sparse_retain op
const bool is_to_gpu = out->ctx().dev_mask() == Context::kGPU;
NDArray out_cpu = is_to_gpu? NDArray(kRowSparseStorage, src.shape(),
src.ctx(), true, src.dtype(), src.aux_types()) : *out;
Engine::Get()->PushAsync(
[=](RunContext rctx, Engine::CallbackOnComplete on_complete) {
const TBlob& indices = row_id.data();
NDArray temp = out_cpu; // get rid of const qualifier
op::SparseRetainOpForwardRspImpl<cpu>(rctx.get_stream<cpu>(),
src, indices, kWriteTo,
&temp);
on_complete();
}, Context::CPU(), {src.var(), row_id.var()}, {out_cpu.var()},
FnProperty::kNormal, priority, PROFILER_MESSAGE("KVStoreSparseRetain"));
if (is_to_gpu) {
CopyFromTo(out_cpu, out, priority);
}
} else { // direct copy rows
Engine::Get()->PushAsync(
[=](RunContext rctx, Engine::CallbackOnComplete on_complete) {
CopyRetainedRowsToGPU(rctx.get_stream<cpu>(), rctx.get_stream<gpu>(),
src, row_id, out);
on_complete();
}, out->ctx(), {src.var(), row_id.var()}, {out->var()},
FnProperty::kCopyToGPU, priority, PROFILER_MESSAGE("KVStoreCopyRetainedRowsToGPU"));
}
}
}
}
private:
/*!
* \brief When src is a rsp with full rows,
* simply copy retained rows directly from cpu to gpu
* without invoking sparse_retain op.
*/
void CopyRetainedRowsToGPU(mshadow::Stream<cpu>* cpu_stream,
mshadow::Stream<gpu>* gpu_stream,
const NDArray& src,
const NDArray& indices,
NDArray* dst) {
#if MXNET_USE_CUDA == 1
CHECK_EQ(src.storage_type(), kRowSparseStorage)
<< "CopyRetainedRowsToGPU expects row-sparse src NDArray";
CHECK_EQ(src.ctx().dev_mask(), Context::kCPU)
<< "CopyRetainedRowsToGPU with src on gpu context not supported";
CHECK_EQ(src.storage_shape()[0], src.shape()[0])
<< "CopyRetainedRowsToGPU only supports src rsp with full rows";
CHECK_EQ(indices.storage_type(), kDefaultStorage);
CHECK_EQ(indices.ctx().dev_mask(), Context::kCPU);
CHECK_EQ(dst->storage_type(), kRowSparseStorage);
CHECK_EQ(dst->ctx().dev_mask(), Context::kGPU);
CHECK_EQ(indices.dtype(), dst->aux_type(rowsparse::kIdx))
<< "CopyRetainedRowsToGPU only supports same data type for idx array and dst aux_data(0)";
if (!src.storage_initialized() || indices.data().Size() == 0U) {
op::FillZerosRspImpl(gpu_stream, *dst);
return;
}
using namespace mshadow;
const TBlob& src_data = src.data();
const TBlob& idx_data = indices.data();
const size_t row_length = src.shape().ProdShape(1, src.shape().ndim());
const size_t num_rows_retained = idx_data.Size();
dst->CheckAndAlloc({Shape1(num_rows_retained)});
TBlob dst_data = dst->data();
TBlob dst_idx_data = dst->aux_data(rowsparse::kIdx);
MSHADOW_TYPE_SWITCH(src.dtype(), DType, {
MSHADOW_IDX_TYPE_SWITCH(indices.dtype(), IType, {
// copy idx array
Tensor<gpu, 1, IType> dst_idx_tensor = dst_idx_data.FlatTo1D<gpu, IType>(gpu_stream);
const Tensor<cpu, 1, IType> idx_tensor = idx_data.FlatTo1D<cpu, IType>(cpu_stream);
Copy(dst_idx_tensor, idx_tensor, gpu_stream);
// copy src data
const Tensor<cpu, 2, DType> src_data_tensor = src_data.get_with_shape<cpu, 2, DType>(
Shape2(src_data.shape_[0], row_length), cpu_stream);
Tensor<gpu, 2, DType> dst_data_tensor = dst_data.get_with_shape<gpu, 2, DType>(
Shape2(dst_data.shape_[0], row_length), gpu_stream);
for (size_t i = 0; i < num_rows_retained; ++i) {
Copy(dst_data_tensor[i], src_data_tensor[idx_tensor[i]], gpu_stream);
}
})
})
#else
LOG(FATAL) << "GPU not enabled";
#endif
}
// reduce sum into val[0]
inline void ReduceSumCPU(const std::vector<NDArray> &in_data) {
MSHADOW_TYPE_SWITCH(in_data[0].dtype(), DType, {
std::vector<DType*> dptr(in_data.size());
for (size_t i = 0; i < in_data.size(); ++i) {
TBlob data = in_data[i].data();
CHECK(data.CheckContiguous());
dptr[i] = data.FlatTo2D<cpu, DType>().dptr_;
}
size_t total = in_data[0].shape().Size();
ReduceSumCPUImpl(dptr, total);
});
}
// serial implementation of reduce sum for row sparse NDArray.
inline void ReduceSumCPUExSerial(const std::vector<NDArray> &in, NDArray *out) {
using namespace rowsparse;
using namespace mshadow;
auto stype = out->storage_type();
CHECK_EQ(stype, kRowSparseStorage) << "Unexpected storage type " << stype;
size_t total_num_rows = 0;
size_t num_in = in.size();
// skip the ones with empty indices and values
std::vector<bool> skip(num_in, false);
// the values tensor of the inputs
MSHADOW_TYPE_SWITCH(out->dtype(), DType, {
MSHADOW_IDX_TYPE_SWITCH(out->aux_type(kIdx), IType, {
std::vector<Tensor<cpu, 2, DType>> in_vals(num_in);
std::vector<Tensor<cpu, 1, IType>> in_indices(num_in);
// offset to the values tensor of all inputs
std::vector<size_t> offsets(num_in, 0);
std::vector<size_t> num_rows(num_in, 0);
for (size_t i = 0; i < num_in; i++) {
if (!in[i].storage_initialized()) {
skip[i] = true;
continue;
}
auto size = in[i].aux_shape(kIdx).Size();
num_rows[i] = size;
total_num_rows += size;
in_vals[i] = in[i].data().FlatTo2D<cpu, DType>();
in_indices[i] = in[i].aux_data(kIdx).FlatTo1D<cpu, IType>();
}
std::vector<IType> indices;
indices.reserve(total_num_rows);
// gather indices from all inputs
for (size_t i = 0; i < num_in; i++) {
for (size_t j = 0; j < num_rows[i]; j++) {
indices.emplace_back(in_indices[i][j]);
}
}
CHECK_EQ(indices.size(), total_num_rows);
// dedup indices
std::sort(indices.begin(), indices.end());
indices.resize(std::unique(indices.begin(), indices.end()) - indices.begin());
// the one left are unique non-zero rows
size_t nnr = indices.size();
// allocate memory for output
out->CheckAndAlloc({Shape1(nnr)});
auto idx_data = out->aux_data(kIdx).FlatTo1D<cpu, IType>();
auto val_data = out->data().FlatTo2D<cpu, DType>();
for (size_t i = 0; i < nnr; i++) {
// copy indices back
idx_data[i] = indices[i];
bool zeros = true;
for (size_t j = 0; j < num_in; j++) {
if (skip[j]) continue;
size_t offset = offsets[j];
if (offset < num_rows[j]) {
if (indices[i] == in_indices[j][offset]) {
if (zeros) {
Copy(val_data[i], in_vals[j][offset], nullptr);
zeros = false;
} else {
val_data[i] += in_vals[j][offset];
}
offsets[j] += 1;
}
}
}
}
});
});
}
template<typename DType>
inline static void ReduceSumCPU(
const std::vector<DType*> &dptr, size_t offset, index_t size) {
using namespace mshadow; // NOLINT(*)
Tensor<cpu, 1, DType> in_0(dptr[0] + offset, Shape1(size));
for (size_t i = 1; i < dptr.size(); i+=4) {
switch (dptr.size() - i) {
case 1: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
in_0 += in_1;
break;
}
case 2: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size));
in_0 += in_1 + in_2;
break;
}
case 3: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size));
in_0 += in_1 + in_2 + in_3;
break;
}
default: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_4(dptr[i+3] + offset, Shape1(size));
in_0 += in_1 + in_2 + in_3 + in_4;
break;
}
}
}
}
template<typename DType>
inline void ReduceSumCPUImpl(std::vector<DType*> dptr, size_t total) {
const size_t step = std::min(bigarray_bound_, static_cast<size_t>(4 << 10));
long ntask = (total + step - 1) / step; // NOLINT(*)
if (total < bigarray_bound_ || nthread_reduction_ <= 1) {
ReduceSumCPU(dptr, 0, total);
} else {
#pragma omp parallel for schedule(static) num_threads(nthread_reduction_)
for (long j = 0; j < ntask; ++j) { // NOLINT(*)
size_t k = static_cast<size_t>(j);
size_t begin = std::min(k * step, total);
size_t end = std::min((k + 1) * step, total);
if (j == ntask - 1) CHECK_EQ(end, total);
ReduceSumCPU(dptr, begin, static_cast<index_t>(end - begin));
}
}
}
/// \brief temporal space for pushing and pulling
struct BufferEntry {
/// \brief the merged value
NDArray merged;
/// \brief the cpu buffer for gpu data
std::vector<NDArray> copy_buf;
};
std::unordered_map<int, BufferEntry> merge_buf_;
size_t bigarray_bound_;
int nthread_reduction_;
bool is_serial_push_;
};
/**
* \brief an implementation of Comm that performs reduction on device
* directly.
*
* It is faster if the total device-to-device bandwidths is larger than
* device-to-cpu, which is often true for 4 or 8 GPUs. But it uses more device
* memory.
*/
class CommDevice : public Comm {
public:
CommDevice() {
inited_ = false;
}
virtual ~CommDevice() { }
void Init(int key, const NDArrayStorageType stype, const TShape& shape,
int dtype = mshadow::kFloat32) override {
if (stype == kDefaultStorage) {
sorted_key_attrs_.push_back(std::make_tuple(key, shape, dtype));
} else {
LOG(FATAL) << "storage type " << stype << " not implemented for device yet";
}
}
const NDArray& Reduce(int key, const std::vector<NDArray>& src,
int priority) override {
// avoid extra copy for single device, but it may bring problems for
// abnormal usage of kvstore
if (src.size() == 1) {
return src[0];
}
if (!inited_) {
std::vector<Context> devs;
for (const auto& a : src) {
devs.push_back(a.ctx());
}
InitMergeBuffer(devs);
if (dmlc::GetEnv("MXNET_ENABLE_GPU_P2P", 1)) {
EnableP2P(devs);
}
}
auto& buf = merge_buf_[key];
std::vector<NDArray> reduce(src.size());
CopyFromTo(src[0], &(buf.merged), priority);
reduce[0] = buf.merged;
if (buf.copy_buf.empty()) {
// TODO(mli) this results in large device memory usage for huge ndarray,
// such as the largest fullc in VGG. consider to do segment reduce with
// NDArray.Slice or gpu direct memory access. for the latter, we need to
// remove some ctx check, and also it reduces 20% perf
buf.copy_buf.resize(src.size()-1);
for (size_t i = 0; i < src.size()-1; ++i) {
buf.copy_buf[i] = NDArray(
buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype());
}
}
for (size_t i = 0; i < src.size()-1; ++i) {
CopyFromTo(src[i+1], &(buf.copy_buf[i]), priority);
reduce[i+1] = buf.copy_buf[i];
}
ElementwiseSum(reduce, &buf.merged);
return buf.merged;
}
void Broadcast(int key, const NDArray& src,
const std::vector<NDArray*> dst, int priority) override {
if (!inited_) {
// copy to a random device first
int dev_id = key % dst.size();
CopyFromTo(src, dst[dev_id], priority);
for (size_t i = 0; i < dst.size(); ++i) {
if (i != static_cast<size_t>(dev_id)) {
CopyFromTo(*dst[dev_id], dst[i], priority);
}
}
} else {
auto& buf = merge_buf_[key];
CopyFromTo(src, &buf.merged, priority);
for (auto d : dst) {
CopyFromTo(buf.merged, d, priority);
}
}
}
void BroadcastRowSparse(int key, const NDArray& src,
const std::vector<std::pair<NDArray*, NDArray>>& dst,
const bool use_copy,
const int priority) override {
LOG(FATAL) << "Not implemented yet";
}
private:
void EnableP2P(const std::vector<Context>& devs) {
#if MXNET_USE_CUDA
std::vector<int> gpus;
for (const auto& d : devs) {
if (d.dev_mask() == gpu::kDevMask) {
gpus.push_back(d.dev_id);
}
}
int n = static_cast<int>(gpus.size());
int enabled = 0;
std::vector<int> p2p(n*n);
for (int i = 0; i < n; ++i) {
cudaSetDevice(gpus[i]);
for (int j = 0; j < n; j++) {
int access;
cudaDeviceCanAccessPeer(&access, gpus[i], gpus[j]);
if (access) {
cudaError_t e = cudaDeviceEnablePeerAccess(gpus[j], 0);
if (e == cudaSuccess || e == cudaErrorPeerAccessAlreadyEnabled) {
++enabled;
p2p[i*n+j] = 1;
}
}
}
}
if (enabled != n*(n-1)) {
// print warning info if not fully enabled
LOG(WARNING) << "only " << enabled << " out of "
<< n*(n-1) << " GPU pairs are enabled direct access. "
<< "It may affect the performance. "
<< "You can set MXNET_ENABLE_GPU_P2P=0 to turn it off";
std::string access(n, '.');
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
access[j] = p2p[i*n+j] ? 'v' : '.';
}
LOG(WARNING) << access;
}
}
#endif
}
using KeyAttrs = std::tuple<int, TShape, int>;
// try to allocate buff on device evenly
void InitMergeBuffer(const std::vector<Context>& devs) {
std::sort(sorted_key_attrs_.begin(), sorted_key_attrs_.end(), [](
const KeyAttrs& a, const KeyAttrs& b) {
return std::get<1>(a).Size() > std::get<1>(b).Size();
});
std::unordered_map<int, std::pair<Context, size_t>> ctx_info;
for (auto d : devs) {
ctx_info[d.dev_id] = std::make_pair(d, 0);
}
for (size_t i = 0; i < sorted_key_attrs_.size(); ++i) {
int key = std::get<0>(sorted_key_attrs_[i]);
TShape s = std::get<1>(sorted_key_attrs_[i]);
int type = std::get<2>(sorted_key_attrs_[i]);
auto& buf = merge_buf_[key];
Context ctx;
size_t min_size = std::numeric_limits<size_t>::max();
for (auto it = ctx_info.begin(); it != ctx_info.end(); ++it) {
size_t size = it->second.second;
if (size <= min_size) {
ctx = it->second.first;
min_size = size;
}
}
buf.merged = NDArray(s, ctx, false, type);
ctx_info[ctx.dev_id].second += s.Size();
}
inited_ = true;
}
std::vector<KeyAttrs> sorted_key_attrs_;
/// \brief temporal space for pushing and pulling
struct BufferEntry {
/// \brief the merged value
NDArray merged;
/// \brief the gpu buffer
std::vector<NDArray> copy_buf;
};
std::unordered_map<int, BufferEntry> merge_buf_;
bool inited_;
};
} // namespace kvstore
} // namespace mxnet
#endif // MXNET_KVSTORE_COMM_H_
|
SpatialSubSampling.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/SpatialSubSampling.c"
#else
static int nn_(SpatialSubSampling_updateOutput)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
int kW = luaT_getfieldcheckint(L, 1, "kW");
int kH = luaT_getfieldcheckint(L, 1, "kH");
int dW = luaT_getfieldcheckint(L, 1, "dW");
int dH = luaT_getfieldcheckint(L, 1, "dH");
int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane");
THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor *bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor);
THTensor *output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
real *weight_data = THTensor_(data)(weight);
real *bias_data = THTensor_(data)(bias);
real *output_data;
real *input_data;
int dimw = 2;
int dimh = 1;
long nbatch = 1;
long inputWidth;
long inputHeight;
long outputWidth;
long outputHeight;
long k;
luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D(batch mode) tensor expected");
if (input->nDimension == 4) {
nbatch = input->size[0];
dimw++;
dimh++;
}
inputWidth = input->size[dimw];
inputHeight = input->size[dimh];
outputWidth = (inputWidth - kW) / dW + 1;
outputHeight = (inputHeight - kH) / dH + 1;
luaL_argcheck(L, input->size[dimh-1] == nInputPlane, 2, "invalid number of input planes");
luaL_argcheck(L, inputWidth >= kW && inputHeight >= kH, 2, "input image smaller than kernel size");
if (input->nDimension == 3)
THTensor_(resize3d)(output, nInputPlane, outputHeight, outputWidth);
else
THTensor_(resize4d)(output, input->size[0], nInputPlane, outputHeight, outputWidth);
input = THTensor_(newContiguous)(input);
input_data = THTensor_(data)(input);
output_data = THTensor_(data)(output);
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
long p;
for(p = 0; p < nbatch; p++)
{
long xx, yy;
/* For all output pixels... */
real *ptr_output = output_data + p*nInputPlane*outputWidth*outputHeight + k*outputWidth*outputHeight;
/* Get the good mask for (k,i) (k out, i in) */
real the_weight = weight_data[k];
/* Initialize to the bias */
real z = bias_data[k];
long i;
for(i = 0; i < outputWidth*outputHeight; i++)
ptr_output[i] = z;
for(yy = 0; yy < outputHeight; yy++)
{
for(xx = 0; xx < outputWidth; xx++)
{
/* Compute the mean of the input image... */
real *ptr_input = input_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight + yy*dH*inputWidth+xx*dW;
real sum = 0;
long kx, ky;
for(ky = 0; ky < kH; ky++)
{
for(kx = 0; kx < kW; kx++)
sum += ptr_input[kx];
ptr_input += inputWidth; /* next input line */
}
/* Update output */
*ptr_output++ += the_weight*sum;
}
}
}
}
THTensor_(free)(input);
return 1;
}
static int nn_(SpatialSubSampling_updateGradInput)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
THTensor *gradOutput = luaT_checkudata(L, 3, torch_Tensor);
int kW = luaT_getfieldcheckint(L, 1, "kW");
int kH = luaT_getfieldcheckint(L, 1, "kH");
int dW = luaT_getfieldcheckint(L, 1, "dW");
int dH = luaT_getfieldcheckint(L, 1, "dH");
int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane");
THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor *gradInput = luaT_getfieldcheckudata(L, 1, "gradInput", torch_Tensor);
int dimw = 2;
int dimh = 1;
long nbatch = 1;
long inputWidth;
long inputHeight;
long outputWidth;
long outputHeight;
real *weight_data;
real *gradOutput_data;
real *input_data, *gradInput_data;
long k;
if (input->nDimension == 4) {
nbatch = input->size[0];
dimw++;
dimh++;
}
inputWidth = input->size[dimw];
inputHeight = input->size[dimh];
outputWidth = (inputWidth - kW) / dW + 1;
outputHeight = (inputHeight - kH) / dH + 1;
weight_data = THTensor_(data)(weight);
gradOutput_data = THTensor_(data)(gradOutput);
input_data = THTensor_(data)(input);
THTensor_(resizeAs)(gradInput, input);
gradInput_data = THTensor_(data)(gradInput);
gradOutput_data = THTensor_(data)(gradOutput);
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
long p;
for(p = 0; p < nbatch; p++)
{
real the_weight = weight_data[k];
real *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight;
long xx, yy;
real* ptr_gi = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight;
long i;
for(i=0; i<inputWidth*inputHeight; i++)
ptr_gi[i] = 0.0;
for(yy = 0; yy < outputHeight; yy++)
{
for(xx = 0; xx < outputWidth; xx++)
{
real *ptr_gradInput = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight + yy*dH*inputWidth+xx*dW;
real z = *ptr_gradOutput++ * the_weight;
long kx, ky;
for(ky = 0; ky < kH; ky++)
{
for(kx = 0; kx < kW; kx++)
ptr_gradInput[kx] += z;
ptr_gradInput += inputWidth;
}
}
}
}
}
return 1;
}
static int nn_(SpatialSubSampling_accGradParameters)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
THTensor *gradOutput = luaT_checkudata(L, 3, torch_Tensor);
real scale = luaL_optnumber(L, 4, 1);
int kW = luaT_getfieldcheckint(L, 1, "kW");
int kH = luaT_getfieldcheckint(L, 1, "kH");
int dW = luaT_getfieldcheckint(L, 1, "dW");
int dH = luaT_getfieldcheckint(L, 1, "dH");
int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane");
THTensor *gradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor);
THTensor *gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor);
long nbatch = 1;
long dimw = 2;
long dimh = 1;
long inputWidth;
long inputHeight;
long outputWidth;
long outputHeight;
real *gradWeight_data;
real *gradBias_data;
real *gradOutput_data;
real *input_data;
long k;
if (input->nDimension == 4) {
dimw++;
dimh++;
nbatch = input->size[0];
}
inputWidth = input->size[dimw];
inputHeight = input->size[dimh];
outputWidth = (inputWidth - kW) / dW + 1;
outputHeight = (inputHeight - kH) / dH + 1;
gradWeight_data = THTensor_(data)(gradWeight);
gradBias_data = THTensor_(data)(gradBias);
gradOutput_data = THTensor_(data)(gradOutput);
input = THTensor_(newContiguous)(input);
input_data = THTensor_(data)(input);
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
long p;
for(p = 0; p < nbatch; p++)
{
real *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight;
real sum;
long xx, yy;
long i;
sum = 0;
for(i = 0; i < outputWidth*outputHeight; i++)
sum += ptr_gradOutput[i];
gradBias_data[k] += scale*sum;
sum = 0;
for(yy = 0; yy < outputHeight; yy++)
{
for(xx = 0; xx < outputWidth; xx++)
{
real *ptr_input = input_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight + yy*dH*inputWidth+xx*dW;
real z = *ptr_gradOutput++;
long kx, ky;
for(ky = 0; ky < kH; ky++)
{
for(kx = 0; kx < kW; kx++)
sum += z * ptr_input[kx];
ptr_input += inputWidth;
}
}
}
gradWeight_data[k] += scale*sum;
}
}
THTensor_(free)(input);
return 0;
}
static const struct luaL_Reg nn_(SpatialSubSampling__) [] = {
{"SpatialSubSampling_updateOutput", nn_(SpatialSubSampling_updateOutput)},
{"SpatialSubSampling_updateGradInput", nn_(SpatialSubSampling_updateGradInput)},
{"SpatialSubSampling_accGradParameters", nn_(SpatialSubSampling_accGradParameters)},
{NULL, NULL}
};
static void nn_(SpatialSubSampling_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, nn_(SpatialSubSampling__), "nn");
lua_pop(L,1);
}
#endif
|
GB_binop__eq_uint32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__eq_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__eq_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__eq_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__eq_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_uint32)
// A*D function (colscale): GB (_AxD__eq_uint32)
// D*A function (rowscale): GB (_DxB__eq_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__eq_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__eq_uint32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_uint32)
// C=scalar+B GB (_bind1st__eq_uint32)
// C=scalar+B' GB (_bind1st_tran__eq_uint32)
// C=A+scalar GB (_bind2nd__eq_uint32)
// C=A'+scalar GB (_bind2nd_tran__eq_uint32)
// C type: bool
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = (aij == bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint32_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
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_EQ || GxB_NO_UINT32 || GxB_NO_EQ_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void 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__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *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__eq_uint32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// get the scalar b for C += b, of type uint32_t
uint32_t bwork = (*((uint32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *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__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *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__eq_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__eq_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__eq_uint32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__eq_uint32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_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__eq_uint32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_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) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x == aij) ; \
}
GrB_Info GB (_bind1st_tran__eq_uint32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij == y) ; \
}
GrB_Info GB (_bind2nd_tran__eq_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
simple.c | // RUN: %libomp-compile
// RUN: env OMP_DISPLAY_AFFINITY=false %libomp-run | %python %S/check.py -c 'NOTHING' %s
// RUN: env OMP_DISPLAY_AFFINITY=true OMP_NUM_THREADS=1 %libomp-run | %python %S/check.py -c 'CHECK' %s
// RUN: env OMP_DISPLAY_AFFINITY=true OMP_NUM_THREADS=2 %libomp-run | %python %S/check.py -c 'CHECK-2' %s
// RUN: env OMP_DISPLAY_AFFINITY=true OMP_NUM_THREADS=3 %libomp-run | %python %S/check.py -c 'CHECK-3' %s
// RUN: env OMP_DISPLAY_AFFINITY=true OMP_NUM_THREADS=4 %libomp-run | %python %S/check.py -c 'CHECK-4' %s
// RUN: env OMP_DISPLAY_AFFINITY=true OMP_NUM_THREADS=8 %libomp-run | %python %S/check.py -c 'CHECK-8' %s
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(int argc, char** argv) {
omp_set_affinity_format("TESTER: tl:%L tn:%n nt:%N");
#pragma omp parallel
{ }
#pragma omp parallel
{ }
return 0;
}
// NOTHING: NO_OUTPUT
// CHECK: num_threads=1 TESTER: tl:1 tn:0 nt:1
// CHECK-2: num_threads=2 TESTER: tl:1 tn:[01] nt:2
// CHECK-3: num_threads=3 TESTER: tl:1 tn:[0-2] nt:3
// CHECK-4: num_threads=4 TESTER: tl:1 tn:[0-3] nt:4
// CHECK-8: num_threads=8 TESTER: tl:1 tn:[0-7] nt:8
|
affinity_values.c | // RUN: %libomp-compile
// RUN: env OMP_PROC_BIND=close OMP_PLACES=threads %libomp-run
// RUN: env OMP_PROC_BIND=close OMP_PLACES=cores %libomp-run
// RUN: env OMP_PROC_BIND=close OMP_PLACES=sockets %libomp-run
// RUN: env KMP_AFFINITY=compact %libomp-run
// RUN: env KMP_AFFINITY=scatter %libomp-run
// REQUIRES: affinity
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#define XSTR(x) #x
#define STR(x) XSTR(x)
#define streqls(s1, s2) (!strcmp(s1, s2))
#define check(condition) \
if (!(condition)) { \
fprintf(stderr, "error: %s: %d: " STR(condition) "\n", __FILE__, \
__LINE__); \
exit(1); \
}
#define DEBUG 0
#if DEBUG
#include <stdarg.h>
#endif
#define BUFFER_SIZE 1024
char buf[BUFFER_SIZE];
#pragma omp threadprivate(buf)
static int debug_printf(const char* format, ...) {
int retval = 0;
#if DEBUG
va_list args;
va_start(args, format);
retval = vprintf(format, args);
va_end(args);
#endif
return retval;
}
static void display_affinity_environment() {
#if DEBUG
printf("Affinity Environment:\n");
printf(" OMP_PROC_BIND=%s\n", getenv("OMP_PROC_BIND"));
printf(" OMP_PLACES=%s\n", getenv("OMP_PLACES"));
printf(" KMP_AFFINITY=%s\n", getenv("KMP_AFFINITY"));
#endif
}
// Reads in a list of integers into ids array (not going past ids_size)
// e.g., if affinity = "0-4,6,8-10,14,16,17-20,23"
// then ids = [0,1,2,3,4,6,8,9,10,14,16,17,18,19,20,23]
void list_to_ids(const char* affinity, int* ids, int ids_size) {
int id, b, e, ids_index;
char *aff, *begin, *end, *absolute_end;
aff = strdup(affinity);
absolute_end = aff + strlen(aff);
ids_index = 0;
begin = end = aff;
while (end < absolute_end) {
end = begin;
while (*end != '\0' && *end != ',')
end++;
*end = '\0';
if (strchr(begin, '-') != NULL) {
// Range
sscanf(begin, "%d-%d", &b, &e);
} else {
// Single Number
sscanf(begin, "%d", &b);
e = b;
}
for (id = b; id <= e; ++id) {
ids[ids_index++] = id;
if (ids_index >= ids_size) {
free(aff);
return;
}
}
begin = end + 1;
}
free(aff);
}
void check_thread_affinity() {
int i;
const char *formats[2] = {"%{thread_affinity}", "%A"};
for (i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) {
omp_set_affinity_format(formats[i]);
#pragma omp parallel
{
int j, k;
int place = omp_get_place_num();
int num_procs = omp_get_place_num_procs(place);
int *ids = (int *)malloc(sizeof(int) * num_procs);
int *ids2 = (int *)malloc(sizeof(int) * num_procs);
char buf[256];
size_t n = omp_capture_affinity(buf, 256, NULL);
check(n <= 256);
omp_get_place_proc_ids(place, ids);
list_to_ids(buf, ids2, num_procs);
#pragma omp for schedule(static) ordered
for (k = 0; k < omp_get_num_threads(); ++k) {
#pragma omp ordered
{
debug_printf("Thread %d: captured affinity = %s\n",
omp_get_thread_num(), buf);
for (j = 0; j < num_procs; ++j) {
debug_printf("Thread %d: ids[%d] = %d ids2[%d] = %d\n",
omp_get_thread_num(), j, ids[j], j, ids2[j]);
check(ids[j] == ids2[j]);
}
}
}
free(ids);
free(ids2);
}
}
}
int main(int argc, char** argv) {
omp_set_nested(1);
display_affinity_environment();
check_thread_affinity();
return 0;
}
|
nodal_sensitivity_builder.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors:
//
#if !defined(KRATOS_NODAL_SENSITIVITY_BUILDER_H_INCLUDED)
#define KRATOS_NODAL_SENSITIVITY_BUILDER_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "includes/model_part.h"
#include "utilities/openmp_utils.h"
#include "response_functions/adjoint_response_function.h"
namespace Kratos
{
///@name Kratos Classes
///@{
class NodalSensitivityBuilder
{
public:
///@name Type Definitions
///@{
typedef Geometry<Node<3>> GeometryType;
///@}
///@name Life Cycle
///@{
NodalSensitivityBuilder(ModelPart& rModelPart, AdjointResponseFunction::Pointer pResponseFunction)
: mrModelPart(rModelPart), mpResponseFunction(pResponseFunction)
{
}
///@}
///@name Operations
///@{
void BuildNodalSolutionStepSensitivities(std::string const& rVariable,
double ScalingFactor = 1.0)
{
KRATOS_TRY;
if (KratosComponents<Variable<double>>::Has(rVariable) == true)
{
const Variable<double>& r_variable =
KratosComponents<Variable<double>>::Get(rVariable);
BuildNodalSolutionStepSensitivities(r_variable, ScalingFactor);
}
else if (KratosComponents<Variable<array_1d<double, 3>>>::Has(rVariable) == true)
{
const Variable<array_1d<double, 3>>& r_variable =
KratosComponents<Variable<array_1d<double, 3>>>::Get(rVariable);
BuildNodalSolutionStepSensitivities(r_variable, ScalingFactor);
}
else
KRATOS_ERROR << "Unsupported variable: " << rVariable << "." << std::endl;
KRATOS_CATCH("");
}
///@}
private:
///@name Private Operations
///@{
template <class TDataType>
void BuildNodalSolutionStepSensitivities(Variable<TDataType> const& rVariable,
double ScalingFactor)
{
KRATOS_TRY;
Communicator& r_comm = mrModelPart.GetCommunicator();
if (r_comm.TotalProcesses() > 1)
{
// Make sure we only add the old sensitivity once when we assemble.
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(mrModelPart.NumberOfNodes()); ++i)
{
const auto it = mrModelPart.NodesBegin() + i;
if (it->FastGetSolutionStepValue(PARTITION_INDEX) != r_comm.MyPID())
it->FastGetSolutionStepValue(rVariable) = rVariable.Zero();
}
}
BuildNodalSolutionStepElementContributions(rVariable, ScalingFactor);
BuildNodalSolutionStepConditionContributions(rVariable, ScalingFactor);
r_comm.AssembleCurrentData(rVariable);
KRATOS_CATCH("");
}
///@}
private:
///@name Member Variables
///@{
ModelPart& mrModelPart;
AdjointResponseFunction::Pointer mpResponseFunction;
///@}
///@name Private Operations
///@{
template <class TDataType>
void BuildNodalSolutionStepElementContributions(Variable<TDataType> const& rVariable,
double ScalingFactor)
{
KRATOS_TRY;
auto& r_elements = mrModelPart.Elements();
const auto& r_process_info = mrModelPart.GetProcessInfo();
const int num_threads = OpenMPUtils::GetNumThreads();
std::vector<Vector> local_sensitivity(num_threads);
std::vector<Vector> partial_sensitivity(num_threads);
std::vector<Vector> adjoint_vector(num_threads);
std::vector<Matrix> sensitivity_matrix(num_threads);
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(r_elements.size()); ++i)
{
const auto it = r_elements.begin() + i;
const int k = OpenMPUtils::ThisThread();
Element::GeometryType& r_geom = it->GetGeometry();
if (HasActiveNodes(r_geom) == false)
continue;
it->CalculateSensitivityMatrix(rVariable, sensitivity_matrix[k], r_process_info);
mpResponseFunction->CalculatePartialSensitivity(
*it, rVariable, sensitivity_matrix[k], partial_sensitivity[k], r_process_info);
it->GetValuesVector(adjoint_vector[k]);
if (local_sensitivity[k].size() != sensitivity_matrix[k].size1())
local_sensitivity[k].resize(sensitivity_matrix[k].size1(), false);
noalias(local_sensitivity[k]) =
ScalingFactor * (prod(sensitivity_matrix[k], adjoint_vector[k]) +
partial_sensitivity[k]);
AssembleNodalSolutionStepSensitivityContribution(
rVariable, local_sensitivity[k], r_geom);
}
KRATOS_CATCH("");
}
template <class TDataType>
void BuildNodalSolutionStepConditionContributions(Variable<TDataType> const& rVariable,
double ScalingFactor)
{
KRATOS_TRY;
auto& r_conditions = mrModelPart.Conditions();
const auto& r_process_info = mrModelPart.GetProcessInfo();
const int num_threads = OpenMPUtils::GetNumThreads();
std::vector<Vector> local_sensitivity(num_threads);
std::vector<Vector> partial_sensitivity(num_threads);
std::vector<Vector> adjoint_vector(num_threads);
std::vector<Matrix> sensitivity_matrix(num_threads);
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(r_conditions.size()); ++i)
{
const auto it = r_conditions.begin() + i;
const int k = OpenMPUtils::ThisThread();
Condition::GeometryType& r_geom = it->GetGeometry();
it->CalculateSensitivityMatrix(rVariable, sensitivity_matrix[k], r_process_info);
if (sensitivity_matrix[k].size1() == 0 || HasActiveNodes(r_geom) == false)
continue;
mpResponseFunction->CalculatePartialSensitivity(
*it, rVariable, sensitivity_matrix[k], partial_sensitivity[k], r_process_info);
it->GetValuesVector(adjoint_vector[k]);
if (local_sensitivity[k].size() != sensitivity_matrix[k].size1())
local_sensitivity[k].resize(sensitivity_matrix[k].size1(), false);
noalias(local_sensitivity[k]) =
ScalingFactor * (prod(sensitivity_matrix[k], adjoint_vector[k]) +
partial_sensitivity[k]);
AssembleNodalSolutionStepSensitivityContribution(
rVariable, local_sensitivity[k], r_geom);
}
KRATOS_CATCH("");
}
bool HasActiveNodes(GeometryType const& rGeom)
{
bool result = false;
for (unsigned i_node = 0; i_node < rGeom.PointsNumber(); ++i_node)
if (rGeom[i_node].GetValue(UPDATE_SENSITIVITIES))
{
result = true;
break;
}
return result;
}
void AssembleNodalSolutionStepSensitivityContribution(Variable<double> const& rVariable,
Vector const& rSensitivityVector,
GeometryType& rGeom)
{
unsigned int index = 0;
for (unsigned int i_node = 0; i_node < rGeom.PointsNumber(); ++i_node)
{
const auto& r_node = rGeom[i_node];
if (r_node.GetValue(UPDATE_SENSITIVITIES))
{
double& r_sensitivity = rGeom[i_node].FastGetSolutionStepValue(rVariable);
rGeom[i_node].SetLock();
r_sensitivity += rSensitivityVector[index++];
rGeom[i_node].UnSetLock();
}
else
++index;
}
}
void AssembleNodalSolutionStepSensitivityContribution(Variable<array_1d<double, 3>> const& rVariable,
Vector const& rSensitivityVector,
GeometryType& rGeom)
{
unsigned int index = 0;
for (unsigned int i_node = 0; i_node < rGeom.PointsNumber(); ++i_node)
{
const auto& r_node = rGeom[i_node];
if (r_node.GetValue(UPDATE_SENSITIVITIES))
{
array_1d<double, 3>& r_sensitivity =
rGeom[i_node].FastGetSolutionStepValue(rVariable);
rGeom[i_node].SetLock();
for (unsigned int d = 0; d < rGeom.WorkingSpaceDimension(); ++d)
r_sensitivity[d] += rSensitivityVector[index++];
rGeom[i_node].UnSetLock();
}
else
index += rGeom.WorkingSpaceDimension();
}
}
///@}
};
///@} // Kratos Classes
} /* namespace Kratos.*/
#endif /* KRATOS_NODAL_SENSITIVITY_BUILDER_H_INCLUDED defined */
|
GB_unaryop__identity_fp32_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__identity_fp32_uint8
// op(A') function: GB_tran__identity_fp32_uint8
// C type: float
// A type: uint8_t
// cast: float cij = (float) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
float z = (float) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_fp32_uint8
(
float *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__identity_fp32_uint8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
io.c |
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include <stddef.h>
#include "base.h"
#include "io.h"
#include "sptensor.h"
#include "matrix.h"
#include "graph.h"
#include "timer.h"
/******************************************************************************
* FILE TYPES
*****************************************************************************/
struct ftype
{
char * extension;
splatt_file_type type;
};
static struct ftype file_extensions[] = {
{ ".tns", SPLATT_FILE_TEXT_COORD },
{ ".coo", SPLATT_FILE_TEXT_COORD },
{ ".bin", SPLATT_FILE_BIN_COORD },
{ NULL, 0}
};
splatt_file_type get_file_type(
char const * const fname)
{
/* find last . in filename */
char const * const suffix = strrchr(fname, '.');
if(suffix == NULL) {
goto NOT_FOUND;
}
size_t idx = 0;
do {
if(strcmp(suffix, file_extensions[idx].extension) == 0) {
return file_extensions[idx].type;
}
} while(file_extensions[++idx].extension != NULL);
/* default to text coordinate format */
NOT_FOUND:
fprintf(stderr, "SPLATT: extension for '%s' not recognized. "
"Defaulting to ASCII coordinate form.\n", fname);
return SPLATT_FILE_TEXT_COORD;
}
/******************************************************************************
* PRIVATE FUNCTIONS
*****************************************************************************/
static sptensor_t * p_tt_read_file(
FILE * fin)
{
char * ptr = NULL;
/* first count nnz in tensor */
idx_t nnz = 0;
idx_t nmodes = 0;
idx_t dims[MAX_NMODES];
idx_t offsets[MAX_NMODES];
tt_get_dims(fin, &nmodes, &nnz, dims, offsets);
if(nmodes > MAX_NMODES) {
fprintf(stderr, "SPLATT ERROR: maximum %"SPLATT_PF_IDX" modes supported. "
"Found %"SPLATT_PF_IDX". Please recompile with "
"MAX_NMODES=%"SPLATT_PF_IDX".\n",
(idx_t) MAX_NMODES, nmodes, nmodes);
return NULL;
}
/* allocate structures */
sptensor_t * tt = tt_alloc(nnz, nmodes);
memcpy(tt->dims, dims, nmodes * sizeof(*dims));
char * line = NULL;
int64_t read;
size_t len = 0;
/* fill in tensor data */
rewind(fin);
nnz = 0;
while((read = getline(&line, &len, fin)) != -1) {
/* skip empty and commented lines */
if(read > 1 && line[0] != '#') {
ptr = line;
for(idx_t m=0; m < nmodes; ++m) {
tt->ind[m][nnz] = strtoull(ptr, &ptr, 10) - offsets[m];
}
tt->vals[nnz++] = strtod(ptr, &ptr);
}
}
free(line);
return tt;
}
/**
* @brief Write a binary header to an input file.
*
* @param fout The file to write to.
* @param tt The tensor to form a header from.
* @param[out] header The header to write.
*/
static void p_write_tt_binary_header(
FILE * fout,
sptensor_t const * const tt,
bin_header * header)
{
int32_t type = SPLATT_BIN_COORD;
fwrite(&type, sizeof(type), 1, fout);
/* now see if all indices fit in 32bit values */
uint64_t idx = tt->nnz < UINT32_MAX ? sizeof(uint32_t) : sizeof(uint64_t);
for(idx_t m=0; m < tt->nmodes; ++m) {
if(tt->dims[m] > UINT32_MAX) {
idx = sizeof(uint64_t);
break;
}
}
/* now see if every value can exactly be represented as a float */
uint64_t val = sizeof(float);
for(idx_t n=0; n < tt->nnz; ++n) {
float conv = tt->vals[n];
if((splatt_val_t) conv != tt->vals[n]) {
val = sizeof(splatt_val_t);
}
}
header->magic = type;
header->idx_width = idx;
header->val_width = val;
fwrite(&idx, sizeof(idx), 1, fout);
fwrite(&val, sizeof(val), 1, fout);
}
/**
* @brief Read a COORD tensor from a binary file, converting from smaller idx or
* val precision if necessary.
*
* @param fin The file to read from.
*
* @return The parsed tensor.
*/
static sptensor_t * p_tt_read_binary_file(
FILE * fin)
{
bin_header header;
read_binary_header(fin, &header);
idx_t nnz = 0;
idx_t nmodes = 0;
idx_t dims[MAX_NMODES];
fill_binary_idx(&nmodes, 1, &header, fin);
fill_binary_idx(dims, nmodes, &header, fin);
fill_binary_idx(&nnz, 1, &header, fin);
if(nmodes > MAX_NMODES) {
fprintf(stderr, "SPLATT ERROR: maximum %"SPLATT_PF_IDX" modes supported. "
"Found %"SPLATT_PF_IDX". Please recompile with "
"MAX_NMODES=%"SPLATT_PF_IDX".\n",
(idx_t) MAX_NMODES, nmodes, nmodes);
return NULL;
}
/* allocate structures */
sptensor_t * tt = tt_alloc(nnz, nmodes);
memcpy(tt->dims, dims, nmodes * sizeof(*dims));
/* fill in tensor data */
for(idx_t m=0; m < nmodes; ++m) {
fill_binary_idx(tt->ind[m], nnz, &header, fin);
}
fill_binary_val(tt->vals, nnz, &header, fin);
return tt;
}
/******************************************************************************
* API FUNCTIONS
*****************************************************************************/
int splatt_load(
char const * const fname,
splatt_idx_t * nmodes,
splatt_idx_t ** dims,
splatt_idx_t * nnz,
splatt_idx_t *** inds,
splatt_val_t ** vals)
{
sptensor_t * tt = tt_read_file(fname);
if(tt == NULL) {
return SPLATT_ERROR_BADINPUT;
}
*nmodes = tt->nmodes;
*dims = tt->dims;
*nnz = tt->nnz;
*vals = tt->vals;
*inds = tt->ind;
free(tt);
return SPLATT_SUCCESS;
}
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
sptensor_t * tt_read_file(
char const * const fname)
{
FILE * fin;
if((fin = fopen(fname, "r")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n", fname);
return NULL;
}
sptensor_t * tt = NULL;
timer_start(&timers[TIMER_IO]);
switch(get_file_type(fname)) {
case SPLATT_FILE_TEXT_COORD:
tt = p_tt_read_file(fin);
break;
case SPLATT_FILE_BIN_COORD:
tt = p_tt_read_binary_file(fin);
break;
}
timer_stop(&timers[TIMER_IO]);
fclose(fin);
return tt;
}
sptensor_t * tt_read_binary_file(
char const * const fname)
{
FILE * fin;
if((fin = fopen(fname, "r")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n", fname);
return NULL;
}
timer_start(&timers[TIMER_IO]);
sptensor_t * tt = p_tt_read_binary_file(fin);
timer_stop(&timers[TIMER_IO]);
fclose(fin);
return tt;
}
void tt_get_dims(
FILE * fin,
idx_t * const outnmodes,
idx_t * const outnnz,
idx_t * outdims,
idx_t * offset)
{
char * ptr = NULL;
idx_t nnz = 0;
char * line = NULL;
ssize_t read;
size_t len = 0;
/* first count modes in tensor */
idx_t nmodes = 0;
while((read = getline(&line, &len, fin)) != -1) {
if(read > 1 && line[0] != '#') {
/* get nmodes from first nnz line */
ptr = strtok(line, " \t");
while(ptr != NULL) {
++nmodes;
ptr = strtok(NULL, " \t");
}
break;
}
}
--nmodes;
for(idx_t m=0; m < nmodes; ++m) {
outdims[m] = 0;
offset[m] = 1;
}
/* fill in tensor dimensions */
rewind(fin);
while((read = getline(&line, &len, fin)) != -1) {
/* skip empty and commented lines */
if(read > 1 && line[0] != '#') {
ptr = line;
for(idx_t m=0; m < nmodes; ++m) {
idx_t ind = strtoull(ptr, &ptr, 10);
/* outdim is maximum */
outdims[m] = (ind > outdims[m]) ? ind : outdims[m];
/* offset is minimum */
offset[m] = (ind < offset[m]) ? ind : offset[m];
}
/* skip over tensor val */
strtod(ptr, &ptr);
++nnz;
}
}
*outnnz = nnz;
*outnmodes = nmodes;
/* only support 0 or 1 indexing */
for(idx_t m=0; m < nmodes; ++m) {
if(offset[m] != 0 && offset[m] != 1) {
fprintf(stderr, "SPLATT: ERROR tensors must be 0 or 1 indexed. "
"Mode %"SPLATT_PF_IDX" is %"SPLATT_PF_IDX" indexed.\n",
m, offset[m]);
exit(1);
}
}
/* adjust dims when zero-indexing */
for(idx_t m=0; m < nmodes; ++m) {
if(offset[m] == 0) {
++outdims[m];
}
}
rewind(fin);
free(line);
}
void tt_write(
sptensor_t const * const tt,
char const * const fname)
{
FILE * fout;
if(fname == NULL) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
tt_write_file(tt, fout);
if(fname != NULL) {
fclose(fout);
}
}
void tt_write_file(
sptensor_t const * const tt,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
for(idx_t n=0; n < tt->nnz; ++n) {
for(idx_t m=0; m < tt->nmodes; ++m) {
/* files are 1-indexed instead of 0 */
fprintf(fout, "%"SPLATT_PF_IDX" ", tt->ind[m][n] + 1);
}
fprintf(fout, "%"SPLATT_PF_VAL"\n", tt->vals[n]);
}
timer_stop(&timers[TIMER_IO]);
}
void tt_write_binary(
sptensor_t const * const tt,
char const * const fname)
{
FILE * fout;
if(fname == NULL) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
tt_write_binary_file(tt, fout);
if(fname != NULL) {
fclose(fout);
}
}
void tt_write_binary_file(
sptensor_t const * const tt,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
bin_header header;
p_write_tt_binary_header(fout, tt, &header);
/* WRITE INDICES */
/* if we are writing to the same precision they are stored in, just fwrite */
if(header.idx_width == sizeof(splatt_idx_t)) {
fwrite(&tt->nmodes, sizeof(tt->nmodes), 1, fout);
fwrite(tt->dims, sizeof(*tt->dims), tt->nmodes, fout);
fwrite(&tt->nnz, sizeof(tt->nnz), 1, fout);
for(idx_t m=0; m < tt->nmodes; ++m) {
fwrite(tt->ind[m], sizeof(*tt->ind[m]), tt->nnz, fout);
}
/* otherwise we convert (downwards) element-wise */
} else if(header.idx_width < sizeof(splatt_idx_t)) {
uint32_t buf = tt->nmodes;
fwrite(&buf, sizeof(buf), 1, fout);
for(idx_t m=0; m < tt->nmodes; ++m) {
buf = tt->dims[m];
fwrite(&buf, sizeof(buf), 1, fout);
}
buf = tt->nnz;
fwrite(&buf, sizeof(buf), 1, fout);
/* write inds */
for(idx_t m=0; m < tt->nmodes; ++m) {
for(idx_t n=0; n < tt->nnz; ++n) {
buf = tt->ind[m][n];
fwrite(&buf, sizeof(buf), 1, fout);
}
}
} else {
/* XXX this should never be reached */
fprintf(stderr, "SPLATT: the impossible happened, "
"idx_width > IDX_TYPEWIDTH.\n");
abort();
}
/* WRITE VALUES */
if(header.val_width == sizeof(splatt_val_t)) {
fwrite(tt->vals, sizeof(*tt->vals), tt->nnz, fout);
/* otherwise we convert (downwards) element-wise */
} else if(header.val_width < sizeof(splatt_val_t)) {
for(idx_t n=0; n < tt->nnz; ++n) {
float buf = tt->vals[n];
fwrite(&buf, sizeof(buf), 1, fout);
}
} else {
/* XXX this should never be reached */
fprintf(stderr, "SPLATT: the impossible happened, "
"val_width > VAL_TYPEWIDTH.\n");
abort();
}
timer_stop(&timers[TIMER_IO]);
}
void read_binary_header(
FILE * fin,
bin_header * header)
{
fread(&(header->magic), sizeof(header->magic), 1, fin);
fread(&(header->idx_width), sizeof(header->idx_width), 1, fin);
fread(&(header->val_width), sizeof(header->val_width), 1, fin);
if(header->idx_width > SPLATT_IDX_TYPEWIDTH / 8) {
fprintf(stderr, "SPLATT: ERROR input has %zu-bit integers. "
"Build with SPLATT_IDX_TYPEWIDTH %zu\n",
header->idx_width * 8, header->idx_width * 8);
exit(EXIT_FAILURE);
}
if(header->val_width > SPLATT_VAL_TYPEWIDTH / 8) {
fprintf(stderr, "SPLATT: WARNING input has %zu-bit floating-point values. "
"Build with SPLATT_VAL_TYPEWIDTH %zu for full precision\n",
header->val_width * 8, header->val_width * 8);
}
}
void fill_binary_idx(
idx_t * const buffer,
idx_t const count,
bin_header const * const header,
FILE * fin)
{
if(header->idx_width == sizeof(splatt_idx_t)) {
fread(buffer, sizeof(idx_t), count, fin);
} else {
/* read in uint32_t in a buffered fashion */
idx_t const BUF_LEN = 1024*1024;
uint32_t * ubuf = splatt_malloc(BUF_LEN * sizeof(*ubuf));
for(idx_t n=0; n < count; n += BUF_LEN) {
idx_t const read_count = SS_MIN(BUF_LEN, count - n);
fread(ubuf, sizeof(*ubuf), read_count, fin);
#pragma omp parallel for schedule(static)
for(idx_t i=0; i < read_count; ++i) {
buffer[n + i] = ubuf[i];
}
}
splatt_free(ubuf);
}
}
void fill_binary_val(
val_t * const buffer,
idx_t const count,
bin_header const * const header,
FILE * fin)
{
if(header->val_width == sizeof(splatt_val_t)) {
fread(buffer, sizeof(val_t), count, fin);
} else {
/* read in float in a buffered fashion */
idx_t const BUF_LEN = 1024*1024;
/* select whichever SPLATT *is not* configured with. */
#if SPLATT_VAL_TYPEWIDTH == 64
float * ubuf = splatt_malloc(BUF_LEN * sizeof(*ubuf));
#else
double * ubuf = splatt_malloc(BUF_LEN * sizeof(*ubuf));
#endif
for(idx_t n=0; n < count; n += BUF_LEN) {
idx_t const read_count = SS_MIN(BUF_LEN, count - n);
fread(ubuf, sizeof(*ubuf), read_count, fin);
#pragma omp parallel for schedule(static)
for(idx_t i=0; i < read_count; ++i) {
buffer[n + i] = ubuf[i];
}
}
splatt_free(ubuf);
}
}
void hgraph_write(
hgraph_t const * const hg,
char const * const fname)
{
FILE * fout;
if(fname == NULL || strcmp(fname, "-") == 0) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
hgraph_write_file(hg, fout);
fclose(fout);
}
void hgraph_write_file(
hgraph_t const * const hg,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
/* print header */
fprintf(fout, "%"SPLATT_PF_IDX" %"SPLATT_PF_IDX, hg->nhedges, hg->nvtxs);
if(hg->vwts != NULL) {
if(hg->hewts != NULL) {
fprintf(fout, " 11");
} else {
fprintf(fout, " 10");
}
} else if(hg->hewts != NULL) {
fprintf(fout, " 1");
}
fprintf(fout, "\n");
/* print hyperedges */
for(idx_t e=0; e < hg->nhedges; ++e) {
if(hg->hewts != NULL) {
fprintf(fout, "%"SPLATT_PF_IDX" ", hg->hewts[e]);
}
for(idx_t v=hg->eptr[e]; v < hg->eptr[e+1]; ++v) {
fprintf(fout, "%"SPLATT_PF_IDX" ", hg->eind[v]+1);
}
fprintf(fout, "\n");
}
/* print vertex weights */
if(hg->vwts != NULL) {
for(idx_t v=0; v < hg->nvtxs; ++v) {
fprintf(fout, "%"SPLATT_PF_IDX"\n", hg->vwts[v]);
}
}
timer_stop(&timers[TIMER_IO]);
}
void graph_write_file(
splatt_graph const * const graph,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
/* print header */
fprintf(fout, "%"SPLATT_PF_IDX" %"SPLATT_PF_IDX" 0%d%d", graph->nvtxs,
graph->nedges/2, graph->vwgts != NULL, graph->ewgts != NULL);
/* handle multi-constraint partitioning */
if(graph->nvwgts > 1) {
fprintf(fout, " %"SPLATT_PF_IDX, graph->nvwgts);
}
fprintf(fout, "\n");
/* now write adj list */
for(vtx_t v=0; v < graph->nvtxs; ++v) {
/* vertex weights */
if(graph->vwgts != NULL) {
for(idx_t x=0; x < graph->nvwgts; ++x) {
fprintf(fout, "%"SPLATT_PF_IDX" ", graph->vwgts[x+(v*graph->nvwgts)]);
}
}
for(adj_t e=graph->eptr[v]; e < graph->eptr[v+1]; ++e) {
fprintf(fout, "%"SPLATT_PF_IDX" ", graph->eind[e] + 1);
/* edge weight */
if(graph->ewgts != NULL) {
fprintf(fout, "%"SPLATT_PF_IDX" ", graph->ewgts[e]);
}
}
fprintf(fout, "\n");
}
timer_stop(&timers[TIMER_IO]);
}
void spmat_write(
spmatrix_t const * const mat,
char const * const fname)
{
FILE * fout;
if(fname == NULL || strcmp(fname, "-") == 0) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
spmat_write_file(mat, fout);
if(fout != stdout) {
fclose(fout);
}
}
void spmat_write_file(
spmatrix_t const * const mat,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
/* write CSR matrix */
for(idx_t i=0; i < mat->I; ++i) {
for(idx_t j=mat->rowptr[i]; j < mat->rowptr[i+1]; ++j) {
fprintf(fout, "%"SPLATT_PF_IDX" %"SPLATT_PF_VAL" ", mat->colind[j], mat->vals[j]);
}
fprintf(fout, "\n");
}
timer_stop(&timers[TIMER_IO]);
}
void mat_write(
matrix_t const * const mat,
char const * const fname)
{
FILE * fout;
if(fname == NULL) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
mat_write_file(mat, fout);
if(fout != stdout) {
fclose(fout);
}
}
void mat_write_file(
matrix_t const * const mat,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
idx_t const I = mat->I;
idx_t const J = mat->J;
val_t const * const vals = mat->vals;
if(mat->rowmajor) {
for(idx_t i=0; i < mat->I; ++i) {
for(idx_t j=0; j < J; ++j) {
fprintf(fout, "%+0.8le ", vals[j + (i*J)]);
}
fprintf(fout, "\n");
}
} else {
for(idx_t i=0; i < mat->I; ++i) {
for(idx_t j=0; j < J; ++j) {
fprintf(fout, "%+0.8le ", vals[i + (j*I)]);
}
fprintf(fout, "\n");
}
}
timer_stop(&timers[TIMER_IO]);
}
void vec_write(
val_t const * const vec,
idx_t const len,
char const * const fname)
{
FILE * fout;
if(fname == NULL) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
vec_write_file(vec, len, fout);
if(fout != stdout) {
fclose(fout);
}
}
void vec_write_file(
val_t const * const vec,
idx_t const len,
FILE * fout)
{
timer_start(&timers[TIMER_IO]);
for(idx_t i=0; i < len; ++i) {
fprintf(fout, "%le\n", vec[i]);
}
timer_stop(&timers[TIMER_IO]);
}
idx_t * part_read(
char const * const ifname,
idx_t const nvtxs,
idx_t * nparts)
{
FILE * pfile;
if((pfile = fopen(ifname, "r")) == NULL) {
fprintf(stderr, "SPLATT ERROR: unable to open '%s'\n", ifname);
return NULL;
}
*nparts = 0;
idx_t ret;
idx_t * arr = (idx_t *) splatt_malloc(nvtxs * sizeof(idx_t));
for(idx_t i=0; i < nvtxs; ++i) {
if((ret = fscanf(pfile, "%"SPLATT_PF_IDX, &(arr[i]))) == 0) {
fprintf(stderr, "SPLATT ERROR: not enough elements in '%s'\n", ifname);
free(arr);
return NULL;
}
if(arr[i] > *nparts) {
*nparts = arr[i];
}
}
fclose(pfile);
/* increment to adjust for 0-indexing of partition ids */
*nparts += 1;
return arr;
}
/******************************************************************************
* PERMUTATION FUNCTIONS
*****************************************************************************/
void perm_write(
idx_t * perm,
idx_t const dim,
char const * const fname)
{
FILE * fout;
if(fname == NULL) {
fout = stdout;
} else {
if((fout = fopen(fname,"w")) == NULL) {
fprintf(stderr, "SPLATT ERROR: failed to open '%s'\n.", fname);
return;
}
}
perm_write_file(perm, dim, fout);
if(fname != NULL) {
fclose(fout);
}
}
void perm_write_file(
idx_t * perm,
idx_t const dim,
FILE * fout)
{
for(idx_t i=0; i < dim; ++i) {
fprintf(fout, "%"SPLATT_PF_IDX"\n", perm[i]);
}
}
|
GB_unop__identity_uint32_uint8.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_uint32_uint8)
// op(A') function: GB (_unop_tran__identity_uint32_uint8)
// C type: uint32_t
// A type: uint8_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
uint32_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) \
uint32_t z = (uint32_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint32_t z = (uint32_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_UINT32 || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint32_uint8)
(
uint32_t *Cx, // Cx and Ax may be aliased
const uint8_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint8_t aij = Ax [p] ;
uint32_t z = (uint32_t) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint8_t aij = Ax [p] ;
uint32_t z = (uint32_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_uint32_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unaryop__minv_int16_uint32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_int16_uint32
// op(A') function: GB_tran__minv_int16_uint32
// C type: int16_t
// A type: uint32_t
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = GB_IMINV_SIGNED (aij, 16)
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 16) ;
// casting
#define GB_CASTING(z, aij) \
int16_t z = (int16_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_INT16 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_int16_uint32
(
int16_t *Cx, // Cx and Ax may be aliased
uint32_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_int16_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
core_ztrsm.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> c d s
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "core_lapack.h"
/***************************************************************************//**
*
* @ingroup core_trsm
*
* Solves one of the matrix equations
*
* \f[ op( A )\times X = \alpha B, \f] or
* \f[ X \times op( A ) = \alpha B, \f]
*
* where op( A ) is one of:
* \f[ op( A ) = A, \f]
* \f[ op( A ) = A^T, \f]
* \f[ op( A ) = A^H, \f]
*
* alpha is a scalar, X and B are m-by-n matrices, and
* A is a unit or non-unit, upper or lower triangular matrix.
* The matrix X overwrites B.
*
*******************************************************************************
*
* @param[in] side
* - PlasmaLeft: op(A)*X = B,
* - PlasmaRight: X*op(A) = B.
*
* @param[in] uplo
* - PlasmaUpper: A is upper triangular,
* - PlasmaLower: A is lower triangular.
*
* @param[in] transa
* - PlasmaNoTrans: A is not transposed,
* - PlasmaTrans: A is transposed,
* - PlasmaConjTrans: A is conjugate transposed.
*
* @param[in] diag
* - PlasmaNonUnit: A has non-unit diagonal,
* - PlasmaUnit: A has unit diagonal.
*
* @param[in] m
* The number of rows of the matrix B. m >= 0.
*
* @param[in] n
* The number of columns of the matrix B. n >= 0.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] A
* The lda-by-ka triangular matrix,
* where ka = m if side = PlasmaLeft,
* and ka = n if side = PlasmaRight.
* If uplo = PlasmaUpper, the leading k-by-k upper triangular part
* of the array A contains the upper triangular matrix, and the
* strictly lower triangular part of A is not referenced.
* If uplo = PlasmaLower, the leading k-by-k lower triangular part
* of the array A contains the lower triangular matrix, and the
* strictly upper triangular part of A is not referenced.
* If diag = PlasmaUnit, the diagonal elements of A are also not
* referenced and are assumed to be 1.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,k).
*
* @param[in,out] B
* On entry, the ldb-by-n right hand side matrix B.
* On exit, if return value = 0, the ldb-by-n solution matrix X.
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= max(1,m).
*
******************************************************************************/
__attribute__((weak))
void plasma_core_ztrsm(plasma_enum_t side, plasma_enum_t uplo,
plasma_enum_t transa, plasma_enum_t diag,
int m, int n,
plasma_complex64_t alpha, const plasma_complex64_t *A, int lda,
plasma_complex64_t *B, int ldb)
{
cblas_ztrsm(CblasColMajor,
(CBLAS_SIDE)side, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)transa, (CBLAS_DIAG)diag,
m, n,
CBLAS_SADDR(alpha), A, lda,
B, ldb);
}
/******************************************************************************/
void plasma_core_omp_ztrsm(
plasma_enum_t side, plasma_enum_t uplo,
plasma_enum_t transa, plasma_enum_t diag,
int m, int n,
plasma_complex64_t alpha, const plasma_complex64_t *A, int lda,
plasma_complex64_t *B, int ldb,
plasma_sequence_t *sequence, plasma_request_t *request)
{
int ak;
if (side == PlasmaLeft)
ak = m;
else
ak = n;
#pragma omp task depend(in:A[0:lda*ak]) \
depend(inout:B[0:ldb*n])
{
if (sequence->status == PlasmaSuccess)
plasma_core_ztrsm(side, uplo,
transa, diag,
m, n,
alpha, A, lda,
B, ldb);
}
}
|
GB_unaryop__abs_bool_int16.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_bool_int16
// op(A') function: GB_tran__abs_bool_int16
// C type: bool
// A type: int16_t
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
bool z = (bool) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_BOOL || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_bool_int16
(
bool *restrict Cx,
const int16_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_bool_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
util.c | #include "baryakhtar_clib.h"
void compute_laplace_m(double *m, double *field, double *Ms, double dx,
double dy, double dz, int nx, int ny, int nz) {
int nyz = ny * nz;
int n1 = nx * nyz, n2 = 2 * n1;
double ax = 1.0 / (dx * dx), ay = 1.0 / (dy * dy), az = 1.0 / (dz * dz);
#pragma omp parallel for
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
int id = 0;
int index = nyz * i + nz * j + k;
double fx = 0, fy = 0, fz = 0;
if (Ms[index] == 0.0) {
field[index] = 0;
field[index + n1] = 0;
field[index + n2] = 0;
continue;
}
if (k > 0) {
id = index - 1;
if (Ms[id] > 0) {
fx += az * (m[id] - m[index]);
fy += az * (m[id + n1] - m[index + n1]);
fz += az * (m[id + n2] - m[index + n2]);
}
}
if (j > 0) {
id = index - nz;
if (Ms[id] > 0) {
fx += ay * (m[id] - m[index]);
fy += ay * (m[id + n1] - m[index + n1]);
fz += ay * (m[id + n2] - m[index + n2]);
}
}
if (i > 0) {
id = index - nyz;
if (Ms[id] > 0) {
fx += ax * (m[id] - m[index]);
fy += ax * (m[id + n1] - m[index + n1]);
fz += ax * (m[id + n2] - m[index + n2]);
}
}
if (i < nx - 1) {
id = index + nyz;
if (Ms[id] > 0) {
fx += ax * (m[id] - m[index]);
fy += ax * (m[id + n1] - m[index + n1]);
fz += ax * (m[id + n2] - m[index + n2]);
}
}
if (j < ny - 1) {
id = index + nz;
if (Ms[id] > 0) {
fx += ay * (m[id] - m[index]);
fy += ay * (m[id + n1] - m[index + n1]);
fz += ay * (m[id + n2] - m[index + n2]);
}
}
if (k < nz - 1) {
id = index + 1;
if (Ms[id] > 0) {
fx += az * (m[id] - m[index]);
fy += az * (m[id + n1] - m[index + n1]);
fz += az * (m[id + n2] - m[index + n2]);
}
}
field[index] = fx;
field[index + n1] = fy;
field[index + n2] = fz;
}
}
}
}
void compute_relaxation_field_c(double *m, double *field, double *Ms,
double chi_inv, int n) {
#pragma omp parallel for
for (int i = 0; i < n; i++) {
int j = i + n;
int k = j + n;
double relax = Ms[i] * chi_inv / 2.0;
double mm = m[i] * m[i] + m[j] * m[j] + m[k] * m[k];
field[i] = relax * (1 - mm) * m[i];
field[j] = relax * (1 - mm) * m[j];
field[k] = relax * (1 - mm) * m[k];
}
}
void compute_perp_field_c(double *m, double *field, double *field_p, int n) {
#pragma omp parallel for
for (int i = 0; i < n; i++) {
int j = i + n;
int k = j + n;
double mm = m[i] * m[i] + m[j] * m[j] + m[k] * m[k];
double hm = field[i] * m[i] + field[j] * m[j] + field[k] * m[k];
field_p[i] = field[i] - hm * m[i] / mm;
field_p[j] = field[j] - hm * m[j] / mm;
field_p[k] = field[k] - hm * m[k] / mm;
}
}
|
GB_unop__identity_int64_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 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_int64_fc32)
// op(A') function: GB (_unop_tran__identity_int64_fc32)
// C type: int64_t
// A type: GxB_FC32_t
// cast: int64_t cij = GB_cast_to_int64_t ((double) crealf (aij))
// unaryop: cij = aij
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
int64_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 = x ;
// casting
#define GB_CAST(z, aij) \
int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int64_fc32)
(
int64_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] ;
int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
int64_t z = GB_cast_to_int64_t ((double) crealf (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_int64_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
|
VerletClusterLists.h | /**
* @file VerletClusterLists.h
* @author nguyen
* @date 14.10.18
*/
#pragma once
#include <cmath>
#include "autopas/cells/FullParticleCell.h"
#include "autopas/containers/CompatibleTraversals.h"
#include "autopas/containers/ParticleContainer.h"
#include "autopas/containers/verletClusterLists/VerletClusterMaths.h"
#include "autopas/containers/verletClusterLists/traversals/VerletClustersTraversalInterface.h"
#include "autopas/iterators/ParticleIterator.h"
#include "autopas/utils/ArrayMath.h"
#include "autopas/utils/inBox.h"
namespace autopas {
/**
* Particles are divided into clusters.
* The VerletClusterLists class uses neighborhood lists for each cluster
* to calculate pairwise interactions of particles.
* It is optimized for a constant, i.e. particle independent, cutoff radius of
* the interaction.
* @tparam Particle
*/
template <class Particle>
class VerletClusterLists : public ParticleContainer<FullParticleCell<Particle>> {
/**
* the index type to access the particle cells
*/
using index_t = VerletClusterMaths::index_t;
public:
/**
* Constructor of the VerletClusterLists class.
* The neighbor lists are build using a estimated density.
* The box is divided into cuboids with roughly the
* same side length.
* @param boxMin the lower corner of the domain
* @param boxMax the upper corner of the domain
* @param cutoff the cutoff radius of the interaction
* @param skin the skin radius
* @param clusterSize size of clusters
*/
VerletClusterLists(const std::array<double, 3> boxMin, const std::array<double, 3> boxMax, double cutoff,
double skin = 0, int clusterSize = 4)
: ParticleContainer<FullParticleCell<Particle>>(boxMin, boxMax, cutoff, skin),
_clusterSize(clusterSize),
_numClusters(0),
_boxMin(boxMin),
_boxMax(boxMax),
_skin(skin),
_cutoff(cutoff),
_neighborListIsNewton3(false),
_interactionLengthSqr((cutoff + skin) * (cutoff + skin)) {
rebuild(false);
}
ContainerOption getContainerType() const override { return ContainerOption::verletClusterLists; }
void iteratePairwise(TraversalInterface *traversal) override {
AutoPasLog(debug, "Using traversal {}.", traversal->getTraversalType().to_string());
auto *traversalInterface = dynamic_cast<VerletClustersTraversalInterface<Particle> *>(traversal);
if (traversalInterface) {
traversalInterface->setClusterLists(*this);
} else {
autopas::utils::ExceptionHandler::exception(
"Trying to use a traversal of wrong type in VerletClusterLists::iteratePairwise. TraversalID: {}",
traversal->getTraversalType());
}
traversal->initTraversal();
traversal->traverseParticlePairs();
traversal->endTraversal();
}
/**
* @copydoc VerletLists::addParticle()
*/
void addParticle(const Particle &p) override {
// add particle somewhere, because lists will be rebuild anyways
this->_cells[0].addParticle(p);
}
/**
* @copydoc VerletLists::addHaloParticle()
*/
void addHaloParticle(const Particle &haloParticle) override {
autopas::utils::ExceptionHandler::exception("VerletClusterLists.addHaloParticle not yet implemented.");
}
/**
* @copydoc autopas::ParticleContainerInterface::updateHaloParticle()
*/
bool updateHaloParticle(const Particle &haloParticle) override { throw std::runtime_error("not yet implemented"); }
/**
* @copydoc VerletLists::deleteHaloParticles
*/
void deleteHaloParticles() override {
// quick and dirty: iterate over all particles and delete halo particles
// @todo: make this proper
for (auto iter = this->begin(IteratorBehavior::haloOnly); iter.isValid(); ++iter) {
if (not iter->isOwned()) {
internal::deleteParticle(iter);
}
}
}
/**
* @copydoc VerletLists::updateContainer()
*/
AUTOPAS_WARN_UNUSED_RESULT
std::vector<Particle> updateContainer() override {
AutoPasLog(debug, "updating container");
// first delete all particles
this->deleteHaloParticles();
// next find invalid particles
std::vector<Particle> invalidParticles;
/// @todo: parallelize
for (auto iter = this->begin(IteratorBehavior::ownedOnly); iter.isValid(); ++iter) {
if (not utils::inBox(iter->getR(), _boxMin, _boxMax)) {
invalidParticles.push_back(*iter);
internal::deleteParticle(iter);
}
}
return invalidParticles;
}
bool isContainerUpdateNeeded() const override {
autopas::utils::ExceptionHandler::exception("VerletClusterLists.isContainerUpdateNeeded not yet implemented");
return false;
}
TraversalSelectorInfo getTraversalSelectorInfo() const override {
return TraversalSelectorInfo(_cellsPerDim, this->getInteractionLength(), {0., 0., 0.}, _clusterSize);
}
ParticleIteratorWrapper<Particle, true> begin(IteratorBehavior behavior = IteratorBehavior::haloAndOwned) override {
return ParticleIteratorWrapper<Particle, true>(
new internal::ParticleIterator<Particle, FullParticleCell<Particle>, true>(&this->_cells));
}
ParticleIteratorWrapper<Particle, false> begin(
IteratorBehavior behavior = IteratorBehavior::haloAndOwned) const override {
return ParticleIteratorWrapper<Particle, false>(
new internal::ParticleIterator<Particle, FullParticleCell<Particle>, false>(&this->_cells));
}
ParticleIteratorWrapper<Particle, true> getRegionIterator(
const std::array<double, 3> &lowerCorner, const std::array<double, 3> &higherCorner,
IteratorBehavior behavior = IteratorBehavior::haloAndOwned) override {
// @todo implement this if bounding boxes are here
autopas::utils::ExceptionHandler::exception("VerletClusterLists.getRegionIterator not yet implemented.");
return ParticleIteratorWrapper<Particle, true>();
}
ParticleIteratorWrapper<Particle, false> getRegionIterator(
const std::array<double, 3> &lowerCorner, const std::array<double, 3> &higherCorner,
IteratorBehavior behavior = IteratorBehavior::haloAndOwned) const override {
// @todo implement this if bounding boxes are here
autopas::utils::ExceptionHandler::exception("VerletClusterLists.getRegionIterator not yet implemented.");
return ParticleIteratorWrapper<Particle, false>();
}
void rebuildNeighborLists(TraversalInterface *traversal) override { rebuild(traversal->getUseNewton3()); }
/**
* Helper method to iterate over all clusters.
* @tparam LoopBody The type of the lambda to execute for all clusters.
* @tparam inParallel If the iteration should be executed in parallel or sequential. See traverseClustersParallel()
* for thread safety.
* @param loopBody The lambda to execute for all clusters. Parameters given are Particle* clusterStart, int
* clusterSize, std::vector<Particle*> clusterNeighborList.
*/
template <bool inParallel, class LoopBody>
void traverseClusters(LoopBody &&loopBody) {
if (inParallel) {
traverseClustersParallel<LoopBody>(std::forward<LoopBody>(loopBody));
} else {
traverseClustersSequential<LoopBody>(std::forward<LoopBody>(loopBody));
}
}
/**
* Returns the ClusterIndexMap for usage in the traversals of this container.
* @return the ClusterIndexMap.
*/
const auto &getClusterIndexMap() const { return _clusterIndexMap; }
/**
* Returns the number of clusters in this container.
* @return The number of clusters in this container.
*/
auto getNumClusters() const { return _numClusters; }
/**
* Returns the neighbor lists of this container.
* @return the neighbor lists of this container.
*/
const auto &getNeighborLists() const { return _neighborLists; }
/**
* Returns the grid side length of the grids in the container.
* @return the grid side length of the grids in the container.
*/
auto getGridSideLength() const { return _gridSideLength; }
/**
* Returns the number of grids per dimension on the container.
* @return the number of grids per dimension on the container.
*/
auto getCellsPerDimension() const { return _cellsPerDim; }
/**
* Returns the 2D grid for the XY-plane of this container that defines the cluster towers.
* @return the grids of this container for usage in traversals.
*/
auto &getGrids() { return this->_cells; }
/**
* Returns the number of particles in each cluster.
* @return the number of particles in each cluster.
*/
auto getClusterSize() const { return _clusterSize; }
protected:
/**
* Helper method to sequentially iterate over all clusters.
* @tparam LoopBody The type of the lambda to execute for all clusters.
* @param loopBody The lambda to execute for all clusters. Parameters given are Particle* clusterStart, index_t
* clusterSize, std::vector<Particle*> clusterNeighborList.
*/
template <class LoopBody>
void traverseClustersSequential(LoopBody &&loopBody) {
for (index_t x = 0; x < _cellsPerDim[0]; x++) {
for (index_t y = 0; y < _cellsPerDim[1]; y++) {
index_t index = VerletClusterMaths::index1D(x, y, _cellsPerDim);
auto &grid = this->_cells[index];
auto &gridNeighborList = _neighborLists[index];
const index_t numClustersInGrid = grid.numParticles() / _clusterSize;
for (index_t clusterInGrid = 0; clusterInGrid < numClustersInGrid; clusterInGrid++) {
Particle *iClusterStart = &grid[clusterInGrid * _clusterSize];
auto &clusterNeighborList = gridNeighborList[clusterInGrid];
loopBody(iClusterStart, _clusterSize, clusterNeighborList);
}
}
}
}
/**
* Helper method to iterate over all clusters in parallel.
*
* It is always safe to modify the particles in the cluster that is passed to the given loop body. However, when
* modifying particles from other clusters, the caller has to make sure that no data races occur. Particles must not
* be added or removed during the traversal.
* @tparam LoopBody The type of the lambda to execute for all clusters.
* @param loopBody The lambda to execute for all clusters. Parameters given are Particle* clusterStart, index_t
* clusterSize, std::vector<Particle*> clusterNeighborList.
*/
template <class LoopBody>
void traverseClustersParallel(LoopBody &&loopBody) {
const index_t endX = _cellsPerDim[0];
const index_t endY = _cellsPerDim[1];
#if defined(AUTOPAS_OPENMP)
// @todo: find sensible chunksize
#pragma omp parallel for schedule(dynamic) collapse(2)
#endif
for (index_t x = 0; x < endX; x++) {
for (index_t y = 0; y < endY; y++) {
index_t index = VerletClusterMaths::index1D(x, y, _cellsPerDim);
auto &grid = this->_cells[index];
auto &gridNeighborList = _neighborLists[index];
const index_t numClustersInGrid = grid.numParticles() / _clusterSize;
for (index_t clusterInGrid = 0; clusterInGrid < numClustersInGrid; clusterInGrid++) {
Particle *iClusterStart = &grid[clusterInGrid * _clusterSize];
auto &clusterNeighborList = gridNeighborList[clusterInGrid];
loopBody(iClusterStart, _clusterSize, clusterNeighborList);
}
}
}
}
/**
* Recalculate grids and clusters, build verlet lists and pad clusters.
* @param useNewton3 If the everything should be build using newton 3 or not.
*/
void rebuild(bool useNewton3) {
std::vector<Particle> invalidParticles = collectParticlesAndClearClusters();
auto boxSize = utils::ArrayMath::sub(_boxMax, _boxMin);
_gridSideLength = estimateOptimalGridSideLength(invalidParticles.size(), boxSize);
_gridSideLengthReciprocal = 1 / _gridSideLength;
_cellsPerDim = calculateCellsPerDim(boxSize);
// _cellsPerDim[2] is always 1
index_t numCells = _cellsPerDim[0] * _cellsPerDim[1];
// resize to number of grids
this->_cells.resize(numCells);
_neighborLists.resize(numCells);
sortParticlesIntoClusters(invalidParticles);
// sort by last dimension and reserve space for dummy particles
for (auto &cluster : this->_cells) {
cluster.sortByDim(2);
size_t size = cluster.numParticles();
size_t rest = size % _clusterSize;
if (rest > 0) cluster.reserve(size + (_clusterSize - rest));
}
clearNeighborLists();
_numClusters = buildClusterIndexMap();
updateVerletLists(useNewton3);
// fill last cluster with dummy particles, such that each cluster is a multiple of _clusterSize
padClusters();
}
/**
* Takes all particles from all clusters and returns them. Clusters are cleared.
* @return All particles in the container.
*/
std::vector<Particle> collectParticlesAndClearClusters() {
std::vector<Particle> invalidParticles;
for (auto &cluster : this->_cells) {
for (auto it = cluster.begin(); it.isValid(); ++it) {
invalidParticles.push_back(*it);
}
cluster.clear();
}
return invalidParticles;
}
/**
* Estimates the optimal grid side length.
* @param numParticles The number of particles in the container.
* @param boxSize The size of the domain.
* @return an estimated optimal grid side length.
*/
virtual double estimateOptimalGridSideLength(size_t numParticles, std::array<double, 3> boxSize) const {
double volume = boxSize[0] * boxSize[1] * boxSize[2];
if (numParticles > 0) {
// estimate particle density
double density = numParticles / volume;
return std::cbrt(_clusterSize / density);
} else {
return std::max(boxSize[0], boxSize[1]);
}
}
/**
* Calculates the cells per dimension in the container using the _gridSideLengthReciprocal.
* @param boxSize the size of the domain.
* @return the cells per dimension in the container.
*/
std::array<index_t, 3> calculateCellsPerDim(std::array<double, 3> boxSize) const {
std::array<index_t, 3> cellsPerDim{};
for (int d = 0; d < 2; d++) {
cellsPerDim[d] = static_cast<index_t>(std::ceil(boxSize[d] * _gridSideLengthReciprocal));
// at least one cell
cellsPerDim[d] = std::max(cellsPerDim[d], 1ul);
}
cellsPerDim[2] = 1ul;
return cellsPerDim;
}
/**
* Sorts all passed particles in the appropriate clusters.
* @param particles The particles to sort in the clusters.
*/
void sortParticlesIntoClusters(std::vector<Particle> &particles) {
for (auto &particle : particles) {
if (utils::inBox(particle.getR(), _boxMin, _boxMax)) {
auto index = get1DIndexOfPosition(particle.getR());
this->_cells[index].addParticle(particle);
}
}
}
/**
* Clears all neighbor lists.
*/
void clearNeighborLists() {
for (auto &verlet : _neighborLists) {
verlet.clear();
}
}
/**
* Update the verlet lists.
*
* @param useNewton3 If newton 3 should be used to build the neighbor lists or not. If true, only saves neighbor
* clusters that have a higher index that the current cluster. (@see buildClusterIndexMap())
*/
void updateVerletLists(bool useNewton3) {
_neighborListIsNewton3 = useNewton3;
const int boxRange = static_cast<int>(std::ceil((_cutoff + _skin) * _gridSideLengthReciprocal));
const int gridMaxX = _cellsPerDim[0] - 1;
const int gridMaxY = _cellsPerDim[1] - 1;
// for all grids
for (int yi = 0; yi <= gridMaxY; yi++) {
for (int xi = 0; xi <= gridMaxX; xi++) {
auto &iGrid = this->_cells[VerletClusterMaths::index1D(xi, yi, _cellsPerDim)];
// calculate number of full clusters and rest
index_t iSize = iGrid.numParticles() / _clusterSize;
int iRest = iGrid.numParticles() % _clusterSize;
const int minX = std::max(xi - boxRange, 0);
const int minY = std::max(yi - boxRange, 0);
const int maxX = std::min(xi + boxRange, gridMaxX);
const int maxY = std::min(yi + boxRange, gridMaxY);
auto &iNeighbors = _neighborLists[VerletClusterMaths::index1D(xi, yi, _cellsPerDim)];
if (iRest > 0)
iNeighbors.resize(iSize + 1);
else
iNeighbors.resize(iSize);
addClustersOfNeighborGridsAsNeighborsIfInRange(iGrid, iSize, iRest, iNeighbors, minX, maxX, minY, maxY, xi, yi);
}
}
}
/**
* Iterates over neighbor grids of the i-th grid and adds all clusters in them that are within the cutoff radius to
* the neighbor list of the clusters in the i-th grid.
* @param iGrid The i-th grid.
* @param iSize The number of full clusters in the i-th grid.
* @param iRest If the last cluster is not full: The number of particles in the last cluster. 0 otherwise.
* @param iNeighbors The neighbor list of the i-th grid.
* @param minX
* @param maxX
* @param minY
* @param maxY
* @param xi The x-index of the i-th grid.
* @param yi the y-index of the i-th grid.
*/
void addClustersOfNeighborGridsAsNeighborsIfInRange(FullParticleCell<Particle> &iGrid, index_t iSize, int iRest,
std::vector<std::vector<Particle *>> &iNeighbors, const int minX,
const int maxX, const int minY, const int maxY, const int xi,
const int yi) {
// for all neighbor grids
for (int yj = minY; yj <= maxY; yj++) {
double distY = std::max(0, std::abs(yi - yj) - 1) * _gridSideLength;
for (int xj = minX; xj <= maxX; xj++) {
double distX = std::max(0, std::abs(xi - xj) - 1) * _gridSideLength;
// calculate distance in xy-plane and skip if already longer than cutoff
double distXYsqr = distX * distX + distY * distY;
if (distXYsqr <= _interactionLengthSqr) {
auto &jGrid = this->_cells[VerletClusterMaths::index1D(xj, yj, _cellsPerDim)];
// calculate number of full clusters and rest
const index_t jSize = jGrid.numParticles() / _clusterSize;
const int jRest = jGrid.numParticles() % _clusterSize;
// for all clusters in the i-th grid
for (index_t zi = 0; zi < iSize; zi++) {
addAllJClustersAsNeighborIfInRange(iGrid, zi, _clusterSize, iNeighbors, jGrid, jSize, jRest, distXYsqr);
}
// special case: last cluster of iGrid not full
if (iRest > 0) {
addAllJClustersAsNeighborIfInRange(iGrid, iSize, iRest, iNeighbors, jGrid, jSize, jRest, distXYsqr);
}
}
}
}
}
/**
* Adds all clusters in jGrid that are within the cutoff radius to the neighbor list of the given cluster in iGrid
* (iClusterIndex).
* @param iGrid The i-th grid.
* @param iClusterIndex The index of the cluster to work on in the i-th grid.
* @param iClusterSize The size of th cluster with index iClusterIndex in the i-th grid.
* @param iNeighbors The neighbor list of the i-th grid.
* @param jGrid The j-th grid.
* @param jSize The number of full clusters in the j-th grid.
* @param jRest If the last cluster is not full: The number of particles in the last cluster. 0 otherwise.
* @param distXYsqr The distance between the i-th grid and the j-th grid in the xy-plane.
*/
void addAllJClustersAsNeighborIfInRange(FullParticleCell<Particle> &iGrid, index_t iClusterIndex, int iClusterSize,
std::vector<std::vector<Particle *>> &iNeighbors,
FullParticleCell<Particle> &jGrid, index_t jSize, int jRest,
double distXYsqr) {
// bbox in z of iGrid
double iBBoxBot = iGrid[iClusterIndex * _clusterSize].getR()[2];
double iBBoxTop = iGrid[iClusterIndex * _clusterSize + iClusterSize - 1].getR()[2];
auto &iClusterNeighborList = iNeighbors[iClusterIndex];
Particle *iClusterStart = &iGrid[iClusterIndex * _clusterSize];
// iterate over full clusters of j-th grid.
for (index_t jClusterIndex = 0; jClusterIndex < jSize; jClusterIndex++) {
Particle *jClusterStart = &jGrid[jClusterIndex * _clusterSize];
// If newton 3 is used, only add clusters as neighbors that have a equal or higher index. Skip otherwise.
if (_neighborListIsNewton3 and _clusterIndexMap.at(iClusterStart) > _clusterIndexMap.at(jClusterStart)) continue;
addJClusterAsNeighborIfInRange(jGrid, jClusterStart, _clusterSize, iClusterNeighborList, distXYsqr, iBBoxBot,
iBBoxTop);
}
// special case: last cluster not full
if (jRest > 0) {
Particle *jClusterStart = &jGrid[jSize * _clusterSize];
// If newton 3 is used, only add clusters as neighbors that have a equal or higher index. Skip otherwise.
if (not(_neighborListIsNewton3 and _clusterIndexMap.at(iClusterStart) > _clusterIndexMap.at(jClusterStart))) {
addJClusterAsNeighborIfInRange(jGrid, jClusterStart, jRest, iClusterNeighborList, distXYsqr, iBBoxBot,
iBBoxTop);
}
}
}
/**
* Adds the given cluster in jGrid to the given neighbor list (iClusterNeighborList), if it is within the cutoff
* radius.
* @param jGrid The j-th grid.
* @param jClusterStart A pointer to the start of the cluster to work on in the j-th grid.
* @param jClusterSize The size of the cluster to work on in the j-th grid.
* @param iClusterNeighborList The neighbor list of the cluster in the i-th grid to fill the neighbors for.
* @param distXYsqr The distance between the i-th grid and the j-th grid in the xy-plane.
* @param iBBoxBot The bottom z-coordinate of the cluster in the i-th grid.
* @param iBBoxTop The top z-coordinate of the cluster in the i-th grid.
*/
void addJClusterAsNeighborIfInRange(FullParticleCell<Particle> &jGrid, Particle *jClusterStart, int jClusterSize,
std::vector<Particle *> &iClusterNeighborList, double distXYsqr, double iBBoxBot,
double iBBoxTop) {
// bbox in z of jGrid
double jBBoxBot = jClusterStart->getR()[2];
double jBBoxTop = (jClusterStart + (jClusterSize - 1))->getR()[2];
double distZ = bboxDistance(iBBoxBot, iBBoxTop, jBBoxBot, jBBoxTop);
if (distXYsqr + distZ * distZ <= _interactionLengthSqr) {
iClusterNeighborList.push_back(jClusterStart);
}
}
/**
* Pad clusters with dummy particles
* until each cluster is a multiple of _clusterSize.
* Useful for SIMD vectorization.
*/
void padClusters() {
for (index_t x = 0; x < _cellsPerDim[0]; x++) {
for (index_t y = 0; y < _cellsPerDim[1]; y++) {
auto &grid = this->_cells[VerletClusterMaths::index1D(x, y, _cellsPerDim)];
index_t rest = grid.numParticles() % _clusterSize;
if (rest > 0) {
for (int i = rest; i < _clusterSize; i++) {
Particle p = Particle();
p.setR({2 * x * _cutoff, 2 * y * _cutoff, 2 * _boxMax[2] + 2 * i * _cutoff});
grid.addParticle(p);
}
}
}
}
}
/**
* Calculates the distance of two bounding boxes in one dimension.
* @param min1 minimum coordinate of first bbox in tested dimension
* @param max1 maximum coordinate of first bbox in tested dimension
* @param min2 minimum coordinate of second bbox in tested dimension
* @param max2 maximum coordinate of second bbox in tested dimension
* @return distance
*/
inline double bboxDistance(const double min1, const double max1, const double min2, const double max2) const {
if (max1 < min2) {
return min2 - max1;
} else if (min1 > max2) {
return min1 - max2;
} else {
return 0;
}
}
/**
* Gets the 1d grid index containing a particle in given position.
* @param pos the position of the particle
* @return the index of the grid
*/
inline index_t get1DIndexOfPosition(const std::array<double, 3> &pos) const {
std::array<index_t, 2> cellIndex{};
for (int dim = 0; dim < 2; dim++) {
const long int value = (static_cast<long int>(floor((pos[dim] - _boxMin[dim]) * _gridSideLengthReciprocal))) + 1l;
const index_t nonnegativeValue = static_cast<index_t>(std::max(value, 0l));
const index_t nonLargerValue = std::min(nonnegativeValue, _cellsPerDim[dim] - 1);
cellIndex[dim] = nonLargerValue;
/// @todo this is a sanity check to prevent doubling of particles, but
/// could be done better! e.g. by border and flag manager
if (pos[dim] >= _boxMax[dim]) {
cellIndex[dim] = _cellsPerDim[dim] - 1;
} else if (pos[dim] < _boxMin[dim]) {
cellIndex[dim] = 0;
}
}
return VerletClusterMaths::index1D(cellIndex[0], cellIndex[1], _cellsPerDim);
}
/**
* Builds the _clusterIndexMap to be up to date with _cells.
*
* Every cluster gets an index assigned. The indices are given in a way so that the VerletClustersColoringTraversal
* works as easy as possible with newton 3. The newton 3 neighbor list just has to only save neighbors with a higher
* index, and there will be no data races.
*
* For each cluster now holds (with x-axis as left <=> right, y-axis <=> as top <=> bottom):
* - The indices of all clusters of the three color cells above and the color cell to the left are lower.
* - The indices of all clusters of the three color cells below and the color cell to the right are higher.
* - For all grids of the same color cell holds:
* - The indices of all clusters of the three grids above and the grids to the left are lower.
* - The indices of all clusters of the three grids below and the grids to the right are higher.
* - For all clusters in the same grid holds:
* - The indices of all clusters with a lower z-coordinate than the current cluster are lower.
* - The indices of all clusters with a higher z-coordinate than the current cluster are higher.
*
* @return The number of clusters in the container.
*/
index_t buildClusterIndexMap() {
index_t nextFreeMapIndex = 0;
int gridsPerColoringCell = static_cast<int>(std::ceil((_cutoff + _skin) / _gridSideLength));
std::array<unsigned long, 3> coloringCellsPerDim{};
for (int i = 0; i < 3; i++) {
coloringCellsPerDim[i] =
static_cast<unsigned long>(std::ceil(_cellsPerDim[i] / static_cast<double>(gridsPerColoringCell)));
}
for (unsigned long yColorCell = 0; yColorCell < coloringCellsPerDim[1]; yColorCell++) {
for (unsigned long xColorCell = 0; xColorCell < coloringCellsPerDim[0]; xColorCell++) {
nextFreeMapIndex = indexColorCell(xColorCell, yColorCell, gridsPerColoringCell, nextFreeMapIndex);
}
}
return nextFreeMapIndex;
}
private:
/**
* Indexes all clusters of one color cell (inserts value into _clusterIndexMap) starting with currentMapIndex.
*
* The scheme follows the documentation from buildClusterIndexMap().
* @param xColorCell The x coordinate of the color cell.
* @param yColorCell The y coordinate of the color cell.
* @param gridsPerColoringCell The number of grids in x and y dimension of this color cell.
* @param currentMapIndex The first index to use.
* @return The next available index after this cell.
*/
index_t indexColorCell(unsigned long xColorCell, unsigned long yColorCell, int gridsPerColoringCell,
index_t currentMapIndex) {
for (int yInner = 0; yInner < gridsPerColoringCell; yInner++) {
for (int xInner = 0; xInner < gridsPerColoringCell; xInner++) {
unsigned long y = yColorCell * gridsPerColoringCell + yInner;
unsigned long x = xColorCell * gridsPerColoringCell + xInner;
// Not every coloring cell has to have gridsPerColoringCell grids in every direction.
if (x >= _cellsPerDim[0] or y >= _cellsPerDim[1]) {
continue;
}
unsigned long gridIndex1D = VerletClusterMaths::index1D(x, y, _cellsPerDim);
auto ¤tGrid = this->_cells[gridIndex1D];
auto numClusters = currentGrid.numParticles() / _clusterSize;
int rest = currentGrid.numParticles() % _clusterSize;
if (rest > 0) numClusters++;
for (unsigned long currentCluster = 0; currentCluster < numClusters; currentCluster++) {
Particle *clusterStart = ¤tGrid[currentCluster * _clusterSize];
_clusterIndexMap[clusterStart] = currentMapIndex++;
}
}
}
return currentMapIndex;
}
private:
/**
* Neighbors of clusters for each grid. If it uses newton 3 is saved in _neighborListIsNewton3.
* If it uses newton 3: Only the neighbor clusters that have a higher index are saved. (@see _clusterIndexMap)
*/
std::vector<std::vector<std::vector<Particle *>>> _neighborLists;
/**
* The number of particles in a full cluster.
*/
int _clusterSize;
/**
* The number of clusters. This is not equal to _cells.size(), as every grid (=cell) might contain multiple clusters.
*/
index_t _numClusters;
/**
* Box min of the domain.
*/
std::array<double, 3> _boxMin;
/**
* Box max of the domain.
*/
std::array<double, 3> _boxMax;
/**
* Side length of xy-grid.
*/
double _gridSideLength{0.};
/**
* Reciprocal of _gridSideLength.
*/
double _gridSideLengthReciprocal{0.};
/**
* Dimensions of the 2D xy-grid.
*/
std::array<index_t, 3> _cellsPerDim{};
/**
* The skin radius.
*/
double _skin;
/**
* The cutoff.
*/
double _cutoff;
/**
* Specifies if the neighbor list uses newton 3 or not.
*/
bool _neighborListIsNewton3;
/**
* Maps indices to the starting pointers for each cluster. For the idea behind the assignment, @see
* buildClusterIndexMap().
*/
std::unordered_map<Particle *, index_t> _clusterIndexMap;
/**
* (_cutoff + _skin)^2.
*/
double _interactionLengthSqr;
};
} // namespace autopas
|
mkldnn_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file mkldnn_common.h
* \brief Common header file for MKLDNN backend subgraph
* \author Ciyong Chen
*/
#ifndef MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_
#define MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_
#if MXNET_USE_ONEDNN == 1
#include <vector>
#include "../../numpy/np_matrix_op-inl.h"
namespace mxnet {
namespace op {
template <typename DType>
static std::vector<float> GetWeightScales(const NDArray& weight,
const NDArray* bias,
const float data_scale,
bool weight_channelwise_scale) {
auto nthreads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
std::vector<float> weight_scales;
const DType* weight_ptr = weight.data().dptr<DType>();
const DType* bias_ptr = bias ? bias->data().dptr<DType>() : nullptr;
const auto wshape = weight.shape();
size_t channel = wshape[0];
size_t offset = wshape.ProdShape(1, wshape.ndim());
std::vector<DType> weight_c_min(channel, MaxValue<DType>());
std::vector<DType> weight_c_max(channel, MinValue<DType>());
for (int c = 0; c < static_cast<int>(channel); ++c) {
const DType* p1 = weight_ptr + c * offset;
for (size_t k = 0; k < offset; ++k) {
if (weight_c_min[c] > p1[k])
weight_c_min[c] = p1[k];
if (weight_c_max[c] < p1[k])
weight_c_max[c] = p1[k];
}
}
if (weight_channelwise_scale) {
weight_scales.resize(channel);
#pragma omp parallel for num_threads(nthreads)
for (int c = 0; c < static_cast<int>(channel); ++c) {
float scale = GetQuantizeScale(mshadow::kInt8, weight_c_min[c], weight_c_max[c]);
if (bias_ptr && bias_ptr[c]) {
// avoid overflow on bias
// TODO(zhennan): mkldnn has bug to handle INT_MAX in bias, so set the maximum value of bias
// to INT_MAX / 2.
float scale_max =
static_cast<float>(bias_ptr[c] > 0 ? MaxValue<int32_t>() : MinValue<int32_t>()) / 2 /
bias_ptr[c] / data_scale;
scale = Min(scale, scale_max);
}
weight_scales[c] = scale;
}
} else {
DType total_min = weight_c_min[0];
DType total_max = weight_c_max[0];
for (size_t c = 0; c < channel; ++c) {
if (total_min > weight_c_min[c])
total_min = weight_c_min[c];
if (total_max < weight_c_max[c])
total_max = weight_c_max[c];
}
weight_scales.resize(3);
weight_scales[0] = GetQuantizeScale(mshadow::kInt8, total_min, total_max);
weight_scales[1] = total_min;
weight_scales[2] = total_max;
}
return weight_scales;
}
static inline void ConvertWeightBias2MKLDNN(NDArray* weight,
NDArray* bias,
bool has_bias,
const mkldnn::memory::desc& weight_md,
const mkldnn::memory::desc* bias_md,
const int num_group,
float data_scale,
const std::vector<float>& weight_scales,
const bool submit = true) {
MKLDNNStream* stream = MKLDNNStream::Get();
const auto new_weight = NDArray(weight_md);
const auto conv_weights_memory = new_weight.GetMKLDNNData();
mkldnn::primitive_attr weight_attr;
if (weight_scales.size()) {
const int weight_mask = (weight_scales.size()) == 1 ? 0 : 1;
weight_attr.set_output_scales(weight_mask, weight_scales);
}
auto default_weights_memory = GetWeights(*weight, num_group);
if (default_weights_memory == nullptr)
default_weights_memory = weight->GetMKLDNNData();
const auto weight_reorder_pd =
mkldnn::reorder::primitive_desc(*default_weights_memory, *conv_weights_memory, weight_attr);
MKLDNNStream::Get()->RegisterPrimArgs(
mkldnn::reorder(weight_reorder_pd),
{{MKLDNN_ARG_FROM, *default_weights_memory}, {MKLDNN_ARG_TO, *conv_weights_memory}});
NDArray new_bias;
if (has_bias && data_scale) {
std::vector<float> bias_scales(weight_scales.size());
for (size_t c = 0; c < weight_scales.size(); ++c) {
bias_scales[c] = weight_scales[c] * data_scale;
}
new_bias = NDArray(*bias_md);
const auto conv_bias_memory = new_bias.GetMKLDNNData();
const int bias_mask = (bias_scales.size()) == 1 ? 0 : 1;
mkldnn::primitive_attr bias_attr;
bias_attr.set_output_scales(bias_mask, bias_scales);
auto bias_weights_memory = bias->GetMKLDNNData();
const auto bias_reorder_pd =
mkldnn::reorder::primitive_desc(*bias_weights_memory, *conv_bias_memory, bias_attr);
MKLDNNStream::Get()->RegisterPrimArgs(
mkldnn::reorder(bias_reorder_pd),
{{MKLDNN_ARG_FROM, *bias_weights_memory}, {MKLDNN_ARG_TO, *conv_bias_memory}});
}
if (submit)
stream->Submit();
*weight = new_weight;
if (has_bias && data_scale)
*bias = new_bias;
}
static inline bool CheckReshapeConditions(const nnvm::Node& node, const index_t out_index) {
const index_t split_output_index = node.inputs[0].index;
if (split_output_index != out_index)
return false;
const auto& reshape_param = nnvm::get<NumpyXReshapeParam>(node.attrs.parsed);
const auto newshape = reshape_param.newshape;
if (newshape.ndim() != 4 || !(newshape[0] == newshape[1] && newshape[0] == -2))
return false;
return true;
}
static inline bool CheckSwapAxisConditions(const nnvm::Node& node) {
auto params = node.attrs.dict;
int dim1 = 0, dim2 = 0;
if (params.count("dim1") && params.count("dim2")) {
dim1 = std::stoi(params.at("dim1"));
dim2 = std::stoi(params.at("dim2"));
} else {
return false;
}
return ((dim1 == 1 && dim2 == 2) || (dim1 == 2 && dim2 == 1));
}
} // namespace op
} // namespace mxnet
#endif // if MXNET_USE_ONEDNN == 1
#endif // MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_
|
GB_unaryop__abs_fp64_bool.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_fp64_bool
// op(A') function: GB_tran__abs_fp64_bool
// C type: double
// A type: bool
// cast: double cij = (double) aij
// unaryop: cij = fabs (aij)
#define GB_ATYPE \
bool
#define GB_CTYPE \
double
// 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 = fabs (x) ;
// casting
#define GB_CASTING(z, aij) \
double z = (double) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_FP64 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_fp64_bool
(
double *Cx, // Cx and Ax may be aliased
bool *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_fp64_bool
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unaryop__minv_int16_uint64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_int16_uint64
// op(A') function: GB_tran__minv_int16_uint64
// C type: int16_t
// A type: uint64_t
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = GB_IMINV_SIGNED (aij, 16)
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 16) ;
// casting
#define GB_CASTING(z, x) \
int16_t z = (int16_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_MINV || GxB_NO_INT16 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_int16_uint64
(
int16_t *restrict Cx,
const uint64_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_int16_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
mandel-omp-task-point.c | /*
* Sequential Mandelbrot program
*
* This program computes and displays all or part of the Mandelbrot
* set. By default, it examines all points in the complex plane
* that have both real and imaginary parts between -2 and 2.
* Command-line parameters allow zooming in on a specific part of
* this range.
*
* Usage:
* mandel [-i maxiter -c x0 y0 -s size -w windowsize]
* where
* maxiter denotes the maximum number of iterations at each point -- by default 1000
* x0, y0, and size specify the range to examine (a square
* centered at (x0 + iy0) of size 2*size by 2*size -- by default,
* a square of size 4 by 4 centered at the origin)
* windowsize denotes the size of the image (diplay window) to compute
*
* Input: none, except the optional command-line arguments
* Output: a graphical display as described in Wilkinson & Allen,
* displayed using the X Window system, plus text output to
* standard output showing the above parameters, plus execution
* time in seconds.
*
* Code based on the original code from Web site for Wilkinson and Allen's
* text on parallel programming:
* http://www.cs.uncc.edu/~abw/parallel/par_prog/
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <malloc.h>
#if _DISPLAY_
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#endif
#include <sys/time.h>
double getusec_() {
struct timeval time;
gettimeofday(&time, NULL);
return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec);
}
#define START_COUNT_TIME stamp = getusec_();
#define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\
stamp = stamp/1e6;\
printf ("%s: %0.6fs\n",(_m), stamp);
/* Default values for things. */
#define N 2 /* size of problem space (x, y from -N to N) */
#define NPIXELS 800 /* size of display window in pixels */
int row, col; // variables used to traverse the problem space
/* Structure definition for complex numbers */
typedef struct {
double real, imag;
} complex;
#if _DISPLAY_
/* Functions for GUI */
#include "mandelbrot-gui.h" /* has setup(), interact() */
#endif
void mandelbrot(int height,
int width,
double real_min,
double imag_min,
double scale_real,
double scale_imag,
int maxiter,
#if _DISPLAY_
int setup_return,
Display *display,
Window win,
GC gc,
double scale_color,
double min_color)
#else
int ** output)
#endif
{
/* Calculate points and save/display */
#pragma omp parallel
#pragma omp single
for (row = 0; row < height; ++row) {
for (col = 0; col < width; ++col) {
#pragma omp task private(col) firstprivate(row)
{
complex z, c;
z.real = z.imag = 0;
/* Scale display coordinates to actual region */
c.real = real_min + ((double) col * scale_real);
c.imag = imag_min + ((double) (height-1-row) * scale_imag);
/* height-1-row so y axis displays
* with larger values at top
*/
/* Calculate z0, z1, .... until divergence or maximum iterations */
int k = 0;
double lengthsq, temp;
do {
temp = z.real*z.real - z.imag*z.imag + c.real;
z.imag = 2*z.real*z.imag + c.imag;
z.real = temp;
lengthsq = z.real*z.real + z.imag*z.imag;
++k;
} while (lengthsq < (N*N) && k < maxiter);
#if _DISPLAY_
/* Scale color and display point */
long color = (long) ((k-1) * scale_color) + min_color;
if (setup_return == EXIT_SUCCESS) {
#pragma omp critical
{
XSetForeground (display, gc, color);
XDrawPoint (display, win, gc, col, row);
}
}
#else
output[row][col]=k;
#endif
}
}
}
}
int main(int argc, char *argv[]) {
int maxiter = 1000;
double real_min;
double real_max;
double imag_min;
double imag_max;
int width = NPIXELS; /* dimensions of display window */
int height = NPIXELS;
double size=N, x0 = 0, y0 = 0;
#if _DISPLAY_
Display *display;
Window win;
GC gc;
int setup_return;
long min_color = 0, max_color = 0;
double scale_color;
#else
int ** output;
FILE *fp = NULL;
#endif
double scale_real, scale_imag;
/* Process command-line arguments */
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "-i")==0) {
maxiter = atoi(argv[++i]);
}
else if (strcmp(argv[i], "-w")==0) {
width = atoi(argv[++i]);
height = width;
}
else if (strcmp(argv[i], "-s")==0) {
size = atof(argv[++i]);
}
#if !_DISPLAY_
else if (strcmp(argv[i], "-o")==0) {
if((fp=fopen("mandel.out", "wb"))==NULL) {
fprintf(stderr, "Unable to open file\n");
return EXIT_FAILURE;
}
}
#endif
else if (strcmp(argv[i], "-c")==0) {
x0 = atof(argv[++i]);
y0 = atof(argv[++i]);
}
else {
#if _DISPLAY_
fprintf(stderr, "Usage: %s [-i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]);
#else
fprintf(stderr, "Usage: %s [-o -i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]);
fprintf(stderr, " -o to write computed image to disk (default no file generated)\n");
#endif
fprintf(stderr, " -i to specify maximum number of iterations at each point (default 1000)\n");
#if _DISPLAY_
fprintf(stderr, " -w to specify the size of the display window (default 800x800 pixels)\n");
#else
fprintf(stderr, " -w to specify the size of the image to compute (default 800x800 elements)\n");
#endif
fprintf(stderr, " -c to specify the center x0+iy0 of the square to compute (default origin)\n");
fprintf(stderr, " -s to specify the size of the square to compute (default 2, i.e. size 4 by 4)\n");
return EXIT_FAILURE;
}
}
real_min = x0 - size;
real_max = x0 + size;
imag_min = y0 - size;
imag_max = y0 + size;
/* Produce text output */
fprintf(stdout, "\n");
fprintf(stdout, "Mandelbrot program\n");
fprintf(stdout, "center = (%g, %g), size = %g\n",
(real_max + real_min)/2, (imag_max + imag_min)/2,
(real_max - real_min)/2);
fprintf(stdout, "maximum iterations = %d\n", maxiter);
fprintf(stdout, "\n");
#if _DISPLAY_
/* Initialize for graphical display */
setup_return =
setup(width, height, &display, &win, &gc, &min_color, &max_color);
if (setup_return != EXIT_SUCCESS) {
fprintf(stderr, "Unable to initialize display, continuing\n");
return EXIT_FAILURE;
}
#else
output = malloc(height*sizeof(int *));
for (int row = 0; row < height; ++row)
output[row] = malloc(width*sizeof(int));
#endif
/* Compute factors to scale computational region to window */
scale_real = (double) (real_max - real_min) / (double) width;
scale_imag = (double) (imag_max - imag_min) / (double) height;
#if _DISPLAY_
/* Compute factor for color scaling */
scale_color = (double) (max_color - min_color) / (double) (maxiter - 1);
#endif
/* Start timing */
double stamp;
START_COUNT_TIME;
#if _DISPLAY_
mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter,
setup_return, display, win, gc, scale_color, min_color);
#else
mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter,
output);
#endif
/* End timing */
STOP_COUNT_TIME("Total execution time");
/* Be sure all output is written */
#if _DISPLAY_
if (setup_return == EXIT_SUCCESS) {
XFlush (display);
}
#else
if (fp != NULL)
{
for (int row = 0; row < height; ++row)
if(fwrite(output[row], sizeof(int), width, fp) != width) {
fprintf(stderr, "Output file not written correctly\n");
}
}
#endif
#if _DISPLAY_
/* Wait for user response, then exit program */
if (setup_return == EXIT_SUCCESS) {
interact(display, &win, width, height,
real_min, real_max, imag_min, imag_max);
}
return EXIT_SUCCESS;
#endif
}
|
atomic_write_codegen.c | // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -target-cpu core2 -fopenmp -x c -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -target-cpu core2 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -target-cpu core2 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -target-cpu core2 -fopenmp-simd -x c -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c -triple x86_64-apple-darwin10 -target-cpu core2 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c -triple x86_64-apple-darwin10 -target-cpu core2 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
// REQUIRES: x86-registered-target
#ifndef HEADER
#define HEADER
_Bool bv, bx;
char cv, cx;
unsigned char ucv, ucx;
short sv, sx;
unsigned short usv, usx;
int iv, ix;
unsigned int uiv, uix;
long lv, lx;
unsigned long ulv, ulx;
long long llv, llx;
unsigned long long ullv, ullx;
float fv, fx;
double dv, dx;
long double ldv, ldx;
_Complex int civ, cix;
_Complex float cfv, cfx;
_Complex double cdv, cdx;
typedef int int4 __attribute__((__vector_size__(16)));
int4 int4x;
struct BitFields {
int : 32;
int a : 31;
} bfx;
struct BitFields_packed {
int : 32;
int a : 31;
} __attribute__ ((__packed__)) bfx_packed;
struct BitFields2 {
int : 31;
int a : 1;
} bfx2;
struct BitFields2_packed {
int : 31;
int a : 1;
} __attribute__ ((__packed__)) bfx2_packed;
struct BitFields3 {
int : 11;
int a : 14;
} bfx3;
struct BitFields3_packed {
int : 11;
int a : 14;
} __attribute__ ((__packed__)) bfx3_packed;
struct BitFields4 {
short : 16;
int a: 1;
long b : 7;
} bfx4;
struct BitFields4_packed {
short : 16;
int a: 1;
long b : 7;
} __attribute__ ((__packed__)) bfx4_packed;
typedef float float2 __attribute__((ext_vector_type(2)));
float2 float2x;
// Register "0" is currently an invalid register for global register variables.
// Use "esp" instead of "0".
// register int rix __asm__("0");
register int rix __asm__("esp");
int main() {
// CHECK: store atomic i32 1, i32* getelementptr inbounds ({ i32, i32 }, { i32, i32 }* @civ, i32 0, i32 1) monotonic,
#pragma omp atomic write
__imag(civ) = 1;
// CHECK: load i8, i8*
// CHECK: store atomic i8
#pragma omp atomic write
bx = bv;
// CHECK: load i8, i8*
// CHECK: store atomic i8
#pragma omp atomic write
cx = cv;
// CHECK: load i8, i8*
// CHECK: store atomic i8
#pragma omp atomic write
ucx = ucv;
// CHECK: load i16, i16*
// CHECK: store atomic i16
#pragma omp atomic write
sx = sv;
// CHECK: load i16, i16*
// CHECK: store atomic i16
#pragma omp atomic write
usx = usv;
// CHECK: load i32, i32*
// CHECK: store atomic i32
#pragma omp atomic write
ix = iv;
// CHECK: load i32, i32*
// CHECK: store atomic i32
#pragma omp atomic write
uix = uiv;
// CHECK: load i64, i64*
// CHECK: store atomic i64
#pragma omp atomic write
lx = lv;
// CHECK: load i64, i64*
// CHECK: store atomic i64
#pragma omp atomic write
ulx = ulv;
// CHECK: load i64, i64*
// CHECK: store atomic i64
#pragma omp atomic write
llx = llv;
// CHECK: load i64, i64*
// CHECK: store atomic i64
#pragma omp atomic write
ullx = ullv;
// CHECK: load float, float*
// CHECK: bitcast float {{.*}} to i32
// CHECK: store atomic i32 {{.*}}, i32* bitcast (float*
#pragma omp atomic write
fx = fv;
// CHECK: load double, double*
// CHECK: bitcast double {{.*}} to i64
// CHECK: store atomic i64 {{.*}}, i64* bitcast (double*
#pragma omp atomic write
dx = dv;
// CHECK: [[LD:%.+]] = load x86_fp80, x86_fp80*
// CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[LDTEMP:%.*]] to i8*
// CHECK: call void @llvm.memset.p0i8.i64(i8* align 16 [[BITCAST]], i8 0, i64 16, i1 false)
// CHECK: store x86_fp80 [[LD]], x86_fp80* [[LDTEMP]]
// CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[LDTEMP:%.*]] to i128*
// CHECK: [[LD:%.+]] = load i128, i128* [[BITCAST]]
// CHECK: store atomic i128 [[LD]], i128* bitcast (x86_fp80*
#pragma omp atomic write
ldx = ldv;
// CHECK: [[REAL_VAL:%.+]] = load i32, i32* getelementptr inbounds (%complex._ZTSi, %complex._ZTSi* @{{.*}}, i32 0, i32 0)
// CHECK: [[IMG_VAL:%.+]] = load i32, i32* getelementptr inbounds (%complex._ZTSi, %complex._ZTSi* @{{.*}}, i32 0, i32 1)
// CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds %complex._ZTSi, %complex._ZTSi* [[TEMP:%.+]], i32 0, i32 0
// CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds %complex._ZTSi, %complex._ZTSi* [[TEMP]], i32 0, i32 1
// CHECK: store i32 [[REAL_VAL]], i32* [[TEMP_REAL_REF]]
// CHECK: store i32 [[IMG_VAL]], i32* [[TEMP_IMG_REF]]
// CHECK: [[BITCAST:%.+]] = bitcast %complex._ZTSi* [[TEMP]] to i8*
// CHECK: call void @__atomic_store(i64 8, i8* bitcast (%complex._ZTSi* @{{.*}} to i8*), i8* [[BITCAST]], i32 0)
#pragma omp atomic write
cix = civ;
// CHECK: [[REAL_VAL:%.+]] = load float, float* getelementptr inbounds (%complex._ZTSf, %complex._ZTSf* @{{.*}}, i32 0, i32 0)
// CHECK: [[IMG_VAL:%.+]] = load float, float* getelementptr inbounds (%complex._ZTSf, %complex._ZTSf* @{{.*}}, i32 0, i32 1)
// CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds %complex._ZTSf, %complex._ZTSf* [[TEMP:%.+]], i32 0, i32 0
// CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds %complex._ZTSf, %complex._ZTSf* [[TEMP]], i32 0, i32 1
// CHECK: store float [[REAL_VAL]], float* [[TEMP_REAL_REF]]
// CHECK: store float [[IMG_VAL]], float* [[TEMP_IMG_REF]]
// CHECK: [[BITCAST:%.+]] = bitcast %complex._ZTSf* [[TEMP]] to i8*
// CHECK: call void @__atomic_store(i64 8, i8* bitcast (%complex._ZTSf* @{{.*}} to i8*), i8* [[BITCAST]], i32 0)
#pragma omp atomic write
cfx = cfv;
// CHECK: [[REAL_VAL:%.+]] = load double, double* getelementptr inbounds (%complex._ZTSd, %complex._ZTSd* @{{.*}}, i32 0, i32 0)
// CHECK: [[IMG_VAL:%.+]] = load double, double* getelementptr inbounds (%complex._ZTSd, %complex._ZTSd* @{{.*}}, i32 0, i32 1)
// CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds %complex._ZTSd, %complex._ZTSd* [[TEMP:%.+]], i32 0, i32 0
// CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds %complex._ZTSd, %complex._ZTSd* [[TEMP]], i32 0, i32 1
// CHECK: store double [[REAL_VAL]], double* [[TEMP_REAL_REF]]
// CHECK: store double [[IMG_VAL]], double* [[TEMP_IMG_REF]]
// CHECK: [[BITCAST:%.+]] = bitcast %complex._ZTSd* [[TEMP]] to i8*
// CHECK: call void @__atomic_store(i64 16, i8* bitcast (%complex._ZTSd* @{{.*}} to i8*), i8* [[BITCAST]], i32 5)
// CHECK: call{{.*}} @__kmpc_flush(
#pragma omp atomic seq_cst write
cdx = cdv;
// CHECK: load i8, i8*
// CHECK: store atomic i64
#pragma omp atomic write
ulx = bv;
// CHECK: load i8, i8*
// CHECK: store atomic i8
#pragma omp atomic write
bx = cv;
// CHECK: load i8, i8*
// CHECK: store atomic i8
// CHECK: call{{.*}} @__kmpc_flush(
#pragma omp atomic write, seq_cst
cx = ucv;
// CHECK: load i16, i16*
// CHECK: store atomic i64
#pragma omp atomic write
ulx = sv;
// CHECK: load i16, i16*
// CHECK: store atomic i64
#pragma omp atomic write
lx = usv;
// CHECK: load i32, i32*
// CHECK: store atomic i32
// CHECK: call{{.*}} @__kmpc_flush(
#pragma omp atomic seq_cst, write
uix = iv;
// CHECK: load i32, i32*
// CHECK: store atomic i32
#pragma omp atomic write
ix = uiv;
// CHECK: load i64, i64*
// CHECK: [[VAL:%.+]] = trunc i64 %{{.*}} to i32
// CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds %complex._ZTSi, %complex._ZTSi* [[TEMP:%.+]], i32 0, i32 0
// CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds %complex._ZTSi, %complex._ZTSi* [[TEMP]], i32 0, i32 1
// CHECK: store i32 [[VAL]], i32* [[TEMP_REAL_REF]]
// CHECK: store i32 0, i32* [[TEMP_IMG_REF]]
// CHECK: [[BITCAST:%.+]] = bitcast %complex._ZTSi* [[TEMP]] to i8*
// CHECK: call void @__atomic_store(i64 8, i8* bitcast (%complex._ZTSi* @{{.+}} to i8*), i8* [[BITCAST]], i32 0)
#pragma omp atomic write
cix = lv;
// CHECK: load i64, i64*
// CHECK: store atomic i32 %{{.+}}, i32* bitcast (float*
#pragma omp atomic write
fx = ulv;
// CHECK: load i64, i64*
// CHECK: store atomic i64 %{{.+}}, i64* bitcast (double*
#pragma omp atomic write
dx = llv;
// CHECK: load i64, i64*
// CHECK: [[VAL:%.+]] = uitofp i64 %{{.+}} to x86_fp80
// CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[TEMP:%.+]] to i8*
// CHECK: call void @llvm.memset.p0i8.i64(i8* align 16 [[BITCAST]], i8 0, i64 16, i1 false)
// CHECK: store x86_fp80 [[VAL]], x86_fp80* [[TEMP]]
// CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[TEMP]] to i128*
// CHECK: [[VAL:%.+]] = load i128, i128* [[BITCAST]]
// CHECK: store atomic i128 [[VAL]], i128* bitcast (x86_fp80*
#pragma omp atomic write
ldx = ullv;
// CHECK: load float, float*
// CHECK: [[VAL:%.+]] = fptosi float %{{.*}} to i32
// CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds %complex._ZTSi, %complex._ZTSi* [[TEMP:%.+]], i32 0, i32 0
// CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds %complex._ZTSi, %complex._ZTSi* [[TEMP]], i32 0, i32 1
// CHECK: store i32 [[VAL]], i32* [[TEMP_REAL_REF]]
// CHECK: store i32 0, i32* [[TEMP_IMG_REF]]
// CHECK: [[BITCAST:%.+]] = bitcast %complex._ZTSi* [[TEMP]] to i8*
// CHECK: call void @__atomic_store(i64 8, i8* bitcast (%complex._ZTSi* @{{.+}} to i8*), i8* [[BITCAST]], i32 0)
#pragma omp atomic write
cix = fv;
// CHECK: load double, double*
// CHECK: store atomic i16
#pragma omp atomic write
sx = dv;
// CHECK: load x86_fp80, x86_fp80*
// CHECK: store atomic i8
#pragma omp atomic write
bx = ldv;
// CHECK: load i32, i32* getelementptr inbounds (%complex._ZTSi, %complex._ZTSi* @{{.+}}, i32 0, i32 0)
// CHECK: load i32, i32* getelementptr inbounds (%complex._ZTSi, %complex._ZTSi* @{{.+}}, i32 0, i32 1)
// CHECK: icmp ne i32 %{{.+}}, 0
// CHECK: icmp ne i32 %{{.+}}, 0
// CHECK: or i1
// CHECK: store atomic i8
#pragma omp atomic write
bx = civ;
// CHECK: load float, float* getelementptr inbounds (%complex._ZTSf, %complex._ZTSf* @{{.*}}, i32 0, i32 0)
// CHECK: store atomic i16
#pragma omp atomic write
usx = cfv;
// CHECK: load double, double* getelementptr inbounds (%complex._ZTSd, %complex._ZTSd* @{{.+}}, i32 0, i32 0)
// CHECK: store atomic i64
#pragma omp atomic write
llx = cdv;
// CHECK-DAG: [[IDX:%.+]] = load i16, i16* @{{.+}}
// CHECK-DAG: load i8, i8*
// CHECK-DAG: [[VEC_ITEM_VAL:%.+]] = zext i1 %{{.+}} to i32
// CHECK: [[I128VAL:%.+]] = load atomic i128, i128* bitcast (<4 x i32>* [[DEST:@.+]] to i128*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_I128:%.+]] = phi i128 [ [[I128VAL]], %{{.+}} ], [ [[FAILED_I128_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[BITCAST:%.+]] = bitcast <4 x i32>* [[LDTEMP:%.+]] to i128*
// CHECK: store i128 [[OLD_I128]], i128* [[BITCAST]],
// CHECK: [[VEC_VAL:%.+]] = load <4 x i32>, <4 x i32>* [[LDTEMP]]
// CHECK: [[NEW_VEC_VAL:%.+]] = insertelement <4 x i32> [[VEC_VAL]], i32 [[VEC_ITEM_VAL]], i16 [[IDX]]
// CHECK: store <4 x i32> [[NEW_VEC_VAL]], <4 x i32>* [[LDTEMP]]
// CHECK: [[NEW_I128:%.+]] = load i128, i128* [[BITCAST]]
// CHECK: [[RES:%.+]] = cmpxchg i128* bitcast (<4 x i32>* [[DEST]] to i128*), i128 [[OLD_I128]], i128 [[NEW_I128]] monotonic monotonic
// CHECK: [[FAILED_I128_OLD_VAL:%.+]] = extractvalue { i128, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
int4x[sv] = bv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[PREV_VALUE:%.+]] = load atomic i32, i32* bitcast (i8* getelementptr (i8, i8* bitcast (%struct._Z9BitFields* @{{.+}} to i8*), i64 4) to i32*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i32 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[BF_VALUE:%.+]] = and i32 [[NEW_VAL]], 2147483647
// CHECK: [[BF_CLEAR:%.+]] = and i32 %{{.+}}, -2147483648
// CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i32 %{{.+}}, i32* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i32* bitcast (i8* getelementptr (i8, i8* bitcast (%struct._Z9BitFields* @{{.+}} to i8*), i64 4) to i32*), i32 [[OLD_BF_VALUE]], i32 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i32, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i32, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[BITCAST:%.+]] = bitcast i32* [[LDTEMP:%.+]] to i8*
// CHECK: call void @__atomic_load(i64 4, i8* getelementptr (i8, i8* bitcast (%struct._Z16BitFields_packed* @{{.+}} to i8*), i64 4), i8* [[BITCAST]], i32 0)
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]],
// CHECK: store i32 [[OLD_BF_VALUE]], i32* [[LDTEMP1:%.+]],
// CHECK: [[OLD_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP1]],
// CHECK: [[BF_VALUE:%.+]] = and i32 [[NEW_VAL]], 2147483647
// CHECK: [[BF_CLEAR:%.+]] = and i32 [[OLD_BF_VALUE]], -2147483648
// CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i32 %{{.+}}, i32* [[LDTEMP1]]
// CHECK: [[BITCAST_TEMP_OLD_BF_ADDR:%.+]] = bitcast i32* [[LDTEMP]] to i8*
// CHECK: [[BITCAST_TEMP_NEW_BF_ADDR:%.+]] = bitcast i32* [[LDTEMP1]] to i8*
// CHECK: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i64 4, i8* getelementptr (i8, i8* bitcast (%struct._Z16BitFields_packed* @{{.+}} to i8*), i64 4), i8* [[BITCAST_TEMP_OLD_BF_ADDR]], i8* [[BITCAST_TEMP_NEW_BF_ADDR]], i32 0, i32 0)
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx_packed.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[PREV_VALUE:%.+]] = load atomic i32, i32* bitcast (%struct._Z10BitFields2* @{{.+}} to i32*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i32 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[BF_AND:%.+]] = and i32 [[NEW_VAL]], 1
// CHECK: [[BF_VALUE:%.+]] = shl i32 [[BF_AND]], 31
// CHECK: [[BF_CLEAR:%.+]] = and i32 %{{.+}}, 2147483647
// CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i32 %{{.+}}, i32* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i32* bitcast (%struct._Z10BitFields2* @{{.+}} to i32*), i32 [[OLD_BF_VALUE]], i32 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i32, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i32, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx2.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[PREV_VALUE:%.+]] = load atomic i8, i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields2_packed* @{{.+}} to i8*), i64 3) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i8 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[TRUNC:%.+]] = trunc i32 [[NEW_VAL]] to i8
// CHECK: [[BF_AND:%.+]] = and i8 [[TRUNC]], 1
// CHECK: [[BF_VALUE:%.+]] = shl i8 [[BF_AND]], 7
// CHECK: [[BF_CLEAR:%.+]] = and i8 %{{.+}}, 127
// CHECK: or i8 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i8 %{{.+}}, i8* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i8, i8* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields2_packed* @{{.+}} to i8*), i64 3), i8 [[OLD_BF_VALUE]], i8 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i8, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i8, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx2_packed.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[PREV_VALUE:%.+]] = load atomic i32, i32* bitcast (%struct._Z10BitFields3* @{{.+}} to i32*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i32 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[BF_AND:%.+]] = and i32 [[NEW_VAL]], 16383
// CHECK: [[BF_VALUE:%.+]] = shl i32 [[BF_AND]], 11
// CHECK: [[BF_CLEAR:%.+]] = and i32 %{{.+}}, -33552385
// CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i32 %{{.+}}, i32* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i32* bitcast (%struct._Z10BitFields3* @{{.+}} to i32*), i32 [[OLD_BF_VALUE]], i32 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i32, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i32, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx3.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[LDTEMP:%.+]] = bitcast i32* %{{.+}} to i24*
// CHECK: [[BITCAST:%.+]] = bitcast i24* %{{.+}} to i8*
// CHECK: call void @__atomic_load(i64 3, i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields3_packed* @{{.+}} to i8*), i64 1), i8* [[BITCAST]], i32 0)
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_VAL:%.+]] = load i24, i24* %{{.+}},
// CHECK: store i24 [[OLD_VAL]], i24* [[TEMP:%.+]],
// CHECK: [[TRUNC:%.+]] = trunc i32 [[NEW_VAL]] to i24
// CHECK: [[BF_AND:%.+]] = and i24 [[TRUNC]], 16383
// CHECK: [[BF_VALUE:%.+]] = shl i24 [[BF_AND]], 3
// CHECK: [[BF_CLEAR:%.+]] = and i24 %{{.+}}, -131065
// CHECK: or i24 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i24 %{{.+}}, i24* [[TEMP]]
// CHECK: [[BITCAST_TEMP_OLD_BF_ADDR:%.+]] = bitcast i24* [[LDTEMP]] to i8*
// CHECK: [[BITCAST_TEMP_NEW_BF_ADDR:%.+]] = bitcast i24* [[TEMP]] to i8*
// CHECK: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i64 3, i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields3_packed* @{{.+}} to i8*), i64 1), i8* [[BITCAST_TEMP_OLD_BF_ADDR]], i8* [[BITCAST_TEMP_NEW_BF_ADDR]], i32 0, i32 0)
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx3_packed.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[PREV_VALUE:%.+]] = load atomic i64, i64* bitcast (%struct._Z10BitFields4* @{{.+}} to i64*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i64 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[ZEXT:%.+]] = zext i32 [[NEW_VAL]] to i64
// CHECK: [[BF_AND:%.+]] = and i64 [[ZEXT]], 1
// CHECK: [[BF_VALUE:%.+]] = shl i64 [[BF_AND]], 16
// CHECK: [[BF_CLEAR:%.+]] = and i64 %{{.+}}, -65537
// CHECK: or i64 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i64 %{{.+}}, i64* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i64, i64* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i64* bitcast (%struct._Z10BitFields4* @{{.+}} to i64*), i64 [[OLD_BF_VALUE]], i64 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i64, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i64, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx4.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32
// CHECK: [[PREV_VALUE:%.+]] = load atomic i8, i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields4_packed* @{{.+}} to i8*), i64 2) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i8 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[TRUNC:%.+]] = trunc i32 [[NEW_VAL]] to i8
// CHECK: [[BF_VALUE:%.+]] = and i8 [[TRUNC]], 1
// CHECK: [[BF_CLEAR:%.+]] = and i8 %{{.+}}, -2
// CHECK: or i8 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i8 %{{.+}}, i8* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i8, i8* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields4_packed* @{{.+}} to i8*), i64 2), i8 [[OLD_BF_VALUE]], i8 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i8, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i8, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx4_packed.a = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i64
// CHECK: [[PREV_VALUE:%.+]] = load atomic i64, i64* bitcast (%struct._Z10BitFields4* @{{.+}} to i64*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i64 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[BF_AND:%.+]] = and i64 [[NEW_VAL]], 127
// CHECK: [[BF_VALUE:%.+]] = shl i64 [[BF_AND]], 17
// CHECK: [[BF_CLEAR:%.+]] = and i64 %{{.+}}, -16646145
// CHECK: or i64 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i64 %{{.+}}, i64* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i64, i64* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i64* bitcast (%struct._Z10BitFields4* @{{.+}} to i64*), i64 [[OLD_BF_VALUE]], i64 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i64, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i64, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx4.b = ldv;
// CHECK: load x86_fp80, x86_fp80* @{{.+}}
// CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i64
// CHECK: [[PREV_VALUE:%.+]] = load atomic i8, i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields4_packed* @{{.+}} to i8*), i64 2) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_BF_VALUE:%.+]] = phi i8 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[TRUNC:%.+]] = trunc i64 [[NEW_VAL]] to i8
// CHECK: [[BF_AND:%.+]] = and i8 [[TRUNC]], 127
// CHECK: [[BF_VALUE:%.+]] = shl i8 [[BF_AND]], 1
// CHECK: [[BF_CLEAR:%.+]] = and i8 %{{.+}}, 1
// CHECK: or i8 [[BF_CLEAR]], [[BF_VALUE]]
// CHECK: store i8 %{{.+}}, i8* [[LDTEMP:%.+]]
// CHECK: [[NEW_BF_VALUE:%.+]] = load i8, i8* [[LDTEMP]]
// CHECK: [[RES:%.+]] = cmpxchg i8* getelementptr (i8, i8* bitcast (%struct._Z17BitFields4_packed* @{{.+}} to i8*), i64 2), i8 [[OLD_BF_VALUE]], i8 [[NEW_BF_VALUE]] monotonic monotonic
// CHECK: [[FAILED_OLD_VAL]] = extractvalue { i8, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i8, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
bfx4_packed.b = ldv;
// CHECK: load i64, i64*
// CHECK: [[VEC_ITEM_VAL:%.+]] = uitofp i64 %{{.+}} to float
// CHECK: [[I64VAL:%.+]] = load atomic i64, i64* bitcast (<2 x float>* [[DEST:@.+]] to i64*) monotonic
// CHECK: br label %[[CONT:.+]]
// CHECK: [[CONT]]
// CHECK: [[OLD_I64:%.+]] = phi i64 [ [[I64VAL]], %{{.+}} ], [ [[FAILED_I64_OLD_VAL:%.+]], %[[CONT]] ]
// CHECK: [[BITCAST:%.+]] = bitcast <2 x float>* [[LDTEMP:%.+]] to i64*
// CHECK: store i64 [[OLD_I64]], i64* [[BITCAST]],
// CHECK: [[VEC_VAL:%.+]] = load <2 x float>, <2 x float>* [[LDTEMP]]
// CHECK: [[NEW_VEC_VAL:%.+]] = insertelement <2 x float> [[VEC_VAL]], float [[VEC_ITEM_VAL]], i64 0
// CHECK: store <2 x float> [[NEW_VEC_VAL]], <2 x float>* [[LDTEMP]]
// CHECK: [[NEW_I64:%.+]] = load i64, i64* [[BITCAST]]
// CHECK: [[RES:%.+]] = cmpxchg i64* bitcast (<2 x float>* [[DEST]] to i64*), i64 [[OLD_I64]], i64 [[NEW_I64]] monotonic monotonic
// CHECK: [[FAILED_I64_OLD_VAL:%.+]] = extractvalue { i64, i1 } [[RES]], 0
// CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i64, i1 } [[RES]], 1
// CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]]
// CHECK: [[EXIT]]
#pragma omp atomic write
float2x.x = ulv;
// CHECK: call i32 @llvm.read_register.i32(
// CHECK: sitofp i32 %{{.+}} to double
// CHECK: bitcast double %{{.+}} to i64
// CHECK: store atomic i64 %{{.+}}, i64* bitcast (double* @{{.+}} to i64*) seq_cst
// CHECK: call{{.*}} @__kmpc_flush(
#pragma omp atomic write seq_cst
dv = rix;
return 0;
}
#endif
|
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 %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2011 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The RotateImage, XShearImage, and YShearImage methods are based on the
% paper "A Fast Algorithm for General Raster Rotatation" by Alan W. Paeth,
% Graphics Interface '86 (Vancouver). RotateImage 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 "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob-private.h"
#include "magick/cache-private.h"
#include "magick/color-private.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/decorate.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/memory_.h"
#include "magick/list.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-private.h"
#include "magick/quantum.h"
#include "magick/resource_.h"
#include "magick/shear.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/transform.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A f f i n e T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AffineTransformImage() transforms an image as dictated by the affine matrix.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the AffineTransformImage method is:
%
% Image *AffineTransformImage(const Image *image,
% AffineMatrix *affine_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o affine_matrix: the affine matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AffineTransformImage(const Image *image,
const AffineMatrix *affine_matrix,ExceptionInfo *exception)
{
double
distort[6];
Image
*deskew_image;
/*
Affine transform image.
*/
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(affine_matrix != (AffineMatrix *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
distort[0]=affine_matrix->sx;
distort[1]=affine_matrix->rx;
distort[2]=affine_matrix->ry;
distort[3]=affine_matrix->sy;
distort[4]=affine_matrix->tx;
distort[5]=affine_matrix->ty;
deskew_image=DistortImage(image,AffineProjectionDistortion,6,distort,
MagickTrue,exception);
return(deskew_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ 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 MagickRealType x_shear,const MagickRealType x_shear,
% const MagickRealType width,const MagickRealType 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 MagickRealType x_shear,const MagickRealType y_shear,
const MagickRealType width,const MagickRealType 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 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.
%
*/
typedef struct _RadonInfo
{
CacheType
type;
size_t
width,
height;
MagickSizeType
length;
MagickBooleanType
mapped;
char
path[MaxTextExtent];
int
file;
unsigned short
*cells;
} RadonInfo;
static RadonInfo *DestroyRadonInfo(RadonInfo *radon_info)
{
assert(radon_info != (RadonInfo *) NULL);
switch (radon_info->type)
{
case MemoryCache:
{
if (radon_info->mapped == MagickFalse)
radon_info->cells=(unsigned short *) RelinquishMagickMemory(
radon_info->cells);
else
radon_info->cells=(unsigned short *) UnmapBlob(radon_info->cells,
(size_t) radon_info->length);
RelinquishMagickResource(MemoryResource,radon_info->length);
break;
}
case MapCache:
{
radon_info->cells=(unsigned short *) UnmapBlob(radon_info->cells,(size_t)
radon_info->length);
RelinquishMagickResource(MapResource,radon_info->length);
}
case DiskCache:
{
if (radon_info->file != -1)
(void) close(radon_info->file);
(void) RelinquishUniqueFileResource(radon_info->path);
RelinquishMagickResource(DiskResource,radon_info->length);
break;
}
default:
break;
}
return((RadonInfo *) RelinquishMagickMemory(radon_info));
}
static MagickBooleanType ResetRadonCells(RadonInfo *radon_info)
{
register ssize_t
x;
ssize_t
count,
y;
unsigned short
value;
if (radon_info->type != DiskCache)
{
(void) ResetMagickMemory(radon_info->cells,0,(size_t) radon_info->length);
return(MagickTrue);
}
value=0;
(void) lseek(radon_info->file,0,SEEK_SET);
for (y=0; y < (ssize_t) radon_info->height; y++)
{
for (x=0; x < (ssize_t) radon_info->width; x++)
{
count=write(radon_info->file,&value,sizeof(*radon_info->cells));
if (count != (ssize_t) sizeof(*radon_info->cells))
break;
}
if (x < (ssize_t) radon_info->width)
break;
}
return(y < (ssize_t) radon_info->height ? MagickFalse : MagickTrue);
}
static RadonInfo *AcquireRadonInfo(const Image *image,const size_t width,
const size_t height,ExceptionInfo *exception)
{
MagickBooleanType
status;
RadonInfo
*radon_info;
radon_info=(RadonInfo *) AcquireMagickMemory(sizeof(*radon_info));
if (radon_info == (RadonInfo *) NULL)
return((RadonInfo *) NULL);
(void) ResetMagickMemory(radon_info,0,sizeof(*radon_info));
radon_info->width=width;
radon_info->height=height;
radon_info->length=(MagickSizeType) width*height*sizeof(*radon_info->cells);
radon_info->type=MemoryCache;
status=AcquireMagickResource(AreaResource,radon_info->length);
if ((status != MagickFalse) &&
(radon_info->length == (MagickSizeType) ((size_t) radon_info->length)))
{
status=AcquireMagickResource(MemoryResource,radon_info->length);
if (status != MagickFalse)
{
radon_info->mapped=MagickFalse;
radon_info->cells=(unsigned short *) AcquireMagickMemory((size_t)
radon_info->length);
if (radon_info->cells == (unsigned short *) NULL)
{
radon_info->mapped=MagickTrue;
radon_info->cells=(unsigned short *) MapBlob(-1,IOMode,0,(size_t)
radon_info->length);
}
if (radon_info->cells == (unsigned short *) NULL)
RelinquishMagickResource(MemoryResource,radon_info->length);
}
}
radon_info->file=(-1);
if (radon_info->cells == (unsigned short *) NULL)
{
status=AcquireMagickResource(DiskResource,radon_info->length);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(DestroyRadonInfo(radon_info));
}
radon_info->type=DiskCache;
(void) AcquireMagickResource(MemoryResource,radon_info->length);
radon_info->file=AcquireUniqueFileResource(radon_info->path);
if (radon_info->file == -1)
return(DestroyRadonInfo(radon_info));
status=AcquireMagickResource(MapResource,radon_info->length);
if (status != MagickFalse)
{
status=ResetRadonCells(radon_info);
if (status != MagickFalse)
{
radon_info->cells=(unsigned short *) MapBlob(radon_info->file,
IOMode,0,(size_t) radon_info->length);
if (radon_info->cells != (unsigned short *) NULL)
radon_info->type=MapCache;
else
RelinquishMagickResource(MapResource,radon_info->length);
}
}
}
return(radon_info);
}
static inline size_t MagickMin(const size_t x,const size_t y)
{
if (x < y)
return(x);
return(y);
}
static inline ssize_t ReadRadonCell(const RadonInfo *radon_info,
const MagickOffsetType offset,const size_t length,unsigned char *buffer)
{
register ssize_t
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PPREAD)
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ReadRadonCell)
#endif
{
i=(-1);
if (lseek(radon_info->file,offset,SEEK_SET) >= 0)
{
#endif
count=0;
for (i=0; i < (ssize_t) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PPREAD)
count=read(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
SSIZE_MAX));
#else
count=pread(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
SSIZE_MAX),offset+i);
#endif
if (count > 0)
continue;
count=0;
if (errno != EINTR)
{
i=(-1);
break;
}
}
#if !defined(MAGICKCORE_HAVE_PPREAD)
}
}
#endif
return(i);
}
static inline ssize_t WriteRadonCell(const RadonInfo *radon_info,
const MagickOffsetType offset,const size_t length,const unsigned char *buffer)
{
register ssize_t
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PWRITE)
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_WriteRadonCell)
#endif
{
if (lseek(radon_info->file,offset,SEEK_SET) >= 0)
{
#endif
count=0;
for (i=0; i < (ssize_t) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PWRITE)
count=write(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
SSIZE_MAX));
#else
count=pwrite(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
SSIZE_MAX),offset+i);
#endif
if (count > 0)
continue;
count=0;
if (errno != EINTR)
{
i=(-1);
break;
}
}
#if !defined(MAGICKCORE_HAVE_PWRITE)
}
}
#endif
return(i);
}
static inline unsigned short GetRadonCell(const RadonInfo *radon_info,
const ssize_t x,const ssize_t y)
{
MagickOffsetType
i;
unsigned short
value;
i=(MagickOffsetType) radon_info->height*x+y;
if ((i < 0) ||
((MagickSizeType) (i*sizeof(*radon_info->cells)) >= radon_info->length))
return(0);
if (radon_info->type != DiskCache)
return(radon_info->cells[i]);
value=0;
(void) ReadRadonCell(radon_info,i*sizeof(*radon_info->cells),
sizeof(*radon_info->cells),(unsigned char *) &value);
return(value);
}
static inline MagickBooleanType SetRadonCell(const RadonInfo *radon_info,
const ssize_t x,const ssize_t y,const unsigned short value)
{
MagickOffsetType
i;
ssize_t
count;
i=(MagickOffsetType) radon_info->height*x+y;
if ((i < 0) ||
((MagickSizeType) (i*sizeof(*radon_info->cells)) >= radon_info->length))
return(MagickFalse);
if (radon_info->type != DiskCache)
{
radon_info->cells[i]=value;
return(MagickTrue);
}
count=WriteRadonCell(radon_info,i*sizeof(*radon_info->cells),
sizeof(*radon_info->cells),(const unsigned char *) &value);
if (count != (ssize_t) sizeof(*radon_info->cells))
return(MagickFalse);
return(MagickTrue);
}
static void RadonProjection(RadonInfo *source_cells,
RadonInfo *destination_cells,const ssize_t sign,size_t *projection)
{
RadonInfo
*swap;
register ssize_t
x;
register RadonInfo
*p,
*q;
size_t
step;
p=source_cells;
q=destination_cells;
for (step=1; step < p->width; step*=2)
{
for (x=0; x < (ssize_t) p->width; x+=2*(ssize_t) step)
{
register ssize_t
i;
ssize_t
y;
unsigned short
cell;
for (i=0; i < (ssize_t) step; i++)
{
for (y=0; y < (ssize_t) (p->height-i-1); y++)
{
cell=GetRadonCell(p,x+i,y);
(void) SetRadonCell(q,x+2*i,y,cell+GetRadonCell(p,x+i+(ssize_t)
step,y+i));
(void) SetRadonCell(q,x+2*i+1,y,cell+GetRadonCell(p,x+i+(ssize_t)
step,y+i+1));
}
for ( ; y < (ssize_t) (p->height-i); y++)
{
cell=GetRadonCell(p,x+i,y);
(void) SetRadonCell(q,x+2*i,y,cell+GetRadonCell(p,x+i+(ssize_t) step,
y+i));
(void) SetRadonCell(q,x+2*i+1,y,cell);
}
for ( ; y < (ssize_t) p->height; y++)
{
cell=GetRadonCell(p,x+i,y);
(void) SetRadonCell(q,x+2*i,y,cell);
(void) SetRadonCell(q,x+2*i+1,y,cell);
}
}
}
swap=p;
p=q;
q=swap;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4)
#endif
for (x=0; x < (ssize_t) p->width; x++)
{
register ssize_t
y;
size_t
sum;
sum=0;
for (y=0; y < (ssize_t) (p->height-1); y++)
{
ssize_t
delta;
delta=GetRadonCell(p,x,y)-(ssize_t) GetRadonCell(p,x,y+1);
sum+=delta*delta;
}
projection[p->width+sign*x-1]=sum;
}
}
static MagickBooleanType RadonTransform(const Image *image,
const double threshold,size_t *projection,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
RadonInfo
*destination_cells,
*source_cells;
register ssize_t
i;
size_t
count,
width;
ssize_t
y;
unsigned char
byte;
unsigned short
bits[256];
for (width=1; width < ((image->columns+7)/8); width<<=1) ;
source_cells=AcquireRadonInfo(image,width,image->rows,exception);
destination_cells=AcquireRadonInfo(image,width,image->rows,exception);
if ((source_cells == (RadonInfo *) NULL) ||
(destination_cells == (RadonInfo *) NULL))
{
if (destination_cells != (RadonInfo *) NULL)
destination_cells=DestroyRadonInfo(destination_cells);
if (source_cells != (RadonInfo *) NULL)
source_cells=DestroyRadonInfo(source_cells);
return(MagickFalse);
}
if (ResetRadonCells(source_cells) == MagickFalse)
{
destination_cells=DestroyRadonInfo(destination_cells);
source_cells=DestroyRadonInfo(source_cells);
return(MagickFalse);
}
for (i=0; i < 256; i++)
{
byte=(unsigned char) i;
for (count=0; byte != 0; byte>>=1)
count+=byte & 0x01;
bits[i]=(unsigned short) count;
}
status=MagickTrue;
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
register ssize_t
i,
x;
size_t
bit,
byte;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) 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) GetRedPixelComponent(p) < threshold) ||
((MagickRealType) GetGreenPixelComponent(p) < threshold) ||
((MagickRealType) GetBluePixelComponent(p) < threshold))
byte|=0x01;
bit++;
if (bit == 8)
{
(void) SetRadonCell(source_cells,--i,y,bits[byte]);
bit=0;
byte=0;
}
p++;
}
if (bit != 0)
{
byte<<=(8-bit);
(void) SetRadonCell(source_cells,--i,y,bits[byte]);
}
}
RadonProjection(source_cells,destination_cells,-1,projection);
(void) ResetRadonCells(source_cells);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
register ssize_t
i,
x;
size_t
bit,
byte;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
bit=0;
byte=0;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (((MagickRealType) GetRedPixelComponent(p) < threshold) ||
((MagickRealType) GetGreenPixelComponent(p) < threshold) ||
((MagickRealType) GetBluePixelComponent(p) < threshold))
byte|=0x01;
bit++;
if (bit == 8)
{
(void) SetRadonCell(source_cells,i++,y,bits[byte]);
bit=0;
byte=0;
}
p++;
}
if (bit != 0)
{
byte<<=(8-bit);
(void) SetRadonCell(source_cells,i++,y,bits[byte]);
}
}
RadonProjection(source_cells,destination_cells,1,projection);
image_view=DestroyCacheView(image_view);
destination_cells=DestroyRadonInfo(destination_cells);
source_cells=DestroyRadonInfo(source_cells);
return(MagickTrue);
}
static void GetImageBackgroundColor(Image *image,const ssize_t offset,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickPixelPacket
background;
MagickRealType
count;
ssize_t
y;
/*
Compute average background color.
*/
if (offset <= 0)
return;
GetMagickPixelPacket(image,&background);
count=0.0;
image_view=AcquireCacheView(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*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 PixelPacket *) NULL)
continue;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x >= offset) && (x < ((ssize_t) image->columns-offset)))
continue;
background.red+=QuantumScale*GetRedPixelComponent(p);
background.green+=QuantumScale*GetGreenPixelComponent(p);
background.blue+=QuantumScale*GetBluePixelComponent(p);
background.opacity+=QuantumScale*GetOpacityPixelComponent(p);
count++;
p++;
}
}
image_view=DestroyCacheView(image_view);
image->background_color.red=ClampToQuantum((MagickRealType) QuantumRange*
background.red/count);
image->background_color.green=ClampToQuantum((MagickRealType) QuantumRange*
background.green/count);
image->background_color.blue=ClampToQuantum((MagickRealType) QuantumRange*
background.blue/count);
image->background_color.opacity=ClampToQuantum((MagickRealType) QuantumRange*
background.opacity/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);
/*
Deskew image.
*/
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod);
degrees=RadiansToDegrees(-atan((double) skew/width/8));
if (image->debug != MagickFalse)
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" Deskew angle: %g",degrees);
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 (artifact == (const char *) NULL)
{
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.
%
*/
static 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;
ssize_t
y;
/*
Initialize rotated image attributes.
*/
assert(image != (Image *) NULL);
page=image->page;
rotations%=4;
if (rotations == 0)
return(CloneImage(image,0,0,MagickTrue,exception));
if ((rotations == 1) || (rotations == 3))
rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
else
rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
/*
Integral rotate the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireCacheView(image);
rotate_view=AcquireCacheView(rotate_image);
switch (rotations)
{
case 0:
{
/*
Rotate 0 degrees.
*/
break;
}
case 1:
{
size_t
tile_height,
tile_width;
ssize_t
tile_y;
/*
Rotate 90 degrees.
*/
GetPixelCacheTileSize(image,&tile_width,&tile_height);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) shared(progress, status) omp_throttle(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;
for (tile_x=0; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
{
MagickBooleanType
sync;
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p;
register IndexPacket
*restrict rotate_indexes;
register ssize_t
y;
register PixelPacket
*restrict q;
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 PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (y=0; y < (ssize_t) width; y++)
{
register const PixelPacket
*restrict tile_pixels;
register ssize_t
x;
q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t)
(rotate_image->columns-(tile_y+height)),y+tile_x,height,
1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
tile_pixels=p+(height-1)*width+y;
for (x=0; x < (ssize_t) height; x++)
{
*q++=(*tile_pixels);
tile_pixels-=width;
}
rotate_indexes=GetCacheViewAuthenticIndexQueue(rotate_view);
if ((indexes != (IndexPacket *) NULL) &&
(rotate_indexes != (IndexPacket *) NULL))
{
register const IndexPacket
*restrict tile_indexes;
tile_indexes=indexes+(height-1)*width+y;
for (x=0; x < (ssize_t) height; x++)
{
*rotate_indexes++=(*tile_indexes);
tile_indexes-=width;
}
}
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:
{
/*
Rotate 180 degrees.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,8) shared(progress,status) omp_throttle(1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p;
register IndexPacket
*restrict rotate_indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
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 PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
rotate_indexes=GetCacheViewAuthenticIndexQueue(rotate_view);
q+=image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
*--q=(*p++);
if ((indexes != (IndexPacket *) NULL) &&
(rotate_indexes != (IndexPacket *) NULL))
for (x=0; x < (ssize_t) image->columns; x++)
SetIndexPixelComponent(rotate_indexes+image->columns-x-1,
GetIndexPixelComponent(indexes+x));
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;
}
}
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);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) shared(progress,status) omp_throttle(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;
for (tile_x=0; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
{
MagickBooleanType
sync;
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p;
register IndexPacket
*restrict rotate_indexes;
register ssize_t
y;
register PixelPacket
*restrict q;
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 PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (y=0; y < (ssize_t) width; y++)
{
register const PixelPacket
*restrict tile_pixels;
register ssize_t
x;
q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t)
(y+rotate_image->rows-(tile_x+width)),height,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
tile_pixels=p+(width-1)-y;
for (x=0; x < (ssize_t) height; x++)
{
*q++=(*tile_pixels);
tile_pixels+=width;
}
rotate_indexes=GetCacheViewAuthenticIndexQueue(rotate_view);
if ((indexes != (IndexPacket *) NULL) &&
(rotate_indexes != (IndexPacket *) NULL))
{
register const IndexPacket
*restrict tile_indexes;
tile_indexes=indexes+(width-1)-y;
for (x=0; x < (ssize_t) height; x++)
{
*rotate_indexes++=(*tile_indexes);
tile_indexes+=width;
}
}
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;
}
}
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 MagickRealType 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 MagickRealType 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 MagickRealType 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;
MagickPixelPacket
background;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
GetMagickPixelPacket(image,&background);
SetMagickPixelPacket(image,&image->background_color,(IndexPacket *) NULL,
&background);
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
/*
X shear image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(progress, status)
#endif
for (y=0; y < (ssize_t) height; y++)
{
MagickPixelPacket
pixel,
source,
destination;
MagickRealType
area,
displacement;
register IndexPacket
*restrict indexes,
*restrict shear_indexes;
register PixelPacket
*restrict p,
*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 == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
p+=x_offset;
indexes+=x_offset;
displacement=degrees*(MagickRealType) (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=(MagickRealType) (displacement-step);
step++;
pixel=background;
GetMagickPixelPacket(image,&source);
GetMagickPixelPacket(image,&destination);
switch (direction)
{
case LEFT:
{
/*
Transfer pixels left-to-right.
*/
if (step > x_offset)
break;
q=p-step;
shear_indexes=indexes-step;
for (i=0; i < (ssize_t) width; i++)
{
if ((x_offset+i) < step)
{
SetMagickPixelPacket(image,++p,++indexes,&pixel);
q++;
shear_indexes++;
continue;
}
SetMagickPixelPacket(image,p,indexes,&source);
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&source,(MagickRealType) GetOpacityPixelComponent(p),area,&destination);
SetPixelPacket(image,&destination,q++,shear_indexes++);
SetMagickPixelPacket(image,p++,indexes++,&pixel);
}
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&background,(MagickRealType) background.opacity,area,&destination);
SetPixelPacket(image,&destination,q++,shear_indexes++);
for (i=0; i < (step-1); i++)
SetPixelPacket(image,&background,q++,shear_indexes++);
break;
}
case RIGHT:
{
/*
Transfer pixels right-to-left.
*/
p+=width;
indexes+=width;
q=p+step;
shear_indexes=indexes+step;
for (i=0; i < (ssize_t) width; i++)
{
p--;
indexes--;
q--;
shear_indexes--;
if ((size_t) (x_offset+width+step-i) >= image->columns)
continue;
SetMagickPixelPacket(image,p,indexes,&source);
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&source,(MagickRealType) GetOpacityPixelComponent(p),area,&destination);
SetPixelPacket(image,&destination,q,shear_indexes);
SetMagickPixelPacket(image,p,indexes,&pixel);
}
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&background,(MagickRealType) background.opacity,area,&destination);
SetPixelPacket(image,&destination,--q,--shear_indexes);
for (i=0; i < (step-1); i++)
SetPixelPacket(image,&background,--q,--shear_indexes);
break;
}
}
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_XShearImage)
#endif
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 MagickRealType 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 MagickRealType 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 MagickRealType 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;
MagickPixelPacket
background;
ssize_t
x;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
GetMagickPixelPacket(image,&background);
SetMagickPixelPacket(image,&image->background_color,(IndexPacket *) NULL,
&background);
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
/*
Y Shear image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(progress, status)
#endif
for (x=0; x < (ssize_t) width; x++)
{
ssize_t
step;
MagickPixelPacket
pixel,
source,
destination;
MagickRealType
area,
displacement;
register IndexPacket
*restrict indexes,
*restrict shear_indexes;
register ssize_t
i;
register PixelPacket
*restrict p,
*restrict q;
ShearDirection
direction;
if (status == MagickFalse)
continue;
p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows,
exception);
if (p == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
p+=y_offset;
indexes+=y_offset;
displacement=degrees*(MagickRealType) (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=(MagickRealType) (displacement-step);
step++;
pixel=background;
GetMagickPixelPacket(image,&source);
GetMagickPixelPacket(image,&destination);
switch (direction)
{
case UP:
{
/*
Transfer pixels top-to-bottom.
*/
if (step > y_offset)
break;
q=p-step;
shear_indexes=indexes-step;
for (i=0; i < (ssize_t) height; i++)
{
if ((y_offset+i) < step)
{
SetMagickPixelPacket(image,++p,++indexes,&pixel);
q++;
shear_indexes++;
continue;
}
SetMagickPixelPacket(image,p,indexes,&source);
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&source,(MagickRealType) GetOpacityPixelComponent(p),area,&destination);
SetPixelPacket(image,&destination,q++,shear_indexes++);
SetMagickPixelPacket(image,p++,indexes++,&pixel);
}
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&background,(MagickRealType) background.opacity,area,&destination);
SetPixelPacket(image,&destination,q++,shear_indexes++);
for (i=0; i < (step-1); i++)
SetPixelPacket(image,&background,q++,shear_indexes++);
break;
}
case DOWN:
{
/*
Transfer pixels bottom-to-top.
*/
p+=height;
indexes+=height;
q=p+step;
shear_indexes=indexes+step;
for (i=0; i < (ssize_t) height; i++)
{
p--;
indexes--;
q--;
shear_indexes--;
if ((size_t) (y_offset+height+step-i) >= image->rows)
continue;
SetMagickPixelPacket(image,p,indexes,&source);
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&source,(MagickRealType) GetOpacityPixelComponent(p),area,&destination);
SetPixelPacket(image,&destination,q,shear_indexes);
SetMagickPixelPacket(image,p,indexes,&pixel);
}
MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity,
&background,(MagickRealType) background.opacity,area,&destination);
SetPixelPacket(image,&destination,--q,--shear_indexes);
for (i=0; i < (step-1); i++)
SetPixelPacket(image,&background,--q,--shear_indexes);
break;
}
}
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_YShearImage)
#endif
proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RotateImage() 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. RotateImage
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% RotateImage() is based on the paper "A Fast Algorithm for General
% Raster Rotatation" by Alan W. Paeth. RotateImage 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 RotateImage method is:
%
% Image *RotateImage(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 *RotateImage(const Image *image,const double degrees,
ExceptionInfo *exception)
{
Image
*integral_image,
*rotate_image;
ssize_t
x_offset,
y_offset;
MagickBooleanType
status;
MagickRealType
angle;
PointInfo
shear;
RectangleInfo
border_info;
size_t
height,
rotations,
width,
y_width;
/*
Adjust rotation angle.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
angle=degrees;
while (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) == MagickFalse)
{
InheritException(exception,&integral_image->exception);
integral_image=DestroyImage(integral_image);
return(integral_image);
}
if (integral_image->matte == MagickFalse)
(void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel);
/*
Compute image size.
*/
width=image->columns;
height=image->rows;
if ((rotations == 1) || (rotations == 3))
{
width=image->rows;
height=image->columns;
}
y_width=width+(ssize_t) floor(fabs(shear.x)*height+0.5);
x_offset=(ssize_t) ceil((double) width+((fabs(shear.y)*height)-width)/2.0-
0.5);
y_offset=(ssize_t) ceil((double) height+((fabs(shear.y)*y_width)-height)/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) x_offset;
border_info.height=(size_t) y_offset;
rotate_image=BorderImage(integral_image,&border_info,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,x_offset,(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,y_width,height,(ssize_t)
(rotate_image->columns-y_width)/2,y_offset,exception);
if (status == MagickFalse)
{
rotate_image=DestroyImage(rotate_image);
return((Image *) NULL);
}
status=XShearImage(rotate_image,shear.x,y_width,rotate_image->rows,(ssize_t)
(rotate_image->columns-y_width)/2,0,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);
if (status == MagickFalse)
{
rotate_image=DestroyImage(rotate_image);
return((Image *) NULL);
}
rotate_image->compose=image->compose;
rotate_image->page.width=0;
rotate_image->page.height=0;
return(rotate_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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;
ssize_t
x_offset,
y_offset;
MagickBooleanType
status;
PointInfo
shear;
RectangleInfo
border_info;
size_t
y_width;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((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) == MagickFalse)
{
InheritException(exception,&integral_image->exception);
integral_image=DestroyImage(integral_image);
return(integral_image);
}
if (integral_image->matte == MagickFalse)
(void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel);
/*
Compute image size.
*/
y_width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5);
x_offset=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)-
image->columns)/2.0-0.5);
y_offset=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*y_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) x_offset;
border_info.height=(size_t) y_offset;
shear_image=BorderImage(integral_image,&border_info,exception);
integral_image=DestroyImage(integral_image);
if (shear_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
/*
Shear the image.
*/
if (shear_image->matte == MagickFalse)
(void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel);
status=XShearImage(shear_image,shear.x,image->columns,image->rows,x_offset,
(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,y_width,image->rows,(ssize_t)
(shear_image->columns-y_width)/2,y_offset,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);
if (status == MagickFalse)
{
shear_image=DestroyImage(shear_image);
return((Image *) NULL);
}
shear_image->compose=image->compose;
shear_image->page.width=0;
shear_image->page.height=0;
return(shear_image);
}
|
bli_cntx_init_a64fx.c | /*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name(s) of the copyright holder(s) nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "blis.h"
#include "bli_a64fx_sector_cache.h"
void bli_cntx_init_a64fx( cntx_t* cntx )
{
blksz_t blkszs[ BLIS_NUM_BLKSZS ];
blksz_t thresh[ BLIS_NUM_THRESH ];
// Set default kernel blocksizes and functions.
bli_cntx_init_a64fx_ref( cntx );
// -------------------------------------------------------------------------
// Update the context with optimized native gemm micro-kernels and
// their storage preferences.
bli_cntx_set_l3_nat_ukrs
(
4,
BLIS_GEMM_UKR, BLIS_FLOAT, bli_sgemm_armsve_asm_2vx10_unindexed, FALSE,
BLIS_GEMM_UKR, BLIS_DOUBLE, bli_dgemm_armsve_asm_2vx10_unindexed, FALSE,
BLIS_GEMM_UKR, BLIS_SCOMPLEX, bli_cgemm_armsve_asm_2vx10_unindexed, FALSE,
BLIS_GEMM_UKR, BLIS_DCOMPLEX, bli_zgemm_armsve_asm_2vx10_unindexed, FALSE,
cntx
);
// Set SVE-512 packing routine.
bli_cntx_set_packm_kers
(
2,
BLIS_PACKM_10XK_KER, BLIS_DOUBLE, bli_dpackm_armsve512_asm_10xk,
// 12xk is not used and disabled for GCC 8-9 compatibility.
// BLIS_PACKM_12XK_KER, BLIS_DOUBLE, bli_dpackm_armsve512_int_12xk,
BLIS_PACKM_16XK_KER, BLIS_DOUBLE, bli_dpackm_armsve512_asm_16xk,
cntx
);
// Initialize level-3 blocksize objects with architecture-specific values.
// s d c z
bli_blksz_init_easy( &blkszs[ BLIS_MR ], 32, 16, 16, 8 );
bli_blksz_init_easy( &blkszs[ BLIS_NR ], 10, 10, 10, 10 );
bli_blksz_init_easy( &blkszs[ BLIS_MC ], 256, 128, 192, 96 );
bli_blksz_init_easy( &blkszs[ BLIS_KC ], 2048, 2048, 1536, 1536 );
bli_blksz_init_easy( &blkszs[ BLIS_NC ], 23040, 26880, 11520, 11760 );
// Update the context with the current architecture's register and cache
// blocksizes (and multiples) for native execution.
bli_cntx_set_blkszs
(
BLIS_NAT, 5,
BLIS_NC, &blkszs[ BLIS_NC ], BLIS_NR,
BLIS_KC, &blkszs[ BLIS_KC ], BLIS_KR,
BLIS_MC, &blkszs[ BLIS_MC ], BLIS_MR,
BLIS_NR, &blkszs[ BLIS_NR ], BLIS_NR,
BLIS_MR, &blkszs[ BLIS_MR ], BLIS_MR,
cntx
);
#if 0
// Initialize sup thresholds with architecture-appropriate values.
// s d c z
bli_blksz_init_easy( &thresh[ BLIS_MT ], -1, 65, -1, -1 );
bli_blksz_init_easy( &thresh[ BLIS_NT ], -1, 65, -1, -1 );
bli_blksz_init_easy( &thresh[ BLIS_KT ], -1, 65, -1, -1 );
// Initialize the context with the sup thresholds.
bli_cntx_set_l3_sup_thresh
(
3,
BLIS_MT, &thresh[ BLIS_MT ],
BLIS_NT, &thresh[ BLIS_NT ],
BLIS_KT, &thresh[ BLIS_KT ],
cntx
);
// Update the context with optimized small/unpacked gemm kernels.
bli_cntx_set_l3_sup_kers
(
4,
BLIS_RRR, BLIS_DOUBLE, bli_dgemmsup_rv_armsve_10x2v_unindexed, TRUE,
BLIS_RCR, BLIS_DOUBLE, bli_dgemmsup_rv_armsve_10x2v_unindexed, TRUE,
BLIS_CCR, BLIS_DOUBLE, bli_dgemmsup_rv_armsve_10x2v_unindexed, TRUE,
BLIS_CCC, BLIS_DOUBLE, bli_dgemmsup_rv_armsve_10x2v_unindexed, TRUE,
cntx
);
// Initialize level-3 sup blocksize objects with architecture-specific
// values.
// s d c z
bli_blksz_init_easy( &blkszs[ BLIS_MR ], -1, 10, -1, -1 );
bli_blksz_init_easy( &blkszs[ BLIS_NR ], -1, 16, -1, -1 );
bli_blksz_init_easy( &blkszs[ BLIS_MC ], -1, 120, -1, -1 );
bli_blksz_init_easy( &blkszs[ BLIS_KC ], -1, 256, -1, -1 );
bli_blksz_init_easy( &blkszs[ BLIS_NC ], -1, 4080, -1, -1 );
// Update the context with the current architecture's register and cache
// blocksizes for small/unpacked level-3 problems.
bli_cntx_set_l3_sup_blkszs
(
5,
BLIS_NC, &blkszs[ BLIS_NC ],
BLIS_KC, &blkszs[ BLIS_KC ],
BLIS_MC, &blkszs[ BLIS_MC ],
BLIS_NR, &blkszs[ BLIS_NR ],
BLIS_MR, &blkszs[ BLIS_MR ],
cntx
);
#endif
// Set A64FX cache sector sizes for each PE/CMG
// SC Fugaku might disable users' setting cache sizes.
#if !defined(CACHE_SECTOR_SIZE_READONLY)
#pragma omp parallel
{
A64FX_SETUP_SECTOR_CACHE_SIZES(A64FX_SCC(0,1,3,0))
A64FX_SETUP_SECTOR_CACHE_SIZES_L2(A64FX_SCC_L2(9,28))
}
#endif
}
|
local_sum-inl.h | // This is an example demonstrating the usage of mshadow ps
#include <cstdio>
// use openmp to launch multiple threads
#include <omp.h>
#include <mshadow/tensor.h>
#include <mshadow-ps/mshadow_ps.h>
// simple util to print result
void Print_(mshadow::Tensor<mshadow::cpu, 2, float> ts) {
for (mshadow::index_t i = 0; i < ts.size(0); ++i) {
for (mshadow::index_t j = 0; j < ts.size(1); ++j) {
printf("%g ", ts[i][j]);
}
printf("\n");
}
}
template<typename xpu>
inline void Print(mshadow::Tensor<xpu, 2, float> ts) {
mshadow::TensorContainer<mshadow::cpu, 2, float> tmp;
tmp.Resize(ts.shape_);
mshadow::Copy(tmp, ts);
Print_(tmp);
}
// this function is runed by specific thread
template<typename xpu>
inline void RunWorkerThread(int devid,
mshadow::ps::ISharedModel<xpu, float> *ps) {
// initialize tensor engine
mshadow::InitTensorEngine<xpu>(devid);
mshadow::Stream<xpu> *stream = mshadow::NewStream<xpu>();
// allocate tensor on xpu
mshadow::TensorContainer<xpu, 2> data(mshadow::Shape2(2, 3));
// set the computation stream to the new allocated stream
// this will make subsequent computation whose target is data
// to use the stream, stream is needed for async execution in GPU
data.set_stream(stream);
// assume these operations sets the content of dataient
data[0] = 1.0f;
data[1] = devid + data[0];
printf("dev%d: before sync, data:\n", devid);
// use print to show result, do not call
// print normally since Copy will block
Print(data);
printf("====================\n");
// intiaialize the key, register the shape on parameter server
ps->InitKey(data[0].shape_, 0, devid);
ps->InitKey(data[1].shape_, 1, devid);
// push data[0] out, for update, or aggregation
// 0 is the key of the data, devid is the current device id
ps->Push(data[0], 0, devid);
// pull request is used to request the data to be copied back
// once computation is done
ps->PullReq(data[0], 0, devid);
// computation can be done here..
// the pull request handler will be overlapped with
// similar as previous call
ps->Push(data[1], 1, devid);
ps->PullReq(data[1], 1, devid);
// more computation can be done here...
// the computation will be overlapped
// PullWait will block until these request finishes
ps->PullWait(0, devid);
ps->PullWait(1, devid);
printf("dev%d: after sync, data:\n", devid);
// use print to show result, do not call
// print normally since Copy will block
Print(data);
printf("====================\n");
mshadow::DeleteStream(stream);
mshadow::ShutdownTensorEngine<xpu>();
}
namespace mshadow {
namespace ps {
// model updater is used when update is happening on server side
// if we only use parameter server for sum aggregation
// this is not needed, but we must declare this function to return NULL
template<>
IModelUpdater<float> *CreateModelUpdater(void) {
return NULL;
}
}
}
template<typename xpu>
inline int Run(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: device list\n"\
"\tfor CPU the device list can be arbitrary\n"\
"\tfor GPU the device list need to be actual device index\n");
return 0;
}
#if MSHADOW_RABIT_PS
rabit::Init(argc, argv);
#endif
// list of device ids
std::vector<int> devs;
// initialization
for (int i = 1; i < argc; ++i) {
// record the device id
devs.push_back(atoi(argv[i]));
}
mshadow::ps::ISharedModel<xpu, float>
*ps = mshadow::ps::CreateSharedModel<xpu, float>("local");
// intiaialize the ps
ps->Init(devs);
// use openmp to launch #devs threads
#pragma omp parallel num_threads(devs.size())
{
int tid = omp_get_thread_num();
RunWorkerThread<xpu>(devs[tid], ps);
}
delete ps;
#if MSHADOW_RABIT_PS
rabit::Finalize();
#endif
return 0;
}
|
convolution_pack1to4.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void convolution_pack1to4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_pack1ton, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt)
{
int w = bottom_blob.w;
int channels = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int maxk = kernel_w * kernel_h;
// kernel offsets
std::vector<int> _space_ofs(maxk);
int* space_ofs = &_space_ofs[0];
{
int p1 = 0;
int p2 = 0;
int gap = w * dilation_h - kernel_w * dilation_w;
for (int i = 0; i < kernel_h; i++)
{
for (int j = 0; j < kernel_w; j++)
{
space_ofs[p1] = p2;
p1++;
p2 += dilation_w;
}
p2 += gap;
}
}
const float* bias_data_ptr = bias_data;
// num_output
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* outptr = top_blob.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
v4f32 _sum = (v4f32)__msa_fill_w(0);
if (bias_data_ptr)
{
_sum = (v4f32)__msa_ld_w(bias_data_ptr + p * 4, 0);
}
const float* kptr = (const float*)weight_data_pack1ton + maxk * channels * p * 4;
// channels
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob.channel(q);
const float* sptr = m.row(i * stride_h) + j * stride_w;
for (int k = 0; k < maxk; k++) // 29.23
{
v4f32 _val = __msa_fill_w_f32(sptr[space_ofs[k]]);
v4f32 _w = (v4f32)__msa_ld_w(kptr, 0);
_sum = __msa_fmadd_w(_sum, _val, _w);
kptr += 4;
}
}
_sum = activation_ps(_sum, activation_type, activation_params);
__msa_st_w((v4i32)_sum, outptr + j * 4, 0);
}
outptr += outw * 4;
}
}
}
|
dragonfly3_fmt_plug.c | /*
* This file is part of John the Ripper password cracker,
* based on rawSHA256_fmt.c code
*
* This software is Copyright (c) 2012 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.
*
* The DragonFly BSD 2.10.1-REL crypt-sha2 hashes are seriously broken. See
* http://www.openwall.com/lists/john-dev/2012/01/16/1
*
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_dragonfly3_32;
extern struct fmt_main fmt_dragonfly3_64;
#elif FMT_REGISTERS_H
john_register_one(&fmt_dragonfly3_32);
john_register_one(&fmt_dragonfly3_64);
#else
#include "sha2.h"
#include <string.h>
#include "arch.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#ifdef _OPENMP
#ifndef OMP_SCALE
#define OMP_SCALE 4096 // tuned on K8-dual HT
#endif
#include <omp.h>
#endif
#include "memdbg.h"
#define FORMAT_LABEL_32 "dragonfly3-32"
#define FORMAT_LABEL_64 "dragonfly3-64"
#define FORMAT_NAME_32 "DragonFly BSD $3$ w/ bug, 32-bit"
#define FORMAT_NAME_64 "DragonFly BSD $3$ w/ bug, 64-bit"
#define ALGORITHM_NAME "SHA256 32/" ARCH_BITS_STR " " SHA2_LIB
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 125
#define CIPHERTEXT_LENGTH 44
#define BINARY_SIZE 32
#define BINARY_ALIGN 4
#define SALT_SIZE_32 (1+4+8) // 1st char is length
#define SALT_SIZE_64 (1+8+8)
#define SALT_ALIGN 1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static struct fmt_tests tests_32[] = {
{"$3$z$EBG66iBCGfUfENOfqLUH/r9xQxI1cG373/hRop6j.oWs", "magnum"},
{"$3$f6daU5$Xf/u8pKp.sb4VCLKz7tTZMUKJ3J4oOfZgUSHYOFL.M0n", ""},
{"$3$PNPA2tJ$ppD4bXqPMYFVdYVYrxXGMWeYB6Xv8e6jmXbvrB5V.okl", "password"},
{"$3$jWhDSrS$bad..Dy7UAyabPyfrEi3fgQ2qtT.5fE7C5EMNo/n.Qk5", "John the Ripper"},
{"$3$SSYEHO$hkuDmUQHT2Tr0.ai.lUVyb9bCC875Up.CZVa6UJZ.Muv", "DragonFly BSD"},
{"$3$pomO$a2ltqo.LlUSt1DG68sv2FZOdLcul0gYQ3xmn6z0G.I6Y", "123"},
{"$3$F$8Asqp58WwQ3WDMhaR3yQMSJGdCtpBqckemkCSNnJ.gRr", "12345678"},
{NULL}
};
static struct fmt_tests tests_64[] = {
{"$3$z$sNV7KLtLxvJRsj2MfBtGZFuzXP3CECITaFq/rvsy.Y.Q", "magnum"},
{"$3$f6daU5$eV2SX9vUHTMsoy3Ic7cWiQ4mOxyuyenGjYQWkJmy.AF3", ""},
{"$3$PNPA2tJ$GvXjg6zSge3YDh5I35JlYZHoQS2r0/.vn36fQzSY.A0d", "password"},
{"$3$jWhDSrS$5yBH7KFPmsg.PhPeDMj1MY4fv9061zdbYumPe2Ve.Y5J", "John the Ripper"},
{"$3$SSYEHO$AMYLyanRYs8F2U07FsBrSFuOIygJ4kgqvpBB17BI.61N", "DragonFly BSD"},
{"$3$e$TzMK1ePmjnZI/YbGes/1PAKqbj8aOV31Hf8Tz9es.kkq", "123"},
{"$3$XcMa$idKoaBQXdRlhfJFDjnV0jDryW/nEBAGXONyzJvnH.cR3", "12345678"},
{NULL}
};
static int (*saved_len);
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_out)
[(BINARY_SIZE + sizeof(ARCH_WORD_32) - 1) / sizeof(ARCH_WORD_32)];
static char *cur_salt;
static int salt_len;
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
int omp_t;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_len = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_len));
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
MEM_FREE(saved_len);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *pos, *start;
if (strncmp(ciphertext, "$3$", 3))
return 0;
ciphertext += 3;
for (pos = ciphertext; *pos && *pos != '$'; pos++);
if (!*pos || pos < ciphertext || pos > &ciphertext[8]) return 0;
start = ++pos;
while (atoi64[ARCH_INDEX(*pos)] != 0x7F) pos++;
if (*pos || pos - start != CIPHERTEXT_LENGTH) return 0;
return 1;
}
#define TO_BINARY(b1, b2, b3) \
value = (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | \
((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6) | \
((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[2])] << 12) | \
((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[3])] << 18); \
pos += 4; \
out[b1] = value >> 16; \
out[b2] = value >> 8; \
out[b3] = value;
static void *get_binary(char *ciphertext)
{
static ARCH_WORD_32 outbuf[BINARY_SIZE/4];
ARCH_WORD_32 value;
char *pos;
unsigned char *out = (unsigned char*)outbuf;
int i;
pos = strrchr(ciphertext, '$') + 1;
for (i = 0; i < 10; i++) {
TO_BINARY(i, i + 11, i + 21);
}
value = (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] |
((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6) |
((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[2])] << 12) |
((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[3])] << 18);
out[10] = value >> 16;
out[31] = value >> 8;
return (void *)out;
}
static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; }
static void set_key(char *key, int index)
{
int len = strlen(key);
saved_len[index] = len;
if (len > PLAINTEXT_LENGTH)
len = saved_len[index] = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, len);
}
static char *get_key(int index)
{
saved_key[index][saved_len[index]] = 0;
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
{
SHA256_CTX ctx;
SHA256_Init(&ctx);
/* First the password */
SHA256_Update(&ctx, saved_key[index], saved_len[index]);
/* Then the salt, including the $3$ magic */
SHA256_Update(&ctx, cur_salt, salt_len);
SHA256_Final((unsigned char*)crypt_out[index], &ctx);
}
return count;
}
static void set_salt(void *salt)
{
salt_len = (int)*(char*)salt;
cur_salt = (char*)salt + 1;
}
// For 32-bit version of the bug, our magic is "$3$\0" len 4
static void *get_salt_32(char *ciphertext)
{
static char *out;
int len;
if (!out) out = mem_alloc_tiny(SALT_SIZE_32, MEM_ALIGN_WORD);
memset(out, 0, SALT_SIZE_32);
ciphertext += 3;
strcpy(&out[1], "$3$");
for (len = 0; ciphertext[len] != '$'; len++);
memcpy(&out[5], ciphertext, len);
out[0] = len + 4;
return out;
}
// For 64-bit version of the bug, our magic is "$3$\0sha5" len 8
static void *get_salt_64(char *ciphertext)
{
static char *out;
int len;
if (!out) out = mem_alloc_tiny(SALT_SIZE_64, MEM_ALIGN_WORD);
memset(out, 0, SALT_SIZE_64);
ciphertext += 3;
memcpy(&out[1], "$3$\0sha5", 8);
for (len = 0; ciphertext[len] != '$'; len++);
memcpy(&out[9], ciphertext, len);
out[0] = len + 8;
return out;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
#ifdef _OPENMP
for (; index < count; index++)
#endif
if (!memcmp(binary, crypt_out[index], ARCH_SIZE))
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
// Public domain hash function by DJ Bernstein
static int salt_hash(void *salt)
{
unsigned char *s = (unsigned char*)salt + 1;
unsigned int hash = 5381;
unsigned int i;
for (i = 0; i < *(unsigned char*)salt; i++)
hash = ((hash << 5) + hash) ^ s[i];
return hash & (SALT_HASH_SIZE - 1);
}
struct fmt_main fmt_dragonfly3_32 = {
{
FORMAT_LABEL_32,
FORMAT_NAME_32,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE_32,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD,
{ NULL },
tests_32
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt_32,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_dragonfly3_64 = {
{
FORMAT_LABEL_64,
FORMAT_NAME_64,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE_64,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD,
{ NULL },
tests_64
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt_64,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
simd_metadata.c | // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=X86
// RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -target-feature +avx -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=X86-AVX
// RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -target-feature +avx512f -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=X86-AVX512
// RUN: %clang_cc1 -fopenmp -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=X86
// RUN: %clang_cc1 -fopenmp -triple i386-unknown-unknown -target-feature +avx -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=X86-AVX
// RUN: %clang_cc1 -fopenmp -triple i386-unknown-unknown -target-feature +avx512f -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=X86-AVX512
// RUN: %clang_cc1 -fopenmp -triple powerpc64-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=PPC
// RUN: %clang_cc1 -fopenmp -triple powerpc64-unknown-unknown -target-abi elfv1-qpx -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=PPC-QPX
void h1(float *c, float *a, double b[], int size)
{
// CHECK-LABEL: define void @h1
int t = 0;
#pragma omp simd safelen(16) linear(t) aligned(c:32) aligned(a,b)
// CHECK: [[C_PTRINT:%.+]] = ptrtoint
// CHECK-NEXT: [[C_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[C_PTRINT]], 31
// CHECK-NEXT: [[C_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[C_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[C_MASKCOND]])
// CHECK: [[A_PTRINT:%.+]] = ptrtoint
// X86-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// X86-AVX-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 31
// X86-AVX512-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 63
// PPC-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// PPC-QPX-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// CHECK-NEXT: [[A_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[A_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[A_MASKCOND]])
// CHECK: [[B_PTRINT:%.+]] = ptrtoint
// X86-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 15
// X86-AVX-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 31
// X86-AVX512-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 63
// PPC-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 15
// PPC-QPX-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 31
// CHECK-NEXT: [[B_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[B_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[B_MASKCOND]])
for (int i = 0; i < size; ++i) {
c[i] = a[i] * a[i] + b[i] * b[t];
++t;
}
// do not emit parallel_loop_access metadata due to usage of safelen clause.
// CHECK-NOT: store float {{.+}}, float* {{.+}}, align {{.+}}, !llvm.mem.parallel_loop_access {{![0-9]+}}
#pragma omp simd safelen(16) linear(t) aligned(c:32) aligned(a,b) simdlen(8)
// CHECK: [[C_PTRINT:%.+]] = ptrtoint
// CHECK-NEXT: [[C_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[C_PTRINT]], 31
// CHECK-NEXT: [[C_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[C_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[C_MASKCOND]])
// CHECK: [[A_PTRINT:%.+]] = ptrtoint
// X86-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// X86-AVX-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 31
// X86-AVX512-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 63
// PPC-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// PPC-QPX-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// CHECK-NEXT: [[A_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[A_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[A_MASKCOND]])
// CHECK: [[B_PTRINT:%.+]] = ptrtoint
// X86-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 15
// X86-AVX-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 31
// X86-AVX512-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 63
// PPC-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 15
// PPC-QPX-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 31
// CHECK-NEXT: [[B_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[B_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[B_MASKCOND]])
for (int i = 0; i < size; ++i) {
c[i] = a[i] * a[i] + b[i] * b[t];
++t;
}
// do not emit parallel_loop_access metadata due to usage of safelen clause.
// CHECK-NOT: store float {{.+}}, float* {{.+}}, align {{.+}}, !llvm.mem.parallel_loop_access {{![0-9]+}}
#pragma omp simd linear(t) aligned(c:32) aligned(a,b) simdlen(8)
// CHECK: [[C_PTRINT:%.+]] = ptrtoint
// CHECK-NEXT: [[C_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[C_PTRINT]], 31
// CHECK-NEXT: [[C_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[C_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[C_MASKCOND]])
// CHECK: [[A_PTRINT:%.+]] = ptrtoint
// X86-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// X86-AVX-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 31
// X86-AVX512-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 63
// PPC-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// PPC-QPX-NEXT: [[A_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[A_PTRINT]], 15
// CHECK-NEXT: [[A_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[A_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[A_MASKCOND]])
// CHECK: [[B_PTRINT:%.+]] = ptrtoint
// X86-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 15
// X86-AVX-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 31
// X86-AVX512-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 63
// PPC-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 15
// PPC-QPX-NEXT: [[B_MASKEDPTR:%.+]] = and i{{[0-9]+}} [[B_PTRINT]], 31
// CHECK-NEXT: [[B_MASKCOND:%.+]] = icmp eq i{{[0-9]+}} [[B_MASKEDPTR]], 0
// CHECK-NEXT: call void @llvm.assume(i1 [[B_MASKCOND]])
for (int i = 0; i < size; ++i) {
c[i] = a[i] * a[i] + b[i] * b[t];
++t;
// CHECK: store float {{.+}}, float* {{.+}}, align {{.+}}, !llvm.mem.parallel_loop_access {{![0-9]+}}
}
}
void h2(float *c, float *a, float *b, int size)
{
// CHECK-LABEL: define void @h2
int t = 0;
#pragma omp simd linear(t)
for (int i = 0; i < size; ++i) {
c[i] = a[i] * a[i] + b[i] * b[t];
++t;
// CHECK: store float {{.+}}, float* {{.+}}, align {{.+}}, !llvm.mem.parallel_loop_access [[LOOP_H2_HEADER:![0-9]+]]
}
}
void h3(float *c, float *a, float *b, int size)
{
// CHECK-LABEL: define void @h3
#pragma omp simd
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
c[j*i] = a[i] * b[j];
}
}
// do not emit parallel_loop_access for nested loop.
// CHECK-NOT: store float {{.+}}, float* {{.+}}, align {{.+}}, !llvm.mem.parallel_loop_access {{![0-9]+}}
}
// Metadata for h1:
// CHECK: [[LOOP_H1_HEADER:![0-9]+]] = distinct !{[[LOOP_H1_HEADER]], [[LOOP_WIDTH_16:![0-9]+]], [[LOOP_VEC_ENABLE:![0-9]+]]}
// CHECK: [[LOOP_WIDTH_16]] = !{!"llvm.loop.vectorize.width", i32 16}
// CHECK: [[LOOP_VEC_ENABLE]] = !{!"llvm.loop.vectorize.enable", i1 true}
// CHECK: [[LOOP_H1_HEADER:![0-9]+]] = distinct !{[[LOOP_H1_HEADER]], [[LOOP_WIDTH_8:![0-9]+]], [[LOOP_VEC_ENABLE]]}
// CHECK: [[LOOP_WIDTH_8]] = !{!"llvm.loop.vectorize.width", i32 8}
// CHECK: [[LOOP_H1_HEADER:![0-9]+]] = distinct !{[[LOOP_H1_HEADER]], [[LOOP_WIDTH_8]], [[LOOP_VEC_ENABLE]]}
//
// Metadata for h2:
// CHECK: [[LOOP_H2_HEADER]] = distinct !{[[LOOP_H2_HEADER]], [[LOOP_VEC_ENABLE]]}
//
// Metadata for h3:
// CHECK: [[LOOP_H3_HEADER:![0-9]+]] = distinct !{[[LOOP_H3_HEADER]], [[LOOP_VEC_ENABLE]]}
//
|
kmp_taskloop.c | // RUN: %libomp-compile-and-run
// RUN: %libomp-compile && env KMP_TASKLOOP_MIN_TASKS=1 %libomp-run
// REQUIRES: openmp-4.5
#include <stdio.h>
#include <omp.h>
#include "omp_my_sleep.h"
#define N 4
#define GRAIN 10
#define STRIDE 3
// globals
int th_counter[N];
int counter;
// Compiler-generated code (emulation)
typedef struct ident {
void* dummy;
} ident_t;
typedef struct shar {
int(*pth_counter)[N];
int *pcounter;
int *pj;
} *pshareds;
typedef struct task {
pshareds shareds;
int(* routine)(int,struct task*);
int part_id;
// privates:
unsigned long long lb; // library always uses ULONG
unsigned long long ub;
int st;
int last;
int i;
int j;
int th;
} *ptask, kmp_task_t;
typedef int(* task_entry_t)( int, ptask );
void
__task_dup_entry(ptask task_dst, ptask task_src, int lastpriv)
{
// setup lastprivate flag
task_dst->last = lastpriv;
// could be constructor calls here...
}
// OpenMP RTL interfaces
typedef unsigned long long kmp_uint64;
typedef long long kmp_int64;
#ifdef __cplusplus
extern "C" {
#endif
void
__kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int if_val,
kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
int nogroup, int sched, kmp_int64 grainsize, void *task_dup );
ptask
__kmpc_omp_task_alloc( ident_t *loc, int gtid, int flags,
size_t sizeof_kmp_task_t, size_t sizeof_shareds,
task_entry_t task_entry );
void __kmpc_atomic_fixed4_add(void *id_ref, int gtid, int * lhs, int rhs);
int __kmpc_global_thread_num(void *id_ref);
#ifdef __cplusplus
}
#endif
// User's code
int task_entry(int gtid, ptask task)
{
pshareds pshar = task->shareds;
for( task->i = task->lb; task->i <= (int)task->ub; task->i += task->st ) {
task->th = omp_get_thread_num();
__kmpc_atomic_fixed4_add(NULL,gtid,pshar->pcounter,1);
__kmpc_atomic_fixed4_add(NULL,gtid,&((*pshar->pth_counter)[task->th]),1);
task->j = task->i;
}
my_sleep( 0.1 ); // sleep 100 ms in order to allow other threads to steal tasks
if( task->last ) {
*(pshar->pj) = task->j; // lastprivate
}
return 0;
}
int main()
{
int i, j, gtid = __kmpc_global_thread_num(NULL);
ptask task;
pshareds psh;
omp_set_dynamic(0);
counter = 0;
for( i=0; i<N; ++i )
th_counter[i] = 0;
#pragma omp parallel num_threads(N)
{
#pragma omp master
{
int gtid = __kmpc_global_thread_num(NULL);
/*
* This is what the OpenMP runtime calls correspond to:
#pragma omp taskloop num_tasks(N) lastprivate(j)
for( i=0; i<N*GRAIN*STRIDE-1; i+=STRIDE )
{
int th = omp_get_thread_num();
#pragma omp atomic
counter++;
#pragma omp atomic
th_counter[th]++;
j = i;
}
*/
task = __kmpc_omp_task_alloc(NULL,gtid,1,sizeof(struct task),sizeof(struct shar),&task_entry);
psh = task->shareds;
psh->pth_counter = &th_counter;
psh->pcounter = &counter;
psh->pj = &j;
task->lb = 0;
task->ub = N*GRAIN*STRIDE-2;
task->st = STRIDE;
__kmpc_taskloop(
NULL, // location
gtid, // gtid
task, // task structure
1, // if clause value
&task->lb, // lower bound
&task->ub, // upper bound
STRIDE, // loop increment
0, // 1 if nogroup specified
2, // schedule type: 0-none, 1-grainsize, 2-num_tasks
N, // schedule value (ignored for type 0)
(void*)&__task_dup_entry // tasks duplication routine
);
} // end master
} // end parallel
// check results
if( j != N*GRAIN*STRIDE-STRIDE ) {
printf("Error in lastprivate, %d != %d\n",j,N*GRAIN*STRIDE-STRIDE);
return 1;
}
if( counter != N*GRAIN ) {
printf("Error, counter %d != %d\n",counter,N*GRAIN);
return 1;
}
for( i=0; i<N; ++i ) {
if( th_counter[i] % GRAIN ) {
printf("Error, th_counter[%d] = %d\n",i,th_counter[i]);
return 1;
}
}
printf("passed\n");
return 0;
}
|
lap.h | #include <cassert>
#include <cstdio>
#include <limits>
#include <memory>
#ifdef __GNUC__
#define always_inline __attribute__((always_inline)) inline
#define restrict __restrict__
#elif _WIN32
#define always_inline __forceinline
#define restrict __restrict
#else
#define always_inline inline
#define restrict
#endif
template <typename idx, typename cost>
always_inline std::tuple<cost, cost, idx, idx>
find_umins_plain(
idx dim, idx i, const cost *restrict assign_cost,
const cost *restrict v) {
const cost *local_cost = &assign_cost[i * dim];
cost umin = local_cost[0] - v[0];
idx j1 = 0;
idx j2 = -1;
cost usubmin = std::numeric_limits<cost>::max();
for (idx j = 1; j < dim; j++) {
cost h = local_cost[j] - v[j];
if (h < usubmin) {
if (h >= umin) {
usubmin = h;
j2 = j;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = j;
}
}
}
return std::make_tuple(umin, usubmin, j1, j2);
}
// MSVC++ has an awful AVX2 support which does not allow to compile the code
#if defined(__AVX2__) && !defined(_WIN32)
#include <immintrin.h>
#define FLOAT_MIN_DIM 64
#define DOUBLE_MIN_DIM 100000 // 64-bit code is actually always slower
template <typename idx>
always_inline std::tuple<float, float, idx, idx>
find_umins(
idx dim, idx i, const float *restrict assign_cost,
const float *restrict v) {
if (dim < FLOAT_MIN_DIM) {
return find_umins_plain(dim, i, assign_cost, v);
}
const float *local_cost = assign_cost + i * dim;
__m256i idxvec = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
__m256i j1vec = _mm256_set1_epi32(-1), j2vec = _mm256_set1_epi32(-1);
__m256 uminvec = _mm256_set1_ps(std::numeric_limits<float>::max()),
usubminvec = _mm256_set1_ps(std::numeric_limits<float>::max());
for (idx j = 0; j < dim - 7; j += 8) {
__m256 acvec = _mm256_loadu_ps(local_cost + j);
__m256 vvec = _mm256_loadu_ps(v + j);
__m256 h = _mm256_sub_ps(acvec, vvec);
__m256 cmp = _mm256_cmp_ps(h, uminvec, _CMP_LE_OQ);
usubminvec = _mm256_blendv_ps(usubminvec, uminvec, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, j1vec, reinterpret_cast<__m256i>(cmp));
uminvec = _mm256_blendv_ps(uminvec, h, cmp);
j1vec = _mm256_blendv_epi8(
j1vec, idxvec, reinterpret_cast<__m256i>(cmp));
cmp = _mm256_andnot_ps(cmp, _mm256_cmp_ps(h, usubminvec, _CMP_LT_OQ));
usubminvec = _mm256_blendv_ps(usubminvec, h, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, idxvec, reinterpret_cast<__m256i>(cmp));
idxvec = _mm256_add_epi32(idxvec, _mm256_set1_epi32(8));
}
alignas(__m256) float uminmem[8], usubminmem[8];
alignas(__m256) int32_t j1mem[8], j2mem[8];
_mm256_store_ps(uminmem, uminvec);
_mm256_store_ps(usubminmem, usubminvec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j1mem), j1vec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j2mem), j2vec);
idx j1 = -1, j2 = -1;
float umin = std::numeric_limits<float>::max(),
usubmin = std::numeric_limits<float>::max();
for (int vi = 0; vi < 8; vi++) {
float h = uminmem[vi];
if (h < usubmin) {
idx jnew = j1mem[vi];
if (h >= umin) {
usubmin = h;
j2 = jnew;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = jnew;
}
}
}
for (int vi = 0; vi < 8; vi++) {
float h = usubminmem[vi];
if (h < usubmin) {
usubmin = h;
j2 = j2mem[vi];
}
}
for (idx j = dim & 0xFFFFFFF8u; j < dim; j++) {
float h = local_cost[j] - v[j];
if (h < usubmin) {
if (h >= umin) {
usubmin = h;
j2 = j;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = j;
}
}
}
return std::make_tuple(umin, usubmin, j1, j2);
}
template <typename idx>
always_inline std::tuple<double, double, idx, idx>
find_umins(
idx dim, idx i, const double *restrict assign_cost,
const double *restrict v) {
if (dim < DOUBLE_MIN_DIM) {
return find_umins_plain(dim, i, assign_cost, v);
}
const double *local_cost = assign_cost + i * dim;
__m256i idxvec = _mm256_setr_epi64x(0, 1, 2, 3);
__m256i j1vec = _mm256_set1_epi64x(-1), j2vec = _mm256_set1_epi64x(-1);
__m256d uminvec = _mm256_set1_pd(std::numeric_limits<double>::max()),
usubminvec = _mm256_set1_pd(std::numeric_limits<double>::max());
for (idx j = 0; j < dim - 3; j += 4) {
__m256d acvec = _mm256_loadu_pd(local_cost + j);
__m256d vvec = _mm256_loadu_pd(v + j);
__m256d h = _mm256_sub_pd(acvec, vvec);
__m256d cmp = _mm256_cmp_pd(h, uminvec, _CMP_LE_OQ);
usubminvec = _mm256_blendv_pd(usubminvec, uminvec, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, j1vec, reinterpret_cast<__m256i>(cmp));
uminvec = _mm256_blendv_pd(uminvec, h, cmp);
j1vec = _mm256_blendv_epi8(
j1vec, idxvec, reinterpret_cast<__m256i>(cmp));
cmp = _mm256_andnot_pd(cmp, _mm256_cmp_pd(h, usubminvec, _CMP_LT_OQ));
usubminvec = _mm256_blendv_pd(usubminvec, h, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, idxvec, reinterpret_cast<__m256i>(cmp));
idxvec = _mm256_add_epi64(idxvec, _mm256_set1_epi64x(4));
}
alignas(__m256d) double uminmem[4], usubminmem[4];
alignas(__m256d) int64_t j1mem[4], j2mem[4];
_mm256_store_pd(uminmem, uminvec);
_mm256_store_pd(usubminmem, usubminvec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j1mem), j1vec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j2mem), j2vec);
idx j1 = -1, j2 = -1;
double umin = std::numeric_limits<double>::max(),
usubmin = std::numeric_limits<double>::max();
for (int vi = 0; vi < 4; vi++) {
double h = uminmem[vi];
if (h < usubmin) {
idx jnew = j1mem[vi];
if (h >= umin) {
usubmin = h;
j2 = jnew;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = jnew;
}
}
}
for (int vi = 0; vi < 4; vi++) {
double h = usubminmem[vi];
if (h < usubmin) {
usubmin = h;
j2 = j2mem[vi];
}
}
for (idx j = dim & 0xFFFFFFFCu; j < dim; j++) {
double h = local_cost[j] - v[j];
if (h < usubmin) {
if (h >= umin) {
usubmin = h;
j2 = j;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = j;
}
}
}
return std::make_tuple(umin, usubmin, j1, j2);
}
#else // __AVX__
#define find_umins find_umins_plain
#endif // __AVX__
/// @brief Jonker-Volgenant algorithm.
/// @param dim in problem size
/// @param assign_cost in cost matrix
/// @param verbose in indicates whether to report the progress to stdout
/// @param rowsol out column assigned to row in solution / size dim
/// @param colsol out row assigned to column in solution / size dim
/// @param u out dual variables, row reduction numbers / size dim
/// @param v out dual variables, column reduction numbers / size dim
/// @return achieved minimum assignment cost
template <typename idx, typename cost>
cost lap(int dim, const cost *restrict assign_cost, bool verbose,
idx *restrict rowsol, idx *restrict colsol,
cost *restrict u, cost *restrict v) {
auto free = std::unique_ptr<idx[]>(new idx[dim]); // list of unassigned rows.
auto collist = std::unique_ptr<idx[]>(new idx[dim]); // list of columns to be scanned in various ways.
auto matches = std::unique_ptr<idx[]>(new idx[dim]); // counts how many times a row could be assigned.
auto d = std::unique_ptr<cost[]>(new cost[dim]); // 'cost-distance' in augmenting path calculation.
auto pred = std::unique_ptr<idx[]>(new idx[dim]); // row-predecessor of column in augmenting/alternating path.
// init how many times a row will be assigned in the column reduction.
#if _OPENMP >= 201307
#pragma omp simd
#endif
for (idx i = 0; i < dim; i++) {
matches[i] = 0;
}
// COLUMN REDUCTION
for (idx j = dim - 1; j >= 0; j--) { // reverse order gives better results.
// find minimum cost over rows.
cost min = assign_cost[j];
idx imin = 0;
for (idx i = 1; i < dim; i++) {
const cost *local_cost = &assign_cost[i * dim];
if (local_cost[j] < min) {
min = local_cost[j];
imin = i;
}
}
v[j] = min;
if (++matches[imin] == 1) {
// init assignment if minimum row assigned for first time.
rowsol[imin] = j;
colsol[j] = imin;
} else {
colsol[j] = -1; // row already assigned, column not assigned.
}
}
if (verbose) {
printf("lapjv: COLUMN REDUCTION finished\n");
}
// REDUCTION TRANSFER
idx numfree = 0;
for (idx i = 0; i < dim; i++) {
const cost *local_cost = &assign_cost[i * dim];
if (matches[i] == 0) { // fill list of unassigned 'free' rows.
free[numfree++] = i;
} else if (matches[i] == 1) { // transfer reduction from rows that are assigned once.
idx j1 = rowsol[i];
cost min = std::numeric_limits<cost>::max();
for (idx j = 0; j < dim; j++) {
if (j != j1) {
if (local_cost[j] - v[j] < min) {
min = local_cost[j] - v[j];
}
}
}
v[j1] = v[j1] - min;
}
}
if (verbose) {
printf("lapjv: REDUCTION TRANSFER finished\n");
}
// AUGMENTING ROW REDUCTION
for (int loopcnt = 0; loopcnt < 2; loopcnt++) { // loop to be done twice.
// scan all free rows.
// in some cases, a free row may be replaced with another one to be scanned next.
idx k = 0;
idx prevnumfree = numfree;
numfree = 0; // start list of rows still free after augmenting row reduction.
while (k < prevnumfree) {
idx i = free[k++];
// find minimum and second minimum reduced cost over columns.
cost umin, usubmin;
idx j1, j2;
std::tie(umin, usubmin, j1, j2) = find_umins(dim, i, assign_cost, v);
idx i0 = colsol[j1];
cost vj1_new = v[j1] - (usubmin - umin);
bool vj1_lowers = vj1_new < v[j1]; // the trick to eliminate the epsilon bug
if (vj1_lowers) {
// change the reduction of the minimum column to increase the minimum
// reduced cost in the row to the subminimum.
v[j1] = vj1_new;
} else if (i0 >= 0) { // minimum and subminimum equal.
// minimum column j1 is assigned.
// swap columns j1 and j2, as j2 may be unassigned.
j1 = j2;
i0 = colsol[j2];
}
// (re-)assign i to j1, possibly de-assigning an i0.
rowsol[i] = j1;
colsol[j1] = i;
if (i0 >= 0) { // minimum column j1 assigned earlier.
if (vj1_lowers) {
// put in current k, and go back to that k.
// continue augmenting path i - j1 with i0.
free[--k] = i0;
} else {
// no further augmenting reduction possible.
// store i0 in list of free rows for next phase.
free[numfree++] = i0;
}
}
}
if (verbose) {
printf("lapjv: AUGMENTING ROW REDUCTION %d / %d\n", loopcnt + 1, 2);
}
} // for loopcnt
// AUGMENT SOLUTION for each free row.
for (idx f = 0; f < numfree; f++) {
idx endofpath;
idx freerow = free[f]; // start row of augmenting path.
if (verbose) {
printf("lapjv: AUGMENT SOLUTION row %d [%d / %d]\n",
freerow, f + 1, numfree);
}
// Dijkstra shortest path algorithm.
// runs until unassigned column added to shortest path tree.
#if _OPENMP >= 201307
#pragma omp simd
#endif
for (idx j = 0; j < dim; j++) {
d[j] = assign_cost[freerow * dim + j] - v[j];
pred[j] = freerow;
collist[j] = j; // init column list.
}
idx low = 0; // columns in 0..low-1 are ready, now none.
idx up = 0; // columns in low..up-1 are to be scanned for current minimum, now none.
// columns in up..dim-1 are to be considered later to find new minimum,
// at this stage the list simply contains all columns
bool unassigned_found = false;
// initialized in the first iteration: low == up == 0
idx last = 0;
cost min = 0;
do {
if (up == low) { // no more columns to be scanned for current minimum.
last = low - 1;
// scan columns for up..dim-1 to find all indices for which new minimum occurs.
// store these indices between low..up-1 (increasing up).
min = d[collist[up++]];
for (idx k = up; k < dim; k++) {
idx j = collist[k];
cost h = d[j];
if (h <= min) {
if (h < min) { // new minimum.
up = low; // restart list at index low.
min = h;
}
// new index with same minimum, put on undex up, and extend list.
collist[k] = collist[up];
collist[up++] = j;
}
}
// check if any of the minimum columns happens to be unassigned.
// if so, we have an augmenting path right away.
for (idx k = low; k < up; k++) {
if (colsol[collist[k]] < 0) {
endofpath = collist[k];
unassigned_found = true;
break;
}
}
}
if (!unassigned_found) {
// update 'distances' between freerow and all unscanned columns, via next scanned column.
idx j1 = collist[low];
low++;
idx i = colsol[j1];
const cost *local_cost = &assign_cost[i * dim];
cost h = local_cost[j1] - v[j1] - min;
for (idx k = up; k < dim; k++) {
idx j = collist[k];
cost v2 = local_cost[j] - v[j] - h;
if (v2 < d[j]) {
pred[j] = i;
if (v2 == min) { // new column found at same minimum value
if (colsol[j] < 0) {
// if unassigned, shortest augmenting path is complete.
endofpath = j;
unassigned_found = true;
break;
} else { // else add to list to be scanned right away.
collist[k] = collist[up];
collist[up++] = j;
}
}
d[j] = v2;
}
}
}
} while (!unassigned_found);
// update column prices.
#if _OPENMP >= 201307
#pragma omp simd
#endif
for (idx k = 0; k <= last; k++) {
idx j1 = collist[k];
v[j1] = v[j1] + d[j1] - min;
}
// reset row and column assignments along the alternating path.
{
idx i;
do {
i = pred[endofpath];
colsol[endofpath] = i;
idx j1 = endofpath;
endofpath = rowsol[i];
rowsol[i] = j1;
} while (i != freerow);
}
}
if (verbose) {
printf("lapjv: AUGMENT SOLUTION finished\n");
}
// calculate optimal cost.
cost lapcost = 0;
#if _OPENMP >= 201307
#pragma omp simd reduction(+:lapcost)
#endif
for (idx i = 0; i < dim; i++) {
const cost *local_cost = &assign_cost[i * dim];
idx j = rowsol[i];
u[i] = local_cost[j] - v[j];
lapcost += local_cost[j];
}
if (verbose) {
printf("lapjv: optimal cost calculated\n");
}
return lapcost;
}
|
threading_utils.h | /*!
* Copyright 2015-2019 by Contributors
* \file common.h
* \brief Threading utilities
*/
#ifndef XGBOOST_COMMON_THREADING_UTILS_H_
#define XGBOOST_COMMON_THREADING_UTILS_H_
#include <vector>
#include <algorithm>
namespace xgboost {
namespace common {
// Represent simple range of indexes [begin, end)
// Inspired by tbb::blocked_range
class Range1d {
public:
Range1d(size_t begin, size_t end): begin_(begin), end_(end) {
CHECK_LT(begin, end);
}
size_t begin() {
return begin_;
}
size_t end() {
return end_;
}
private:
size_t begin_;
size_t end_;
};
// Split 2d space to balanced blocks
// Implementation of the class is inspired by tbb::blocked_range2d
// However, TBB provides only (n x m) 2d range (matrix) separated by blocks. Example:
// [ 1,2,3 ]
// [ 4,5,6 ]
// [ 7,8,9 ]
// But the class is able to work with different sizes in each 'row'. Example:
// [ 1,2 ]
// [ 3,4,5,6 ]
// [ 7,8,9]
// If grain_size is 2: It produces following blocks:
// [1,2], [3,4], [5,6], [7,8], [9]
// The class helps to process data in several tree nodes (non-balanced usually) in parallel
// Using nested parallelism (by nodes and by data in each node)
// it helps to improve CPU resources utilization
class BlockedSpace2d {
public:
// Example of space:
// [ 1,2 ]
// [ 3,4,5,6 ]
// [ 7,8,9]
// BlockedSpace2d will create following blocks (tasks) if grain_size=2:
// 1-block: first_dimension = 0, range of indexes in a 'row' = [0,2) (includes [1,2] values)
// 2-block: first_dimension = 1, range of indexes in a 'row' = [0,2) (includes [3,4] values)
// 3-block: first_dimension = 1, range of indexes in a 'row' = [2,4) (includes [5,6] values)
// 4-block: first_dimension = 2, range of indexes in a 'row' = [0,2) (includes [7,8] values)
// 5-block: first_dimension = 2, range of indexes in a 'row' = [2,3) (includes [9] values)
// Arguments:
// dim1 - size of the first dimension in the space
// getter_size_dim2 - functor to get the second dimensions for each 'row' by row-index
// grain_size - max size of produced blocks
template<typename Func>
BlockedSpace2d(size_t dim1, Func getter_size_dim2, size_t grain_size) {
for (size_t i = 0; i < dim1; ++i) {
const size_t size = getter_size_dim2(i);
const size_t n_blocks = size/grain_size + !!(size % grain_size);
for (size_t iblock = 0; iblock < n_blocks; ++iblock) {
const size_t begin = iblock * grain_size;
const size_t end = std::min(begin + grain_size, size);
AddBlock(i, begin, end);
}
}
}
// Amount of blocks(tasks) in a space
size_t Size() const {
return ranges_.size();
}
// get index of the first dimension of i-th block(task)
size_t GetFirstDimension(size_t i) const {
CHECK_LT(i, first_dimension_.size());
return first_dimension_[i];
}
// get a range of indexes for the second dimension of i-th block(task)
Range1d GetRange(size_t i) const {
CHECK_LT(i, ranges_.size());
return ranges_[i];
}
private:
void AddBlock(size_t first_dimension, size_t begin, size_t end) {
first_dimension_.push_back(first_dimension);
ranges_.emplace_back(begin, end);
}
std::vector<Range1d> ranges_;
std::vector<size_t> first_dimension_;
};
// Wrapper to implement nested parallelism with simple omp parallel for
template<typename Func>
void ParallelFor2d(const BlockedSpace2d& space, const int nthreads, Func func) {
const size_t num_blocks_in_space = space.Size();
#pragma omp parallel num_threads(nthreads)
{
size_t tid = omp_get_thread_num();
size_t chunck_size = num_blocks_in_space / nthreads + !!(num_blocks_in_space % nthreads);
size_t begin = chunck_size * tid;
size_t end = std::min(begin + chunck_size, num_blocks_in_space);
for (auto i = begin; i < end; i++) {
func(space.GetFirstDimension(i), space.GetRange(i));
}
}
}
} // namespace common
} // namespace xgboost
#endif // XGBOOST_COMMON_THREADING_UTILS_H_
|
GB_binop__minus_uint64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_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__minus_uint64)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__minus_uint64)
// A.*B function (eWiseMult): GB (_AemultB_03__minus_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint64)
// A*D function (colscale): GB (_AxD__minus_uint64)
// D*A function (rowscale): GB (_DxB__minus_uint64)
// C+=B function (dense accum): GB (_Cdense_accumB__minus_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__minus_uint64)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint64)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint64)
// C=scalar+B GB (_bind1st__minus_uint64)
// C=scalar+B' GB (_bind1st_tran__minus_uint64)
// C=A+scalar GB (_bind2nd__minus_uint64)
// C=A'+scalar GB (_bind2nd_tran__minus_uint64)
// C type: uint64_t
// A type: uint64_t
// B,b type: uint64_t
// BinaryOp: cij = (aij - bij)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint64_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = (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_MINUS || GxB_NO_UINT64 || GxB_NO_MINUS_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__minus_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__minus_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__minus_uint64)
(
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__minus_uint64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint64_t
uint64_t bwork = (*((uint64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__minus_uint64)
(
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
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__minus_uint64)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__minus_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *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__minus_uint64)
(
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__minus_uint64)
(
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__minus_uint64)
(
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__minus_uint64)
(
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__minus_uint64)
(
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
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t x = (*((uint64_t *) x_input)) ;
uint64_t *Bx = (uint64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint64_t bij = Bx [p] ;
Cx [p] = (x - bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__minus_uint64)
(
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 ;
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t *Ax = (uint64_t *) Ax_input ;
uint64_t y = (*((uint64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint64_t aij = Ax [p] ;
Cx [p] = (aij - y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB (_bind1st_tran__minus_uint64)
(
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 \
uint64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t x = (*((const uint64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB (_bind2nd_tran__minus_uint64)
(
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
uint64_t y = (*((const uint64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
constant_density_acoustic_time_scalar_1D_6.h | #ifndef __CDA_TIME_SCALAR_1D_6__
#define __CDA_TIME_SCALAR_1D_6__
#include <stdlib.h>
template< typename T, int ACCURACY >
void cda_time_scalar_1D_6( T* km1_u, int nr_km1_u, int nc_km1_u, // in - padded wavefield shape
T* k_Phiz, int nr_k_Phiz, int nc_k_Phiz, // in - padded wavefield shape
T* k_u, int nr_k_u, int nc_k_u, // in - padded wavefield shape
T* C, int nr_C, int nc_C, // in - padded wavefield shape
T* rhs, int nr_rhs, int nc_rhs, // in - padded wavefield shape
T* zlpml, int n_zlpml, // in - length is the number of nodes inside the padding that the pml value is defined.
T* zrpml, int n_zrpml, // in - length is the number of nodes inside the padding that the pml value is defined.
double const& dt, // in
double const& dz, // in
int const& nz, // in
T* kp1_Phiz, int nr_kp1_Phiz, int nc_kp1_Phiz, // out
T* kp1_u, int nr_kp1_u, int nc_kp1_u ) // out
{
enum {MAX_FD_SHIFT = ACCURACY/2};
// PML variable
T sigmaz = 0.0;
// Time delta variables
T dt2 = dt*dt;
// Loop/index variables
int idx;
int zstride=1;
int s = zstride;
// Loop public variables
T dv = dz;
T dv2 = dz*dz;
// Loop private variables
// derivatives
T dU;
T dPhi;
T lapU = 0.0;
// non derivatives
T fac1;
T fac2;
// assignin the NUMBER of threads
char* NUM = getenv("OMP_NUM_THREADS");
int Num_Th = atoi (NUM);
#pragma omp parallel num_threads(Num_Th) private(dU, dPhi, lapU, sigmaz, idx, fac1, fac2) shared(dv, dv2, s, k_u,k_Phiz,kp1_Phiz, kp1_u, rhs, C, dt2, dt, km1_u, zlpml, n_zrpml)
{
#pragma omp for
for(int k=0; k < nz; k++)
{
idx = k;
kp1_Phiz[idx] = 0.0;
kp1_u[idx] = 0.0;
if ((k == 0) || (k == nz-1)) continue;
lapU = 0.0;
if (k==0)
{
//decentered derivative 3 ranks on the right
dU = ((-1./60.)*0.0+(3./20.)*0.0+(-3./4.)*0.0+0.0+(3./4.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./60.)*k_u[idx+3*s])/dv;
dPhi = ((-1./60.)*0.0+(3./20.)*0.0+(-3./4.)*0.0+0.0+(3./4.)*k_Phiz[idx+s]+(-3./20.)*k_Phiz[idx+2*s]+(1./60.)*k_Phiz[idx+3*s])/dv;
lapU += ((1./90.)*0.0+(-3./20.)*0.0+(3./2.)*0.0+(-49./18.)*k_u[idx]+(3./2.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./90.)*k_u[idx+3*s])/dv2;
}
else if (k == 1)
{
//decentered derivative 2 rank on the right
dU = ((-1./60.)*0.0+(3./20.)*0.0+(-3./4.)*k_u[idx-s]+0.0+(3./4.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./60.)*k_u[idx+3*s])/dv;
dPhi = ((-1./60.)*0.0+(3./20.)*0.0+(-3./4.)*k_Phiz[idx-s]+0.0+(3./4.)*k_Phiz[idx+s]+(-3./20.)*k_Phiz[idx+2*s]+(1./60.)*k_Phiz[idx+3*s])/dv;
lapU += ((1./90.)*0.0+(-3./20.)*0.0+(3./2.)*k_u[idx-s]+(-49./18.)*k_u[idx]+(3./2.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./90.)*k_u[idx+3*s])/dv2;
}
else if (k == 2)
{
//decentered derivative 1 rank on the right
dU = ((-1./60.)*0.0+(3./20.)*k_u[idx-2*s]+(-3./4.)*k_u[idx-s]+0.0+(3./4.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./60.)*k_u[idx+3*s])/dv;
dPhi = ((-1./60.)*0.0+(3./20.)*k_Phiz[idx-2*s]+(-3./4.)*k_Phiz[idx-s]+0.0+(3./4.)*k_Phiz[idx+s]+(-3./20.)*k_Phiz[idx+2*s]+(1./60.)*k_Phiz[idx+3*s])/dv;
lapU += ((1./90.)*0.0+(-3./20.)*k_u[idx-2*s]+(3./2.)*k_u[idx-s]+(-49./18.)*k_u[idx]+(3./2.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./90.)*k_u[idx+3*s])/dv2;
}
else if (k == nz-1)
{
//decentered derivative 3 ranks on the left
dU = ((-1./60.)*k_u[idx-3*s]+(3./20.)*k_u[idx-2*s]+(-3./4.)*k_u[idx-s]+0.0+(3./4.)*0.0+(-3./20.)*0.0+(1./60.)*0.0)/dv;
dPhi = ((-1./60.)*k_Phiz[idx-3*s]+(3./20.)*k_Phiz[idx-2*s]+(-3./4.)*k_Phiz[idx-s]+0.0+(3./4.)*0.0+(-3./20.)*0.0+(1./60.)*0.0)/dv;
lapU += ((1./90.)*k_u[idx-3*s]+(-3./20.)*k_u[idx-2*s]+(3./2.)*k_u[idx-s]+(-49./18.)*k_u[idx]+(3./2.)*0.0+(-3./20.)*0.0+(1./90.)*0.0)/dv2;
}
else if (k == nz-2)
{
//decentered derivative 2 ranks on the left
dU = ((-1./60.)*k_u[idx-3*s]+(3./20.)*k_u[idx-2*s]+(-3./4.)*k_u[idx-s]+0.0+(3./4.)*k_u[idx+s]+(-3./20.)*0.0+(1./60.)*0.0)/dv;
dPhi = ((-1./60.)*k_Phiz[idx-3*s]+(3./20.)*k_Phiz[idx-2*s]+(-3./4.)*k_Phiz[idx-s]+0.0+(3./4.)*k_Phiz[idx+s]+(-3./20.)*0.0+(1./60.)*0.0)/dv;
lapU += ((1./90.)*k_u[idx-3*s]+(-3./20.)*k_u[idx-2*s]+(3./2.)*k_u[idx-s]+(-49./18.)*k_u[idx]+(3./2.)*k_u[idx+s]+(-3./20.)*0.0+(1./90.)*0.0)/dv2;
}
else if (k == nz-3)
{
//decentered derivative 1 rank on the left
dU = ((-1./60.)*k_u[idx-3*s]+(3./20.)*k_u[idx-2*s]+(-3./4.)*k_u[idx-s]+0.0+(3./4.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./60.)*0.0)/dv;
dPhi = ((-1./60.)*k_Phiz[idx-3*s]+(3./20.)*k_Phiz[idx-2*s]+(-3./4.)*k_Phiz[idx-s]+0.0+(3./4.)*k_Phiz[idx+s]+(-3./20.)*k_Phiz[idx+2*s]+(1./60.)*0.0)/dv;
lapU += ((1./90.)*k_u[idx-3*s]+(-3./20.)*k_u[idx-2*s]+(3./2.)*k_u[idx-s]+(-49./18.)*k_u[idx]+(3./2.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./90.)*0.0)/dv2;
}
else
{
//classic centered derivative
dU = ((-1./60.)*k_u[idx-3*s]+(3./20.)*k_u[idx-2*s]+(-3./4.)*k_u[idx-s]+0.0+(3./4.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./60.)*k_u[idx+3*s])/dv;
dPhi = ((-1./60.)*k_Phiz[idx-3*s]+(3./20.)*k_Phiz[idx-2*s]+(-3./4.)*k_Phiz[idx-s]+0.0+(3./4.)*k_Phiz[idx+s]+(-3./20.)*k_Phiz[idx+2*s]+(1./60.)*k_Phiz[idx+3*s])/dv;
lapU += ((1./90.)*k_u[idx-3*s]+(-3./20.)*k_u[idx-2*s]+(3./2.)*k_u[idx-s]+(-49./18.)*k_u[idx]+(3./2.)*k_u[idx+s]+(-3./20.)*k_u[idx+2*s]+(1./90.)*k_u[idx+3*s])/dv2;
}
sigmaz = 0.0;
if((n_zlpml>0) && (k < n_zlpml))
{
sigmaz = zlpml[k];
}
else if((n_zrpml>0) && (k >= nz-n_zrpml))
{
sigmaz = zrpml[n_zrpml-((nz-1)-k)];
}
if(sigmaz != 0.0)
{
kp1_Phiz[idx] = k_Phiz[idx] - dt * sigmaz*(k_Phiz[idx] + dU);
fac1 = (2.0*dt2 / (2.0 + dt*sigmaz));
fac2 = (C[idx]*C[idx])*(rhs[idx]+lapU+dPhi) - (km1_u[idx]-2.0*k_u[idx])/dt2 + sigmaz*km1_u[idx]/(2.0*dt);
kp1_u[idx] = fac1 * fac2;
}
else
{
kp1_Phiz[idx] = k_Phiz[idx];
kp1_u[idx] = dt2*(C[idx]*C[idx])*(rhs[idx]+lapU+dPhi) - (km1_u[idx]-2.0*k_u[idx]);
}
}
}
};
#endif
|
GB_dense_subassign_22_template.c | //------------------------------------------------------------------------------
// GB_dense_subassign_22_template: C += b where C is dense and b is a scalar
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
{
//--------------------------------------------------------------------------
// get C
//--------------------------------------------------------------------------
GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ;
const int64_t cnz = GB_NNZ (C) ;
//--------------------------------------------------------------------------
// C += b where C is dense and b is a scalar
//--------------------------------------------------------------------------
int64_t pC ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (pC = 0 ; pC < cnz ; pC++)
{
GB_BINOP (GB_CX (pC), GB_CX (pC), bwork) ;
}
}
|
cmapLapParaSimilarity.h | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program and software framework */
/* CMAP-LAP --- Configurable Massively Parallel Solver for Lattice Problems */
/* */
/* Copyright Written by Nariaki Tateiwa <n-tateiwa@kyudai.jp>, */
/* Yuji Shinano <shinano@zib.de>, */
/* Copyright (C) 2021 by Zuse Institute Berlin, */
/* licensed under LGPL version 3 or later. */
/* Commercial licenses are available through <licenses@zib.de> */
/* */
/* This code is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public License */
/* as published by the Free Software Foundation; either version 3 */
/* of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file cmapLapParaSimilarity.h
* @brief Functions to calculate similarity of basis set.
* @author Nariaki Tateiwa, Yuji Shinano
*
*
*
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
#ifndef __CMAP_LAP_PARA_SIMILARITY_H__
#define __CMAP_LAP_PARA_SIMILARITY_H__
#include <vector>
#include <chrono>
#include <random>
#include <deque>
#include <set>
#include <cassert>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/SVD>
namespace ParaCMapLAP
{
namespace BasisSimilarity
{
/// index to calculate grassmann metric
std::vector<int> grassmannIndexes;
/// calculate grassmann metric
Eigen::MatrixXd scores_geodesic_metric;
Eigen::MatrixXd scores_chordal_metric;
Eigen::MatrixXd scores_fubini_study_metric;
Eigen::MatrixXd scores_chordal_2norm_metric;
Eigen::MatrixXd scores_chordal_fnorm_metric;
Eigen::MatrixXd scores_projection_2norm_metric;
Eigen::MatrixXd scores_max_metric;
Eigen::MatrixXd scores_mean_metric;
Eigen::VectorXd scores_num_upper_duplicate;
Eigen::VectorXd scores_num_all_duplicate;
///
/// @brief setter of grassmannIndexes
/// @param[in] inGrassmannIndexes
///
void setGrassmannIndexes(
std::vector<int> inGrassmannIndexes
)
{
grassmannIndexes = inGrassmannIndexes;
}
///
/// @brief similarity log header
/// @param[in] n dimension
/// @return std::string
///
std::string outputSimilarityOfBasisHeader(
int n
)
{
assert( grassmannIndexes.size() > 0 );
std::ostringstream s;
s << "SimilarityStatus"
<< ",time"
<< ",numPairs";
std::vector<std::string> metrics{"num_upper_duplicate", "num_all_duplicate"};
std::vector<std::string> grassmannMetricNames{
"grassmann_geodesic",
"grassmann_chordal",
"grassmann_fubini",
"grassmann_chordal_2norm",
"grassmann_chordal_fnorm",
"grassmann_projection_2norm",
"grassmann_max",
"grassmann_mean"
};
for( auto name : grassmannMetricNames )
{
for( auto i : grassmannIndexes )
{
std::ostringstream metric;
metric << name << "_" << i;
metrics.push_back(metric.str());
}
}
for( auto metric : metrics )
{
s << "," << metric << "_min";
s << "," << metric << "_max";
s << "," << metric << "_average";
}
return s.str();
}
///
/// @brief sampling of vector
/// @tparam T population type
/// @param[in] population list
/// @param[out] sampled list
/// @param[in] sampled size
///
template<typename T> void sample(
T &list,
T &sampled_list,
int size
)
{
assert( static_cast<int>(list.size()) >= size );
std::vector<int> indexes(list.size(), 0);
for ( size_t i = 0; i < list.size(); ++i )
indexes[i] = i;
std::random_device seed_gen;
// std::mt19937 engine {seed_gen()};
std::mt19937 engine {0};
std::shuffle(indexes.begin(), indexes.end(), engine);
sampled_list.resize(size);
for ( int i = 0; i < size; ++i )
sampled_list[i] = list[indexes[i]];
}
///
/// @brief sign function
/// @param[in] x
/// @return sign of x ( 1 or -1 )
///
int sign(
int x
)
{
if( x >= 0 ) return 1;
else return -1;
}
///
/// @brief max(k; A(i) == B(i) || A(i) == -B(i) for all i <= k )
/// @param[in] basisA basis
/// @param[in] basisB basis
/// @return number of matches from the top of the basis vector
///
double num_upper_duplicate(
LatticeBasis<int>& basisA,
LatticeBasis<int>& basisB
)
{
double score = 0.0;
for( int i = 0; i < basisA.rows(); i++ )
{
if( sign(basisA.coeff(i, 0))*basisA.row(i)
== sign(basisB.coeff(i, 0))*basisB.row(i) )
score += 1;
else
break;
}
return score;
}
///
/// @brief coun ( ( A(i) == B(i) || A(i) == -B(i) ) for all i )
/// @param[in] basisA basis
/// @param[in] basisB basis
/// @return number of basis vector overlaps
///
double num_all_duplicate(
LatticeBasis<int>& basisA,
LatticeBasis<int>& basisB
)
{
double score = 0.0;
for( int i = 0; i < basisA.rows(); i++ )
{
if( sign(basisA.coeff(i, 0))*basisA.row(i)
== sign(basisB.coeff(i, 0))*basisB.row(i) )
score += 1;
}
return score;
}
/// @brief set Gram-Schmidt matrix
/// @parma[in] basis
/// @parma[out] GSO Gram-Schmidt of basis
///
void setGramSchmidt(
LatticeBasis<int>& basis,
Eigen::MatrixXd& GSO
)
{
GSO = LatticeBasis<int>(basis).cast<double>()
.transpose()
.householderQr()
.householderQ()
.transpose();
}
///
/// @brief Grassmann Geodesic Metric
/// @param[in] cc canonical correlations
/// @details sqrt(sum(theta_i^2 for 0 <= i < m))
/// = sqrt(sum(acos(cc(i))^2 for 0 <= i < m))
///
double grassmann_geodesic_metric(
Eigen::VectorXd &cc
)
{
int m = cc.size();
double d = 0.0;
double theta = 0.0;
for( int i = 0; i < m; ++i )
{
theta = std::acos(cc(i));
d += theta * theta;
}
return std::sqrt(d);
}
///
/// @brief Grassmann Projected Metric
/// @param[in] cc canonicalCorrelations
/// @details 2^(-1/2) frobenius_norm(GSOA*GSOA^T - GSOB*GSOB^T)
/// = sqrt(m - sum(cos^2(theta_i) for 0 <= i < m))
/// = sqrt(m - sum(cc(i)^2) for 0 <= i <= m)
///
double grassmann_chordal_metric(
Eigen::VectorXd &cc
)
{
int m = cc.size();
double d = m;
for( int i = 0; i < m; i++ )
d -= cc(i) * cc(i);
return std::sqrt(d);
}
///
/// @brief Grassmann Fubini-Study Metric
/// @param[in] cc canonical correlations
/// @details acos(prod(cos(theta_i) for 0 <= i < m))
/// = acos(prod(cc(i) for 0 <= i < m))
///
double grassmann_fubini_study_metric(
Eigen::VectorXd &cc
)
{
return std::acos( cc.prod() );
}
///
/// @brief Grassmann Chordal 2-norm Metric
/// @param[in] cc canonical correlations
/// @details 2norm( U*GSOA^T - V*GSOB )
/// = infinity_norm(2*sin(theta_i/2) for 0 <= i < m)
/// = 2 * max(sin(theta_i/2) for 0 <= i < m)
/// = 2 * sqrt( max(sin^2(theta_i/2) for 0 <= i < m) ) (because 0 < theta_i < pi)
/// = 2 * sqrt( max((1-cc(i))/2 for 0 <= i < m) )
///
double grassmann_chordal_2norm_metric(
Eigen::VectorXd &cc
)
{
int m = cc.size();
double d = (1.0 - cc(0)) / 2.0;
for( int i = 1; i < m; ++i )
{
d = std::max(d, (1.0 - cc(i))/2.0);
}
return 2.0 * std::sqrt(d);
}
///
/// @brief Grassmann Chordal frobenius-norm Metric
/// @param[in] cc canonical correlations
/// @details frobenius_norm( U*GSOA^T - V*GSOB )
/// = 2_norm(2*sin(theta_i/2) for 0 <= i < m)
/// = 2 * sqrt(sum(sin^2(theta_i/2) for 0 <= i < m)
/// = 2 * sqrt(sum((1-cc(i))/2 for 0 <= i < m)
///
double grassmann_chordal_fnorm_metric(
Eigen::VectorXd &cc
)
{
int m = cc.size();
double d = 0.0;
for( int i = 0; i < m; ++i )
d += (1.0 - cc(i)) / 2.0;
return 2.0 * std::sqrt(d);
}
///
/// @brief Grassmann Projection 2-norm Metric
/// @param[in] cc canonicalCorrelations
/// @details 2norm( GSOA*GSOA^T - GSOB*GSOB^T )
/// infinity_norm( sin(theta_i) ) for 0 <= i < m) )
/// = sqrt( max( sin^2(theta_i) for 0 <= i < m) ) (because 0 <= theta_i <= pi)
/// = sqrt( max( 1 - cos^2(theta_i) for 0 <= i < m) )
/// = sqrt( max( 1 - cc(i)^2 for 0 <= i < m) )
/// = sqrt( 1 - cc(0)^2 )
///
double grassmann_projection_2norm_metric(
Eigen::VectorXd &cc
)
{
// int m = cc.size();
double d = 1.0 - cc(0) * cc(0);
if( d < 1.0e-5 ) return 0;
// for( int i = 1; i < m; ++i )
// {
// d = std::max(d, 1.0 - cc(i) * cc(i));
// }
return std::sqrt(d);
}
///
/// @brief Grassmann max Metric
/// @param[in] cc canonicalCorrelations
/// @details min( sin(theta_i) ) for 0 <= i < m) )
/// = sqrt( min( sin^2(theta_i) for 0 <= i < m) ) (because 0 <= theta_i <= pi)
/// = sqrt( min( 1 - cos^2(theta_i) for 0 <= i < m) )
/// = sqrt( min( 1 - cc(i)^2 for 0 <= i < m) )
/// = sqrt( 1 - cc(m-1)^2 )
///
double grassmann_max_metric(
Eigen::VectorXd &cc
)
{
int m = cc.size();
double d = 1.0 - cc(m-1) * cc(m-1);
if( d < 1.0e-5 ) return 0;
return std::sqrt(d);
}
///
/// @brief Grassmann Mean Metric
/// @param[in] cc canonicalCorrelations
/// @details mean( sin(\theta_i)^2 for 0 <= i <= m )
/// = mean( 1 - cos(\theta_i)^2 for 0 <= i <= m )
///
double grassmann_mean_metric(
Eigen::VectorXd &cc
)
{
int m = cc.size();
double d = 0.0;
for( int i = 0; i < m; i++ )
d += 1.0 - cc(i)*cc(i);
return d / static_cast<double>(m);
}
///
/// @brief output log
/// @param[in] basisDeque container of basis
/// @param[in] time
/// @param[in] n dimension of basis
/// @param[in] nSamples number of samples for calculation of basis similarity
/// @param[in] num_threads number threads
/// @param[in] verbose ( 0: not, 1: light, 2: medium, 3: heave )
///
std::string outputSimilarityOfBasis(
std::deque<std::shared_ptr<LatticeBasis<int>>> &basisDeque,
double time,
int n,
int nSamples=-1,
int numThreads=1,
int verbose=0
)
{
auto start = std::chrono::system_clock::now();
auto elapsed = [&start](
)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now()-start
).count() / 1000.0;
};
int numBasis = basisDeque.size();
int numPairs = numBasis * (numBasis-1) / 2;
int k = -1;
double tol = 1e-6;
std::vector<std::pair<int, int>> combinations;
combinations.resize(numPairs);
k = -1;
for ( int i = 0; i < numBasis; ++i )
{
for ( int j = i+1; j < numBasis; ++j )
{
combinations[++k] = std::make_pair(i, j);
}
}
// sampling
if( nSamples == -1 ){ nSamples = combinations.size(); }
nSamples = std::min(nSamples, static_cast<int>(combinations.size()));
decltype(combinations) sampledConbinations;
sample(
combinations,
sampledConbinations,
nSamples
);
// calculate GSO matrix
std::vector<Eigen::MatrixXd> GSOList;
GSOList.resize(basisDeque.size());
std::set<int> calcGSOindexes;
for( auto pair : sampledConbinations )
{
calcGSOindexes.insert(pair.first);
calcGSOindexes.insert(pair.second);
}
for( auto _k : calcGSOindexes )
{
Eigen::MatrixXd GSO;
setGramSchmidt(*basisDeque.at(_k), GSO);
GSOList[_k] = GSO;
}
// calculate grassmann metric
scores_geodesic_metric .resize(nSamples, grassmannIndexes.size());
scores_chordal_metric .resize(nSamples, grassmannIndexes.size());
scores_fubini_study_metric .resize(nSamples, grassmannIndexes.size());
scores_chordal_2norm_metric .resize(nSamples, grassmannIndexes.size());
scores_chordal_fnorm_metric .resize(nSamples, grassmannIndexes.size());
scores_projection_2norm_metric.resize(nSamples, grassmannIndexes.size());
scores_max_metric .resize(nSamples, grassmannIndexes.size());
scores_mean_metric .resize(nSamples, grassmannIndexes.size());
scores_num_upper_duplicate .resize(nSamples);
scores_num_all_duplicate .resize(nSamples);
#pragma omp parallel for num_threads(numThreads) schedule(static)
for( k = 0; k < nSamples; ++k )
{
int i, j;
std::tie(i, j) = sampledConbinations[k];
// duplicate
scores_num_upper_duplicate(k) = num_upper_duplicate(
*(basisDeque.at(i)), *(basisDeque.at(j))
);
scores_num_all_duplicate(k) = num_all_duplicate(
*(basisDeque.at(i)), *(basisDeque.at(j))
);
// grassmann
// 1. generate sub GSO
// 2. get canonical angles
// 3. calculate metric
for( int l = grassmannIndexes.size()-1; l > -1; --l )
{
int d = grassmannIndexes[l];
Eigen::VectorXd canonicalCorrelations = Eigen::VectorXd::Ones(n-d);
if( d >= n / 2.0 )
{
// GSO = [b*0; b*1; ...; b*n-1] -> [b*d; ...; b*(n-1)]
Eigen::MatrixXd subGSOA{GSOList.at(i).block(d,0,n-d,n)};
Eigen::MatrixXd subGSOB{GSOList.at(j).block(d,0,n-d,n)};
// calculate canonical angles
Eigen::JacobiSVD<Eigen::MatrixXd> SVD{subGSOA * subGSOB.transpose()};
canonicalCorrelations.tail(n-d) = SVD.singularValues();
}
else if( d > 0 )
{
// GSO = [b*0; b*1; ...; b*n-1] -> [b*0; ...; b*d-1]
Eigen::MatrixXd subGSOA{GSOList.at(i).block(0,0,d,n)};
Eigen::MatrixXd subGSOB{GSOList.at(j).block(0,0,d,n)};
// calculate canonical angles
Eigen::JacobiSVD<Eigen::MatrixXd> SVD{subGSOA * subGSOB.transpose()};
canonicalCorrelations.tail(d) = SVD.singularValues();
}
for( int ii = 0; ii < n-d; ++ii )
{
canonicalCorrelations(ii) = std::min(std::max(canonicalCorrelations(ii), -1.0), 1.0);
}
if( verbose > 0 )
{
std::cout << "k: " << k << " pair(" << i << ", " << j << ") d " << d << std::endl;
std::cout << "canonicalCorrelations " << canonicalCorrelations.transpose() << std::endl;
}
if( (canonicalCorrelations.array() >= 1.0-tol).all() && (canonicalCorrelations.array() <= 1.0+tol).all() )
{
// GSOA == GSOB
scores_geodesic_metric(k, l) = 0.0;
scores_chordal_metric(k, l) = 0.0;
scores_fubini_study_metric(k, l) = 0.0;
scores_chordal_2norm_metric(k, l) = 0.0;
scores_chordal_fnorm_metric(k, l) = 0.0;
scores_projection_2norm_metric(k, l) = 0.0;
scores_max_metric(k, l) = 0.0;
scores_mean_metric(k, l) = 0.0;
}
else
{
// calculate metric
scores_geodesic_metric(k, l)
= grassmann_geodesic_metric(canonicalCorrelations);
scores_chordal_metric(k, l)
= grassmann_chordal_metric(canonicalCorrelations);
scores_fubini_study_metric(k, l)
= grassmann_fubini_study_metric(canonicalCorrelations);
scores_chordal_2norm_metric(k, l)
= grassmann_chordal_2norm_metric(canonicalCorrelations);
scores_chordal_fnorm_metric(k, l)
= grassmann_chordal_fnorm_metric(canonicalCorrelations);
scores_projection_2norm_metric(k, l)
= grassmann_projection_2norm_metric(canonicalCorrelations);
scores_max_metric(k, l)
= grassmann_max_metric(canonicalCorrelations);
scores_mean_metric(k, l)
= grassmann_mean_metric(canonicalCorrelations);
}
}
}
std::ostringstream s;
s << "SimilarityStatus"
<< "," << time
<< "," << scores_num_upper_duplicate.size();
// upper_duplicate
s << "," << scores_num_upper_duplicate.minCoeff();
s << "," << scores_num_upper_duplicate.maxCoeff();
s << "," << scores_num_upper_duplicate.mean();
// all_duplicate
s << "," << scores_num_all_duplicate.minCoeff();
s << "," << scores_num_all_duplicate.maxCoeff();
s << "," << scores_num_all_duplicate.mean();
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_geodesic_metric
s << "," << scores_geodesic_metric.col(i).minCoeff();
s << "," << scores_geodesic_metric.col(i).maxCoeff();
s << "," << scores_geodesic_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_chordal_metric
s << "," << scores_chordal_metric.col(i).minCoeff();
s << "," << scores_chordal_metric.col(i).maxCoeff();
s << "," << scores_chordal_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_fubini_study_metric
s << "," << scores_fubini_study_metric.col(i).minCoeff();
s << "," << scores_fubini_study_metric.col(i).maxCoeff();
s << "," << scores_fubini_study_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_chordal_2norm
s << "," << scores_chordal_2norm_metric.col(i).minCoeff();
s << "," << scores_chordal_2norm_metric.col(i).maxCoeff();
s << "," << scores_chordal_2norm_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_chordal_fnorm
s << "," << scores_chordal_fnorm_metric.col(i).minCoeff();
s << "," << scores_chordal_fnorm_metric.col(i).maxCoeff();
s << "," << scores_chordal_fnorm_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_projection_2norm
s << "," << scores_projection_2norm_metric.col(i).minCoeff();
s << "," << scores_projection_2norm_metric.col(i).maxCoeff();
s << "," << scores_projection_2norm_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_max_norm
s << "," << scores_max_metric.col(i).minCoeff();
s << "," << scores_max_metric.col(i).maxCoeff();
s << "," << scores_max_metric.col(i).mean();
}
for( size_t i = 0; i < grassmannIndexes.size(); ++i )
{
// grassmann_mean_norm
s << "," << scores_mean_metric.col(i).minCoeff();
s << "," << scores_mean_metric.col(i).maxCoeff();
s << "," << scores_mean_metric.col(i).mean();
}
std::cout << "\r simlarity total " << elapsed() << " sec" << std::endl;
return s.str();
}
} // namespace BasisSimilarity
} // namespace ParaCMapLAP
#endif // __CMAP_LAP_PARA_SIMILARITY_H__
|
GB_resize.c | //------------------------------------------------------------------------------
// GB_resize: change the size of a matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#include "GB_select.h"
#define GB_FREE_ALL \
{ \
GB_FREE (Ax_new) ; \
GB_FREE (Ab_new) ; \
GB_phbix_free (A) ; \
}
//------------------------------------------------------------------------------
// GB_resize: resize a GrB_Matrix
//------------------------------------------------------------------------------
GrB_Info GB_resize // change the size of a matrix
(
GrB_Matrix A, // matrix to modify
const GrB_Index nrows_new, // new number of rows in matrix
const GrB_Index ncols_new, // new number of columns in matrix
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
GB_void *GB_RESTRICT Ax_new = NULL ;
int8_t *GB_RESTRICT Ab_new = NULL ;
ASSERT_MATRIX_OK (A, "A to resize", GB0) ;
//--------------------------------------------------------------------------
// handle the CSR/CSC format
//--------------------------------------------------------------------------
int64_t vdim_old = A->vdim ;
int64_t vlen_old = A->vlen ;
int64_t vlen_new, vdim_new ;
if (A->is_csc)
{
vlen_new = nrows_new ;
vdim_new = ncols_new ;
}
else
{
vlen_new = ncols_new ;
vdim_new = nrows_new ;
}
if (vdim_new == vdim_old && vlen_new == vlen_old)
{
// nothing to do
return (GrB_SUCCESS) ;
}
//--------------------------------------------------------------------------
// delete any lingering zombies and assemble any pending tuples
//--------------------------------------------------------------------------
// only do so if either dimension is shrinking, or if pending tuples exist
// and vdim_old <= 1 and vdim_new > 1, since in that case, Pending->j has
// not been allocated yet, but would be required in the resized matrix.
// If A is jumbled, it must be sorted.
if (vdim_new < vdim_old || vlen_new < vlen_old || A->jumbled ||
(GB_PENDING (A) && vdim_old <= 1 && vdim_new > 1))
{
GB_MATRIX_WAIT (A) ;
ASSERT_MATRIX_OK (A, "A to resize, wait", GB0) ;
}
ASSERT (!GB_JUMBLED (A)) ;
//--------------------------------------------------------------------------
// resize the matrix
//--------------------------------------------------------------------------
bool A_is_bitmap = GB_IS_BITMAP (A) ;
bool A_is_full = GB_IS_FULL (A) ;
bool A_is_shrinking = (vdim_new <= vdim_old && vlen_new <= vlen_old) ;
if ((A_is_full || A_is_bitmap) && A_is_shrinking)
{
//----------------------------------------------------------------------
// A is full or bitmap
//----------------------------------------------------------------------
// get the old and new dimensions
int64_t anz_old = vlen_old * vdim_old ;
int64_t anz_new = vlen_new * vdim_new ;
size_t nzmax_new = GB_IMAX (anz_new, 1) ;
size_t nzmax_old = A->nzmax ;
bool in_place = A_is_full && (vlen_new == vlen_old || vdim_new <= 1) ;
size_t asize = A->type->size ;
//----------------------------------------------------------------------
// allocate or reallocate A->x and A->b
//----------------------------------------------------------------------
bool ok = true ;
if (in_place)
{
// reallocate A->x in-place; no data movement needed
GB_REALLOC (A->x, nzmax_new*asize, nzmax_old*asize, GB_void, &ok) ;
}
else
{
// allocate new space for A->x
Ax_new = GB_MALLOC (nzmax_new*asize, GB_void) ;
ok = (Ax_new != NULL) ;
if (A_is_bitmap)
{
// allocate new space for A->b
Ab_new = GB_MALLOC (nzmax_new*asize, int8_t) ;
ok = ok && (Ab_new != NULL) ;
}
}
if (!ok)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
//----------------------------------------------------------------------
// move data if not in-place
//----------------------------------------------------------------------
if (!in_place)
{
//------------------------------------------------------------------
// determine number of threads to use
//------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (anz_new, chunk, nthreads_max) ;
//------------------------------------------------------------------
// resize Ax
//------------------------------------------------------------------
GB_void *GB_RESTRICT Ax_old = A->x ;
int64_t j ;
if (vdim_new <= 4*nthreads)
{
// use all threads for each vector
for (j = 0 ; j < vdim_new ; j++)
{
GB_void *pdest = Ax_new + j * vlen_new * asize ;
GB_void *psrc = Ax_old + j * vlen_old * asize ;
GB_memcpy (pdest, psrc, vlen_new * asize, nthreads) ;
}
}
else
{
// use a single thread for each vector
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (j = 0 ; j < vdim_new ; j++)
{
GB_void *pdest = Ax_new + j * vlen_new * asize ;
GB_void *psrc = Ax_old + j * vlen_old * asize ;
memcpy (pdest, psrc, vlen_new * asize) ;
}
}
A->x = Ax_new ;
GB_FREE (Ax_old) ;
//------------------------------------------------------------------
// resize Ab if A is bitmap, and count the # of entries
//------------------------------------------------------------------
if (A_is_bitmap)
{
int8_t *GB_RESTRICT Ab_old = A->b ;
int64_t pnew ;
int64_t anvals = 0 ;
#pragma omp parallel for num_threads(nthreads) \
schedule(static) reduction(+:anvals)
for (pnew = 0 ; pnew < anz_new ; pnew++)
{
int64_t i = pnew % vlen_new ;
int64_t j = pnew / vlen_new ;
int64_t pold = i + j * vlen_old ;
int8_t ab = Ab_old [pold] ;
Ab_new [pnew] = ab ;
anvals += ab ;
}
A->nvals = anvals ;
A->b = Ab_new ;
GB_FREE (Ab_old) ;
}
}
//----------------------------------------------------------------------
// adjust dimensions and return result
//----------------------------------------------------------------------
A->vdim = vdim_new ;
A->vlen = vlen_new ;
A->nzmax = nzmax_new ;
A->nvec = vdim_new ;
A->nvec_nonempty = (vlen_new == 0) ? 0 : vdim_new ;
ASSERT_MATRIX_OK (A, "A bitmap/full shrunk", GB0) ;
return (GrB_SUCCESS) ;
}
else
{
//----------------------------------------------------------------------
// convert A to hypersparse and resize it
//----------------------------------------------------------------------
// convert to hypersparse
GB_OK (GB_convert_any_to_hyper (A, Context)) ;
ASSERT (GB_IS_HYPERSPARSE (A)) ;
// resize the number of sparse vectors
int64_t *GB_RESTRICT Ah = A->h ;
int64_t *GB_RESTRICT Ap = A->p ;
A->vdim = vdim_new ;
if (vdim_new < A->plen)
{
// reduce the size of A->p and A->h; this cannot fail
info = GB_hyper_realloc (A, vdim_new, Context) ;
ASSERT (info == GrB_SUCCESS) ;
Ap = A->p ;
Ah = A->h ;
}
if (vdim_new < vdim_old)
{
// descrease A->nvec to delete the vectors outside the range
// 0...vdim_new-1.
int64_t pleft = 0 ;
int64_t pright = GB_IMIN (A->nvec, vdim_new) - 1 ;
bool found ;
GB_SPLIT_BINARY_SEARCH (vdim_new, Ah, pleft, pright, found) ;
A->nvec = pleft ;
}
if (vdim_new < vdim_old)
{
// number of vectors is decreasing, need to count the new number of
// non-empty vectors: done during pruning or by selector, below.
A->nvec_nonempty = -1 ; // recomputed just below
}
//----------------------------------------------------------------------
// resize the length of each vector
//----------------------------------------------------------------------
// if vlen is shrinking, delete entries outside the new matrix
if (vlen_new < vlen_old)
{
GB_OK (GB_selector (NULL /* A in-place */, GB_RESIZE_opcode, NULL,
false, A, vlen_new-1, NULL, Context)) ;
}
//----------------------------------------------------------------------
// vlen has been resized
//----------------------------------------------------------------------
A->vlen = vlen_new ;
ASSERT_MATRIX_OK (A, "A vlen resized", GB0) ;
//----------------------------------------------------------------------
// conform the matrix to its desired sparsity structure
//----------------------------------------------------------------------
return (GB_conform (A, Context)) ;
}
}
|
GB_unop__lnot_int16_int16.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__lnot_int16_int16
// op(A') function: GB_unop_tran__lnot_int16_int16
// C type: int16_t
// A type: int16_t
// cast: int16_t cij = aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CAST(z, aij) \
int16_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = aij ; \
Cx [pC] = !(z != 0) ; \
}
// 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_LNOT || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__lnot_int16_int16
(
int16_t *Cx, // Cx and Ax may be aliased
const int16_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 (int16_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int16_t aij = Ax [p] ;
int16_t z = aij ;
Cx [p] = !(z != 0) ;
}
#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 ;
int16_t aij = Ax [p] ;
int16_t z = aij ;
Cx [p] = !(z != 0) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__lnot_int16_int16
(
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
|
wick.c | /*
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "wick.h"
#include <stdbool.h>
#include <assert.h>
/* C-kernel for filling custom RDMs using particle RDMs. */
int wickfill(double complex *target,
const double complex *source,
const uint32_t *indices,
const double factor,
const uint32_t *delta,
const int norb,
const int trank,
const int srank) {
if (srank == 0 && trank == 1) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < norb; ++i) {
target[i + norb * i] += factor;
}
} else if (srank == 1 && trank == 1) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < norb; ++i) {
for (int j = 0; j != norb; ++j) {
const int mat[2] = {i, j};
target[j + norb * i] += factor * source[mat[indices[1]]
+ norb * mat[indices[0]]];
}
}
} else if (srank == 0 && trank == 2) {
#pragma omp parallel for schedule(static)
for (int ij = 0; ij < norb * norb; ++ij) {
const int i = ij / norb;
const int j = ij % norb;
for (int k = 0; k != norb; ++k) {
for (int l = 0; l != norb; ++l) {
const int mat[4] = {i, j, k, l};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]] &&
mat[delta[1 * 2 + 0]] == mat[delta[1 * 2 + 1]]) {
target[l + norb * (k + norb * (j + norb * i))] += factor;
}
}
}
}
} else if (srank == 1 && trank == 2) {
#pragma omp parallel for schedule(static)
for (int ij = 0; ij < norb * norb; ++ij) {
const int i = ij / norb;
const int j = ij % norb;
for (int k = 0; k != norb; ++k) {
for (int l = 0; l != norb; ++l) {
const int mat[4] = {i, j, k, l};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]]) {
target[l + norb * (k + norb * (j + norb * i))]
+= factor * source[mat[indices[1]]
+ norb * mat[indices[0]]];
}
}
}
}
} else if (srank == 2 && trank == 2) {
#pragma omp parallel for schedule(static)
for (int ij = 0; ij < norb * norb; ++ij) {
const int i = ij / norb;
const int j = ij % norb;
for (int k = 0; k != norb; ++k) {
for (int l = 0; l != norb; ++l) {
const int mat[4] = {i, j, k, l};
target[l + norb * (k + norb * (j + norb * i))]
+= factor * source[mat[indices[3]]
+ norb * (mat[indices[2]]
+ norb * (mat[indices[1]]
+ norb * mat[indices[0]]))];
}
}
}
} else if (srank == 0 && trank == 3) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < norb; ++i) {
for (int j = 0; j != norb; ++j) {
for (int k = 0; k != norb; ++k) {
for (int l = 0; l != norb; ++l) {
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
const int mat[6] = {i, j, k, l, o, p};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]] &&
mat[delta[1 * 2 + 0]] == mat[delta[1 * 2 + 1]] &&
mat[delta[2 * 2 + 0]] == mat[delta[2 * 2 + 1]]) {
target[p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))]
+= factor;
}
}
}
}
}
}
}
} else if (srank == 1 && trank == 3) {
#pragma omp parallel for schedule(static)
for (int ijk = 0; ijk < norb * norb * norb; ++ijk) {
const int i = ijk / (norb * norb);
const int j = (ijk % (norb * norb)) / norb;
const int k = (ijk % (norb * norb)) % norb;
for (int l = 0; l != norb; ++l) {
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
const int mat[6] = {i, j, k, l, o, p};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]] &&
mat[delta[1 * 2 + 0]] == mat[delta[1 * 2 + 1]]) {
target[p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))]
+= factor * source[mat[indices[1]] + norb * mat[indices[0]]];
}
}
}
}
}
} else if (srank == 2 && trank == 3) {
#pragma omp parallel for schedule(static)
for (int ijk = 0; ijk < norb * norb * norb; ++ijk) {
const int i = ijk / (norb * norb);
const int j = (ijk % (norb * norb)) / norb;
const int k = (ijk % (norb * norb)) % norb;
for (int l = 0; l != norb; ++l) {
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
const int mat[6] = {i, j, k, l, o, p};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]]) {
target[p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))]
+= factor * source[mat[indices[3]]
+ norb * (mat[indices[2]]
+ norb * (mat[indices[1]]
+ norb * mat[indices[0]]))];
}
}
}
}
}
} else if (srank == 3 && trank == 3) {
#pragma omp parallel for schedule(static)
for (int ijk = 0; ijk < norb * norb * norb; ++ijk) {
const int i = ijk / (norb * norb);
const int j = (ijk % (norb * norb)) / norb;
const int k = (ijk % (norb * norb)) % norb;
for (int l = 0; l != norb; ++l) {
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
const int mat[6] = {i, j, k, l, o, p};
target[p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))]
+= factor * source[mat[indices[5]]
+ norb * (mat[indices[4]] + norb * (mat[indices[3]]
+ norb * (mat[indices[2]] + norb * (mat[indices[1]]
+ norb * mat[indices[0]]))))];
}
}
}
}
} else if (srank == 0 && trank == 4) {
#pragma omp parallel for schedule(static)
for (int ijkl = 0; ijkl < norb * norb * norb * norb; ++ijkl) {
const int i = ijkl / (norb * norb * norb);
const int jkl = ijkl % (norb * norb * norb);
const int j = jkl / (norb * norb);
const int kl = jkl % (norb * norb);
const int k = kl / norb;
const int l = kl % norb;
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
for (int q = 0; q != norb; ++q) {
for (int r = 0; r != norb; ++r) {
const int mat[8] = {i, j, k, l, o, p, q, r};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]] &&
mat[delta[1 * 2 + 0]] == mat[delta[1 * 2 + 1]] &&
mat[delta[2 * 2 + 0]] == mat[delta[2 * 2 + 1]] &&
mat[delta[3 * 2 + 0]] == mat[delta[3 * 2 + 1]]) {
target[r + norb * (q + norb * (p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))))]
+= factor;
}
}
}
}
}
}
} else if (srank == 1 && trank == 4) {
#pragma omp parallel for schedule(static)
for (int ijkl = 0; ijkl < norb * norb * norb * norb; ++ijkl) {
const int i = ijkl / (norb * norb * norb);
const int jkl = ijkl % (norb * norb * norb);
const int j = jkl / (norb * norb);
const int kl = jkl % (norb * norb);
const int k = kl / norb;
const int l = kl % norb;
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
for (int q = 0; q != norb; ++q) {
for (int r = 0; r != norb; ++r) {
const int mat[8] = {i, j, k, l, o, p, q, r};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]] &&
mat[delta[1 * 2 + 0]] == mat[delta[1 * 2 + 1]] &&
mat[delta[2 * 2 + 0]] == mat[delta[2 * 2 + 1]]) {
target[r + norb * (q + norb * (p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))))]
+= factor * source[mat[indices[1]] + norb * mat[indices[0]]];
}
}
}
}
}
}
} else if (srank == 2 && trank == 4) {
#pragma omp parallel for schedule(static)
for (int ijkl = 0; ijkl < norb * norb * norb * norb; ++ijkl) {
const int i = ijkl / (norb * norb * norb);
const int jkl = ijkl % (norb * norb * norb);
const int j = jkl / (norb * norb);
const int kl = jkl % (norb * norb);
const int k = kl / norb;
const int l = kl % norb;
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
for (int q = 0; q != norb; ++q) {
for (int r = 0; r != norb; ++r) {
const int mat[8] = {i, j, k, l, o, p, q, r};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]] &&
mat[delta[1 * 2 + 0]] == mat[delta[1 * 2 + 1]]) {
target[r + norb * (q + norb * (p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))))]
+= factor * source[mat[indices[3]]
+ norb * (mat[indices[2]]
+ norb * (mat[indices[1]]
+ norb * mat[indices[0]]))];
}
}
}
}
}
}
} else if (srank == 3 && trank == 4) {
#pragma omp parallel for schedule(static)
for (int ijkl = 0; ijkl < norb * norb * norb * norb; ++ijkl) {
const int i = ijkl / (norb * norb * norb);
const int jkl = ijkl % (norb * norb * norb);
const int j = jkl / (norb * norb);
const int kl = jkl % (norb * norb);
const int k = kl / norb;
const int l = kl % norb;
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
for (int q = 0; q != norb; ++q) {
for (int r = 0; r != norb; ++r) {
const int mat[8] = {i, j, k, l, o, p, q, r};
if (mat[delta[0 * 2 + 0]] == mat[delta[0 * 2 + 1]]) {
target[r + norb * (q + norb * (p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))))]
+= factor * source[mat[indices[5]]
+ norb * (mat[indices[4]]
+ norb * (mat[indices[3]]
+ norb * (mat[indices[2]]
+ norb * (mat[indices[1]]
+ norb * mat[indices[0]]))))];
}
}
}
}
}
}
} else if (srank == 4 && trank == 4) {
#pragma omp parallel for schedule(static)
for (int ijkl = 0; ijkl < norb * norb * norb * norb; ++ijkl) {
const int i = ijkl / (norb * norb * norb);
const int jkl = ijkl % (norb * norb * norb);
const int j = jkl / (norb * norb);
const int kl = jkl % (norb * norb);
const int k = kl / norb;
const int l = kl % norb;
for (int o = 0; o != norb; ++o) {
for (int p = 0; p != norb; ++p) {
for (int q = 0; q != norb; ++q) {
for (int r = 0; r != norb; ++r) {
const int mat[8] = {i, j, k, l, o, p, q, r};
target[r + norb * (q + norb * (p + norb * (o + norb
* (l + norb * (k + norb * (j + norb * i))))))]
+= factor * source[mat[indices[7]]
+ norb * (mat[indices[6]]
+ norb * (mat[indices[5]]
+ norb * (mat[indices[4]]
+ norb * (mat[indices[3]]
+ norb * (mat[indices[2]]
+ norb * (mat[indices[1]]
+ norb * mat[indices[0]]))))))];
}
}
}
}
}
} else {
assert(false);
}
return 0;
}
|
GB_unaryop__minv_int16_fp32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_int16_fp32
// op(A') function: GB_tran__minv_int16_fp32
// C type: int16_t
// A type: float
// cast: int16_t cij ; GB_CAST_SIGNED(cij,aij,16)
// unaryop: cij = GB_IMINV_SIGNED (aij, 16)
#define GB_ATYPE \
float
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 16) ;
// casting
#define GB_CASTING(z, aij) \
int16_t z ; GB_CAST_SIGNED(z,aij,16) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_INT16 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_int16_fp32
(
int16_t *Cx, // Cx and Ax may be aliased
float *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_int16_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
fibonacci.c | #include <stdio.h>
#include <sys/time.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#define omp_get_num_threads() 1
#define omp_set_num_threads(T) 0
#endif
void gettime(double *t) {
struct timeval tv;
gettimeofday(&tv, (void *)0);
*t = tv.tv_sec + 1.0e-6*tv.tv_usec;
}
long fib_number (int n) {
long fn, fn1, fn2;
if ( n == 0 || n == 1) return(n);
if ( n < 20 )
return (fib_number(n-1) + fib_number(n-2));
#pragma omp task shared(fn1)
{
fn1 = fib_number(n-1);
}
#pragma omp task shared(fn2)
{
fn2 = fib_number(n-2);
}
#pragma omp taskwait
fn = fn1 + fn2;
return(fn);
}
int main (int argc, char* argv[]) {
long result;
int N = 0;
int i;
double initial, final, temp;
int num_threads;
if (argv[1] != NULL)
N = atoi(argv[1]);
gettime(&initial);
#pragma omp parallel
{
#pragma omp single nowait
{
num_threads = omp_get_num_threads();
for (i=1; i<N; i++) {
result = fib_number(i);
printf("%lu, ",result);
}
}
}
printf("...\n");
gettime(&final);
temp = final - initial;
printf(" Final Time = %f\n Numbers %d\n", temp, num_threads);
}
|
SimpleParallel.c | #include <omp.h>
#include <stdio.h>
#include <math.h>
#define ARRAYSIZE 10000000 // you decide
#define NUMTRIES 100 // you decide
float A[ARRAYSIZE];
float B[ARRAYSIZE];
float C[ARRAYSIZE];
int
main( )
{
#ifndef _OPENMP
fprintf( stderr, "OpenMP is not supported here -- sorry.\n" );
return 1;
#endif
omp_set_num_threads( NUMT );
fprintf( stderr, "Using %d threads\n", NUMT );
double maxMegaMults = 0.;
double sumMegaMults = 0.;
double time=0.;
for( int t = 0; t < NUMTRIES; t++ )
{
double time0 = omp_get_wtime( );
#pragma omp parallel for
for( int i = 0; i < ARRAYSIZE; i++ )
{
C[i] = A[i] * B[i];
}
double time1 = omp_get_wtime( );
double megaMults = (double)ARRAYSIZE/(time1-time0)/1000000.;
sumMegaMults += megaMults;
if( megaMults > maxMegaMults )
maxMegaMults = megaMults;
time+=time1-time0;
}
double avgMegaMults = sumMegaMults/(double)NUMTRIES;
printf("NUM Tries = %d \nExecution time = %lf\n",NUMT,NUMTRIES,time/NUMTRIES);
printf( "Peak Performance = %8.2lf MegaMults/Sec\n", maxMegaMults );
printf( "Average Performance = %8.2lf MegaMults/Sec\n", avgMegaMults );
// note: %lf stands for "long float", which is what printf calls a "double"
// %d stands for "decimal integer", not "double"
return 0;
}
|
utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file utils.h
* \brief Basic utilility functions.
*/
#ifndef MXNET_COMMON_UTILS_H_
#define MXNET_COMMON_UTILS_H_
#include <dmlc/logging.h>
#include <dmlc/omp.h>
#include <nnvm/graph.h>
#include <nnvm/node.h>
#include <mxnet/imperative.h>
#include <mxnet/engine.h>
#include <mxnet/ndarray.h>
#include <mxnet/storage.h>
#include <mxnet/op_attr_types.h>
#include <mxnet/graph_attr_types.h>
#include <nnvm/graph_attr_types.h>
#include <memory>
#include <vector>
#include <type_traits>
#include <utility>
#include <random>
#include <string>
#include <thread>
#include <algorithm>
#include <functional>
#include <limits>
#include "../operator/mxnet_op.h"
#if MXNET_USE_ONEDNN == 1
#include "../operator/nn/dnnl/dnnl_base-inl.h"
#endif
#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
#include <windows.h>
#else
#include <unistd.h>
#endif
namespace mxnet {
namespace common {
#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
inline size_t current_process_id() {
return ::GetCurrentProcessId();
}
#else
inline size_t current_process_id() {
return getpid();
}
#endif
/*!
* \brief IndPtr should be non-negative, in non-decreasing order, start with 0
* and end with value equal with size of indices.
*/
struct csr_indptr_check {
template <typename DType, typename IType>
MSHADOW_XINLINE static void Map(int i,
DType* out,
const IType* indptr,
const nnvm::dim_t end,
const nnvm::dim_t idx_size) {
if (indptr[i + 1] < 0 || indptr[i + 1] < indptr[i] || (i == 0 && indptr[i] != 0) ||
(i == end - 1 && indptr[end] != idx_size))
*out = kCSRIndPtrErr;
}
};
/*!
* \brief Indices should be non-negative, less than the number of columns
* and in ascending order per row.
*/
struct csr_idx_check {
template <typename DType, typename IType, typename RType>
MSHADOW_XINLINE static void Map(int i,
DType* out,
const IType* idx,
const RType* indptr,
const nnvm::dim_t ncols) {
for (RType j = indptr[i]; j < indptr[i + 1]; j++) {
if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i + 1] - 1 && idx[j] >= idx[j + 1])) {
*out = kCSRIdxErr;
break;
}
}
}
};
/*!
* \brief Indices of RSPNDArray should be non-negative,
* less than the size of first dimension and in ascending order
*/
struct rsp_idx_check {
template <typename DType, typename IType>
MSHADOW_XINLINE static void Map(int i,
DType* out,
const IType* idx,
const nnvm::dim_t end,
const nnvm::dim_t nrows) {
if ((i < end && idx[i + 1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows)
*out = kRSPIdxErr;
}
};
template <typename xpu>
void CheckFormatWrapper(const RunContext& rctx,
const NDArray& input,
const TBlob& err_cpu,
const bool full_check);
/*!
* \brief Check the validity of CSRNDArray.
* \param rctx Execution context.
* \param input Input NDArray of CSRStorage.
* \param err_cpu Error number on cpu.
* \param full_check If true, rigorous check, O(N) operations,
* otherwise basic check, O(1) operations.
*/
template <typename xpu>
void CheckFormatCSRImpl(const RunContext& rctx,
const NDArray& input,
const TBlob& err_cpu,
const bool full_check) {
using namespace op::mxnet_op;
CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray";
const mxnet::TShape shape = input.shape();
const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx);
const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr);
const mxnet::TShape storage_shape = input.storage_shape();
if ((shape.ndim() != 2) ||
(idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) ||
(indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) {
MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
DType* err = err_cpu.dptr<DType>();
*err = kCSRShapeErr;
});
return;
}
if (full_check) {
MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, {
MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, {
mshadow::Stream<xpu>* s = rctx.get_stream<xpu>();
NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_);
TBlob val_xpu = ret_xpu.data();
Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>());
Kernel<csr_indptr_check, xpu>::Launch(s,
indptr_shape[0] - 1,
val_xpu.dptr<DType>(),
input.aux_data(csr::kIndPtr).dptr<RType>(),
indptr_shape[0] - 1,
idx_shape[0]);
// no need to check indices if indices are empty
if (idx_shape[0] != 0) {
Kernel<csr_idx_check, xpu>::Launch(s,
indptr_shape[0] - 1,
val_xpu.dptr<DType>(),
input.aux_data(csr::kIdx).dptr<IType>(),
input.aux_data(csr::kIndPtr).dptr<RType>(),
shape[1]);
}
mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s);
});
});
});
}
}
/*!
* \brief Check the validity of RowSparseNDArray.
* \param rctx Execution context.
* \param input Input NDArray of RowSparseStorage.
* \param err_cpu Error number on cpu.
* \param full_check If true, rigorous check, O(N) operations,
* otherwise basic check, O(1) operations.
*/
template <typename xpu>
void CheckFormatRSPImpl(const RunContext& rctx,
const NDArray& input,
const TBlob& err_cpu,
const bool full_check) {
using namespace op::mxnet_op;
CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray";
const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx);
if (idx_shape[0] != input.storage_shape()[0]) {
MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
DType* err = err_cpu.dptr<DType>();
*err = kRSPShapeErr;
});
return;
}
if (idx_shape[0] == 0) {
return;
}
if (full_check) {
MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, {
MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, {
mshadow::Stream<xpu>* s = rctx.get_stream<xpu>();
NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_);
TBlob val_xpu = ret_xpu.data();
Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>());
Kernel<rsp_idx_check, xpu>::Launch(s,
idx_shape[0],
val_xpu.dptr<DType>(),
input.aux_data(rowsparse::kIdx).dptr<IType>(),
idx_shape[0] - 1,
input.shape()[0]);
mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s);
});
});
}
}
template <typename xpu>
void CheckFormatImpl(const RunContext& rctx,
const NDArray& input,
const TBlob& err_cpu,
const bool full_check) {
int stype = input.storage_type();
if (stype == kCSRStorage) {
CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check);
} else if (stype == kRowSparseStorage) {
CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check);
} else if (stype == kDefaultStorage) {
// no-op for default storage
} else {
LOG(FATAL) << "Unknown storage type " << stype;
}
}
/*! \brief Pick rows specified by user input index array from a row sparse ndarray
* and save them in the output sparse ndarray.
*/
template <typename xpu>
void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu>* s,
const NDArray& input_nd,
const TBlob& idx_data,
const OpReqType req,
NDArray* output_nd);
/* \brief Casts tensor storage type to the new type.
*/
template <typename xpu>
void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output);
/*! \brief returns true if all storage types in `vstorage` are the same as target `stype`.
* false is returned for empty inputs.
*/
inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) {
if (!vstorage.empty()) {
for (const auto& i : vstorage) {
if (i != stype)
return false;
}
return true;
}
return false;
}
/*! \brief returns true if all storage types in `vstorage` are the same as target `stype1`
* or `stype2'. Sets boolean if both found.
* false is returned for empty inputs.
*/
inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage,
const NDArrayStorageType stype1,
const NDArrayStorageType stype2,
bool* has_both) {
if (has_both) {
*has_both = false;
}
if (!vstorage.empty()) {
uint8_t has = 0;
for (const auto i : vstorage) {
if (i == stype1) {
has |= 1;
} else if (i == stype2) {
has |= 2;
} else {
return false;
}
}
if (has_both) {
*has_both = has == 3;
}
return true;
}
return false;
}
/*! \brief returns true if the storage types of arrays in `ndarrays`
* are the same as target `stype`. false is returned for empty inputs.
*/
inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays,
const NDArrayStorageType stype) {
if (!ndarrays.empty()) {
for (const auto& nd : ndarrays) {
if (nd.storage_type() != stype) {
return false;
}
}
return true;
}
return false;
}
/*! \brief returns true if the storage types of arrays in `ndarrays`
* are the same as targets `stype1` or `stype2`. false is returned for empty inputs.
*/
inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays,
const NDArrayStorageType stype1,
const NDArrayStorageType stype2,
bool* has_both) {
if (has_both) {
*has_both = false;
}
if (!ndarrays.empty()) {
uint8_t has = 0;
for (const auto& nd : ndarrays) {
const NDArrayStorageType stype = nd.storage_type();
if (stype == stype1) {
has |= 1;
} else if (stype == stype2) {
has |= 2;
} else {
return false;
}
}
if (has_both) {
*has_both = has == 3;
}
return true;
}
return false;
}
/*! \brief returns true if storage type of any array in `ndarrays`
* is the same as the target `stype`. false is returned for empty inputs.
*/
inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays,
const NDArrayStorageType stype) {
if (!ndarrays.empty()) {
for (const auto& nd : ndarrays) {
if (nd.storage_type() == stype) {
return true;
}
}
}
return false;
}
/*! \brief returns true if any storage type `ndstype` in `ndstypes`
* is the same as the target `stype`. false is returned for empty inputs.
*/
inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) {
if (!ndstypes.empty()) {
for (const auto& ndstype : ndstypes) {
if (ndstype == stype) {
return true;
}
}
}
return false;
}
/*! \brief get string representation of dispatch_mode */
inline std::string dispatch_mode_string(const DispatchMode x) {
switch (x) {
case DispatchMode::kFCompute:
return "fcompute";
case DispatchMode::kFComputeEx:
return "fcompute_ex";
case DispatchMode::kFComputeFallback:
return "fcompute_fallback";
case DispatchMode::kVariable:
return "variable";
case DispatchMode::kUndefined:
return "undefined";
}
return "unknown";
}
/*! \brief get string representation of storage_type */
inline std::string stype_string(const int x) {
switch (x) {
case kDefaultStorage:
return "default";
case kCSRStorage:
return "csr";
case kRowSparseStorage:
return "row_sparse";
}
return "unknown";
}
/*! \brief get string representation of device type */
inline std::string dev_type_string(const int dev_type) {
switch (dev_type) {
case Context::kCPU:
return "cpu";
case Context::kGPU:
return "gpu";
case Context::kCPUPinned:
return "cpu_pinned";
case Context::kCPUShared:
return "cpu_shared";
}
return "unknown";
}
inline std::string attr_value_string(const nnvm::NodeAttrs& attrs,
const std::string& attr_name,
std::string default_val = "") {
if (attrs.dict.find(attr_name) == attrs.dict.end()) {
return default_val;
}
return attrs.dict.at(attr_name);
}
/*! \brief get string representation of the operator stypes */
inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs,
const int dev_mask,
const std::vector<int>& in_attrs,
const std::vector<int>& out_attrs) {
std::ostringstream os;
os << "operator = " << attrs.op->name << "\ninput storage types = [";
for (const int attr : in_attrs) {
os << stype_string(attr) << ", ";
}
os << "]\n"
<< "output storage types = [";
for (const int attr : out_attrs) {
os << stype_string(attr) << ", ";
}
os << "]\n"
<< "params = {";
for (auto kv : attrs.dict) {
os << "\"" << kv.first << "\" : " << kv.second << ", ";
}
os << "}\n"
<< "context.dev_mask = " << dev_type_string(dev_mask);
return os.str();
}
/*! \brief get string representation of the operator */
inline std::string operator_string(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
std::string result = "";
std::vector<int> in_stypes;
std::vector<int> out_stypes;
in_stypes.reserve(inputs.size());
out_stypes.reserve(outputs.size());
auto xform = [](const NDArray arr) -> int { return arr.storage_type(); };
std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform);
std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform);
result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes);
return result;
}
/*! \brief log message once. Intended for storage fallback warning messages. */
inline void LogOnce(const std::string& message) {
typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore;
auto log_store = LogStore::Get();
if (log_store->find(message) == log_store->end()) {
LOG(INFO) << message;
log_store->insert(message);
}
}
/*! \brief log storage fallback event
*/
inline void LogStorageFallback(const nnvm::NodeAttrs& attrs,
const int dev_mask,
const std::vector<int>* in_attrs,
const std::vector<int>* out_attrs) {
static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true);
if (!log)
return;
const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs);
std::ostringstream os;
const char* warning =
"\n WARNING:\n"
"Execution of the operator above will fallback to the generic implementation "
#if MXNET_USE_ONEDNN == 1
"(not utilizing kernels from oneDNN library) "
#endif
"with default dense storage type. You are seeing this warning message because "
#if MXNET_USE_ONEDNN == 1
"MXNET_ONEDNN_ENABLED flag is set to 0, in which case you can re-enable the default "
"execution path by setting MXNET_ONEDNN_ENABLED back to 1, or "
#endif
"the operator above is unable to process the given ndarrays with specified storage types, "
"context and/or parameter, in which case temporary dense ndarrays are generated in order to "
"execute the operator. The fallback does not affect the correctness of the programme. Using "
"default storage type performance degradation might be observed. \nYou can set environment "
"variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to 0 to suppress this warning.";
os << "\nStorage type fallback detected:\n" << op_str << warning;
LogOnce(os.str());
#if MXNET_USE_ONEDNN == 1
if (GetDNNLCacheSize() != -1)
common::LogOnce(
"MXNET_ONEDNN_CACHE_NUM is set."
"Should only be set if "
"your model has variable input shapes, "
"as cache size may grow unbounded");
#endif
}
// heuristic to dermine number of threads per GPU
inline int GetNumThreadsPerGPU() {
// This is resource efficient option.
return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2);
}
// heuristic to get number of matching colors.
// this decides how much parallelism we can get in each GPU.
inline int GetExecNumMatchColor() {
// This is resource efficient option.
int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1);
return std::min(num_match_color, GetNumThreadsPerGPU());
}
template <typename T, typename V>
V ParallelAccumulate(const T* a, const int n, V start) {
V sum = start;
#pragma omp parallel for reduction(+ : sum)
for (int i = 0; i < n; ++i) {
sum += a[i];
}
return sum;
}
/*!
* \brief
* Helper function for ParallelSort.
* DO NOT call this function directly.
* Use the interface ParallelSort instead.
* Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h
*/
template <typename RandomIt, typename Compare>
void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) {
if (len < grainsize) {
std::sort(first, first + len, comp);
} else {
std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len / 2, grainsize, comp);
ParallelSortHelper(first + len / 2, len - len / 2, grainsize, comp);
thr.join();
std::inplace_merge(first, first + len / 2, first + len, comp);
}
}
/*!
* \brief
* Sort the elements in the range [first, last) into the ascending order defined by
* the comparator comp.
* If the length of the range [first, last) is greater than a certain threshold,
* the range will be recursively divided into two and assign two threads
* to sort each half range.
* Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h
*/
template <typename RandomIt, typename Compare>
void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) {
const auto num = std::distance(first, last);
size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024 * 16));
ParallelSortHelper(first, num, grainsize, comp);
}
/*!
* \brief
* Sort the elements in the range [first, last) into ascending order.
* The elements are compared using the default < operator.
* If the length of the range [first, last) is greater than a certain threshold,
* the range will be recursively divided into two and assign two threads
* to sort each half range.
* Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h
*/
template <typename RandomIt>
void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) {
ParallelSort(
first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>());
}
/*!
* \brief Random Engine
*/
typedef std::mt19937 RANDOM_ENGINE;
/*!
* \brief Helper functions.
*/
namespace helper {
/*!
* \brief Helper for non-array type `T`.
*/
template <class T>
struct UniqueIf {
/*!
* \brief Type of `T`.
*/
using SingleObject = std::unique_ptr<T>;
};
/*!
* \brief Helper for an array of unknown bound `T`.
*/
template <class T>
struct UniqueIf<T[]> {
/*!
* \brief Type of `T`.
*/
using UnknownBound = std::unique_ptr<T[]>;
};
/*!
* \brief Helper for an array of known bound `T`.
*/
template <class T, size_t kSize>
struct UniqueIf<T[kSize]> {
/*!
* \brief Type of `T`.
*/
using KnownBound = void;
};
} // namespace helper
/*!
* \brief Constructs an object of type `T` and wraps it in a
* `std``::``unique_ptr`.
* \param args List of arguments with which an instance of `T` will be
* constructed.
* \return `std``::``unique_ptr` of an instance of type `T`.
*
* Constructs a non-array type `T`. The arguments `args` are passed to the
* constructor of `T`. The function does not participate in the overload
* resolution if `T` is an array type.
*/
template <class T, class... Args>
typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
/*!
* \brief Constructs an object of type `T` and wraps it in a
* `std``::``unique_ptr`.
* \param n The size of the array to construct.
* \return `std``::``unique_ptr` of an instance of type `T`.
*
* Constructs an array of unknown bound `T`. The function does not participate
* in the overload resolution unless `T` is an array of unknown bound.
*/
template <class T>
typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) {
using U = typename std::remove_extent<T>::type;
return std::unique_ptr<T>(new U[n]{});
}
/*!
* \brief Constructs an object of type `T` and wraps it in a
* `std``::``unique_ptr`.
* \param args List of arguments with which an instance of `T` will be
* constructed.
*
* Constructs an arrays of known bound is disallowed.
*/
template <class T, class... Args>
typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete;
template <typename FCompType>
FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) {
static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>");
static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>");
if (ctx.dev_mask() == cpu::kDevMask) {
return fcompute_cpu.get(op, nullptr);
} else if (ctx.dev_mask() == gpu::kDevMask) {
return fcompute_gpu.get(op, nullptr);
} else {
LOG(FATAL) << "Unknown device mask " << ctx.dev_mask();
return nullptr;
}
}
/*!
* \brief Return the max integer value representable in the type `T` without loss of precision.
*/
template <typename T>
constexpr size_t MaxIntegerValue() {
return std::is_integral<T>::value ? std::numeric_limits<T>::max()
: size_t(2) << (std::numeric_limits<T>::digits - 1);
}
template <>
constexpr size_t MaxIntegerValue<mshadow::half::half_t>() {
return size_t(2) << 10;
}
template <>
constexpr size_t MaxIntegerValue<mshadow::bfloat::bf16_t>() {
return size_t(2) << 14;
}
MSHADOW_XINLINE int ilog2ul(size_t a) {
int k = 1;
while (a >>= 1)
++k;
return k;
}
MSHADOW_XINLINE int ilog2ui(unsigned int a) {
int k = 1;
while (a >>= 1)
++k;
return k;
}
/*!
* \brief Return an NDArray of all zeros.
*/
inline NDArray InitZeros(const NDArrayStorageType stype,
const mxnet::TShape& shape,
const Context& ctx,
const int dtype) {
// NDArray with default storage
if (stype == kDefaultStorage) {
NDArray ret(shape, ctx, false, dtype);
ret = 0;
return ret;
}
// NDArray with non-default storage. Storage allocation is always delayed.
return NDArray(stype, shape, ctx, true, dtype);
}
/*!
* \brief Helper to add a NDArray of zeros to a std::vector.
*/
inline void EmplaceBackZeros(const NDArrayStorageType stype,
const mxnet::TShape& shape,
const Context& ctx,
const int dtype,
std::vector<NDArray>* vec) {
// NDArray with default storage
if (stype == kDefaultStorage) {
vec->emplace_back(shape, ctx, false, dtype);
vec->back() = 0;
} else {
// NDArray with non-default storage. Storage allocation is always delayed.
vec->emplace_back(stype, shape, ctx, true, dtype);
}
}
/*!
* \brief parallelize copy by OpenMP.
*/
template <typename DType>
inline void ParallelCopy(DType* dst, const DType* src, index_t size) {
static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000);
if (size >= copy_block_size) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t i = 0; i < size; ++i) {
dst[i] = src[i];
}
} else {
#pragma GCC diagnostic push
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
std::memcpy(dst, src, sizeof(DType) * size);
#pragma GCC diagnostic pop
}
}
/*!
* \breif parallelize add by OpenMP
*/
template <typename DType>
inline void ParallelAdd(DType* dst, const DType* src, index_t size) {
static index_t add_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000);
if (size >= add_block_size) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t i = 0; i < size; ++i) {
dst[i] += src[i];
}
} else {
for (index_t i = 0; i < size; ++i) {
dst[i] += src[i];
}
}
}
/*!
* \brief If numpy compatibility is turned off (default), the shapes passed in
* by users follow the legacy shape definition:
* 1. 0 ndim means the shape is completely unknown.
* 2. 0 dim size means the dim size is unknown.
* We need to convert those shapes to use the numpy shape definition:
* 1. 0 ndim means it's a scalar tensor.
* 2. -1 ndim means the shape is unknown.
* 3. 0 dim size means no elements in that dimension.
* 4. -1 dim size means the dimension's size is unknown.
* so that operator's infer shape function can work in backend.
* \param shape to be converted.
* Note: It is possible that the shape to be converted is already
* numpy compatible. For example, when a subgraph operator's infer
* shape function is called from the infer shape pass of the whole
* graph, its input/output shapes have been converted to numpy
* compatible shapes.
*/
inline void ConvertToNumpyShape(mxnet::TShape* shape) {
if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown
*shape = mxnet::TShape(); // unknown shape ndim = -1
} else {
for (int j = 0; j < shape->ndim(); ++j) {
if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown
(*shape)[j] = -1; // unknown dim size = -1
}
}
}
}
inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) {
for (size_t i = 0; i < shapes->size(); ++i) {
ConvertToNumpyShape(&(shapes->at(i)));
}
}
/*!
* \brief This is function is used to convert shapes returned by
* the infer shape functions/pass to the legacy shape definition.
*/
inline void ConvertToLegacyShape(mxnet::TShape* shape) {
if (!mxnet::ndim_is_known(*shape)) {
*shape = mxnet::TShape(0, -1);
} else {
for (int j = 0; j < shape->ndim(); ++j) {
if (!mxnet::dim_size_is_known(*shape, j)) {
(*shape)[j] = 0;
}
}
}
}
inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) {
for (size_t i = 0; i < shapes->size(); ++i) {
ConvertToLegacyShape(&(shapes->at(i)));
}
}
void ExecuteMonInputCallback(
const nnvm::IndexedGraph& idx,
const std::vector<NDArray*>& state_arrays,
size_t nid,
const std::function<void(const char*, const char*, void*)>& monitor_callback);
void ExecuteMonOutputCallback(
const nnvm::IndexedGraph& idx,
const std::vector<NDArray*>& state_arrays,
size_t nid,
const std::function<void(const char*, const char*, void*)>& monitor_callback);
inline mxnet::TShape CanonicalizeAxes(const mxnet::TShape& src) {
// convert negative axes to positive values
const int ndim = src.ndim();
mxnet::TShape axes = src;
for (int i = 0; i < ndim; ++i) {
if (axes[i] < 0) {
axes[i] += ndim;
}
CHECK(axes[i] >= 0 && axes[i] < ndim)
<< "axes[" << i << "]=" << axes[i] << " exceeds the range [" << 0 << ", " << ndim << ")";
}
return axes;
}
inline bool is_float(const int dtype) {
return dtype == mshadow::kFloat32 || dtype == mshadow::kFloat64 || dtype == mshadow::kFloat16;
}
inline bool is_int(const int dtype) {
return dtype == mshadow::kUint8 || dtype == mshadow::kInt8 || dtype == mshadow::kInt32 ||
dtype == mshadow::kInt64;
}
inline int get_more_precise_type(const int type1, const int type2) {
if (type1 == type2)
return type1;
if (is_float(type1) && is_float(type2)) {
if (type1 == mshadow::kFloat64 || type2 == mshadow::kFloat64) {
return mshadow::kFloat64;
}
if (type1 == mshadow::kFloat32 || type2 == mshadow::kFloat32) {
return mshadow::kFloat32;
}
return mshadow::kFloat16;
} else if (is_float(type1) || is_float(type2)) {
return is_float(type1) ? type1 : type2;
}
if (type1 == mshadow::kInt64 || type2 == mshadow::kInt64) {
return mshadow::kInt64;
}
if (type1 == mshadow::kInt32 || type2 == mshadow::kInt32) {
return mshadow::kInt32;
}
CHECK(!((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) ||
(type1 == mshadow::kInt8 && type2 == mshadow::kUint8)))
<< "1 is UInt8 and 1 is Int8 should not get here";
if (type1 == mshadow::kUint8 || type2 == mshadow::kUint8) {
return mshadow::kUint8;
}
return mshadow::kInt8;
}
inline int np_binary_out_infer_type(const int type1, const int type2) {
if ((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) ||
(type1 == mshadow::kInt8 && type2 == mshadow::kUint8)) {
return mshadow::kInt32;
}
return get_more_precise_type(type1, type2);
}
inline const std::string NodeAttrsGetProfilerScope(const nnvm::NodeAttrs& attrs) {
// obtain the profiler scope name, if assigned previously
std::string profiler_scope = MXNET_STORAGE_DEFAULT_PROFILER_SCOPE_CSTR;
const std::unordered_map<std::string, std::string>& node_attrs_dict = attrs.dict;
const std::unordered_map<std::string, std::string>::const_iterator profiler_scope_iter =
node_attrs_dict.find("__profiler_scope__");
if (profiler_scope_iter != node_attrs_dict.end()) {
profiler_scope = profiler_scope_iter->second;
}
return profiler_scope;
}
inline int GetDefaultDtype() {
return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32;
}
inline int GetDefaultDtype(int dtype) {
if (dtype != -1)
return dtype;
return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32;
}
struct MShadowTypeInfo {
std::string name;
int size;
int acc_size;
MShadowTypeInfo(const std::string name, const int size, const int acc_size)
: name(std::move(name)), size(size), acc_size(acc_size) {}
MShadowTypeInfo(const std::string name, const int size) : MShadowTypeInfo(name, size, size) {}
};
MShadowTypeInfo mshadow_type_info(const int type_flag);
inline bool AlignedMemAlloc(void** ptr, size_t size, size_t alignment) {
#if _MSC_VER
*ptr = _aligned_malloc(size, alignment);
if (*ptr == nullptr)
return false;
#else
int res = posix_memalign(ptr, alignment, size);
if (res != 0)
return false;
#endif
return true;
}
inline void AlignedMemFree(void* ptr) {
#if _MSC_VER
_aligned_free(ptr);
#else
free(ptr);
#endif
}
inline index_t div_round(const index_t a, const index_t b) {
return (a + b - 1) / b;
}
inline bool IsPower2(size_t N) {
return ((N & (N - 1)) == 0) && N != 0;
}
inline size_t RoundToPower2(size_t N) {
size_t ret = 1;
size_t copyN = N;
while (N >= 2) {
ret *= 2;
N /= 2;
}
if (ret < copyN) {
ret *= 2;
}
return ret;
}
} // namespace common
} // namespace mxnet
#endif // MXNET_COMMON_UTILS_H_
|
3mm-tile-no.c | /**
* 3mm.c: This file is part of the PolyBench/C 3.2 test suite.
* with tiling 16x16 and nested SIMD
*
* Contact: Louis-Noel Pouchet <pouchet@cse.ohio-state.edu>
* Web address: http://polybench.sourceforge.net
* License: /LICENSE.OSU.txt
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "3mm.h"
/* Array initialization. */
static void init_array(int ni,int nj,int nk,int nl,int nm,double A[128 + 0][128 + 0],double B[128 + 0][128 + 0],double C[128 + 0][128 + 0],double D[128 + 0][128 + 0])
{
//int i;
//int j;
{
int c3;
int c4;
int c1;
int c2;
if (ni >= ((0 > -1 * nj + -1 * nm + 1?0 : -1 * nj + -1 * nm + 1)) && nj >= 0 && nk >= ((0 > -1 * nm + 1?0 : -1 * nm + 1)) && nm >= 0) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((((nk + ni + nj + nm + -1) * 16 < 0?((16 < 0?-((-(nk + ni + nj + nm + -1) + 16 + 1) / 16) : -((-(nk + ni + nj + nm + -1) + 16 - 1) / 16))) : (nk + ni + nj + nm + -1) / 16)) < (((nk + ni + nj + 2 * nm + -2) * 16 < 0?((16 < 0?-((-(nk + ni + nj + 2 * nm + -2) + 16 + 1) / 16) : -((-(nk + ni + nj + 2 * nm + -2) + 16 - 1) / 16))) : (nk + ni + nj + 2 * nm + -2) / 16))?(((nk + ni + nj + nm + -1) * 16 < 0?((16 < 0?-((-(nk + ni + nj + nm + -1) + 16 + 1) / 16) : -((-(nk + ni + nj + nm + -1) + 16 - 1) / 16))) : (nk + ni + nj + nm + -1) / 16)) : (((nk + ni + nj + 2 * nm + -2) * 16 < 0?((16 < 0?-((-(nk + ni + nj + 2 * nm + -2) + 16 + 1) / 16) : -((-(nk + ni + nj + 2 * nm + -2) + 16 - 1) / 16))) : (nk + ni + nj + 2 * nm + -2) / 16)))); c1++) {
if (c1 <= (((((((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = 0; c2 <= (((((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nk + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nk + -1)) < nm + -1?((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nk + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) < nl + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) : nl + -1)) < nm + -1?((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) < nl + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) : nl + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) < nl + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nl > nm?nl : nm); c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nj > nm?nj : nm); c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (((nj > nl?nj : nl)) > nm?((nj > nl?nj : nl)) : nm); c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nk > nl?nk : nl); c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nk > nm?nk : nm); c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (((nk > nl?nk : nl)) > nm?((nk > nl?nk : nl)) : nm); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = (nj > nk?nj : nk); c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (((nj > nk?nj : nk)) > nl?((nj > nk?nj : nk)) : nl); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (((nj > nk?nj : nk)) > nm?((nj > nk?nj : nk)) : nm); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nk + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
for (c3 = nj; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)) < nm + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nl + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (nj > nm?nj : nm); c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
for (c3 = nk; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nm + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nk; c4 <= ((((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)) < nm + -1?((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = (nk > nl?nk : nl); c4 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (nk > nm?nk : nm); c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= nk + -1; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nk; c4 <= nm + -1; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
for (c3 = (nj > nk?nj : nk); c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (((nj > nk?nj : nk)) > nm?((nj > nk?nj : nk)) : nm); c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)) < nm + -1?((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nl > nm?nl : nm); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nj > nm?nj : nm); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = (ni > nm?ni : nm); c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
for (c3 = (ni > nj?ni : nj); c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (((ni > nj?ni : nj)) > nm?((ni > nj?ni : nj)) : nm); c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = (ni > nk?ni : nk); c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (((ni > nk?ni : nk)) > nm?((ni > nk?ni : nk)) : nm); c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = (((ni > nj?ni : nj)) > nk?((ni > nj?ni : nj)) : nk); c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nk + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nj; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = (nj > nk?nj : nk); c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= 16 * c2 + 15; c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = (ni > nj?ni : nj); c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = (ni > nk?ni : nk); c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nk + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nj > nm?nj : nm); c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nk > nm?nk : nm); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = (nj > nk?nj : nk); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
for (c3 = nk; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
for (c3 = (nj > nk?nj : nk); c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = (ni > nj?ni : nj); c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = (ni > nk?ni : nk); c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)) < nm + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = nm; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = nk; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = (nk > nm?nk : nm); c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = (ni > nm?ni : nm); c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = (ni > nk?ni : nk); c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) < nl + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nk > nl?nk : nl); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = (nj > nk?nj : nk); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = (ni > nm?ni : nm); c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))))) {
for (c2 = (((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) < nm + -1?((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nk > nl?nk : nl); c4 <= 16 * c2 + 15; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nm; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nk; c4 <= 16 * c2 + 15; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = (nj > nm?nj : nm); c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= 16 * c2 + 15; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = (ni > nm?ni : nm); c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = (ni > nj?ni : nj); c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) && c1 >= ((((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)))) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nl > nm?nl : nm); c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nk > nl?nk : nl); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nk > nm?nk : nm); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = (ni > nj?ni : nj); c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nj + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nm + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nm + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16))) {
for (c2 = (((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)) < nm + -1?((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nl > nm?nl : nm); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nj > nm?nj : nm); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
for (c3 = nj; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (nj > nm?nj : nm); c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (nk > nm?nk : nm); c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = (nj > nk?nj : nk); c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= 16 * c2 + 15; c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = (((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nl > nm?nl : nm); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nj > nm?nj : nm); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nk; c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))) {
for (c2 = (((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nk; c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = (((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))) {
for (c2 = (((((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= 16 * c2 + 15; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nj; c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))); c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nj; c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c2 = (((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) > ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))?((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16)))) : ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))) {
for (c2 = (((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
}
if (ni >= ((0 > -1 * nj + 1?0 : -1 * nj + 1)) && nj >= 0 && nk >= 1 && nm <= -1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((((nk + ni + -1) * 16 < 0?((16 < 0?-((-(nk + ni + -1) + 16 + 1) / 16) : -((-(nk + ni + -1) + 16 - 1) / 16))) : (nk + ni + -1) / 16)) < (((nk + ni + nj + -2) * 16 < 0?((16 < 0?-((-(nk + ni + nj + -2) + 16 + 1) / 16) : -((-(nk + ni + nj + -2) + 16 - 1) / 16))) : (nk + ni + nj + -2) / 16))?(((nk + ni + -1) * 16 < 0?((16 < 0?-((-(nk + ni + -1) + 16 + 1) / 16) : -((-(nk + ni + -1) + 16 - 1) / 16))) : (nk + ni + -1) / 16)) : (((nk + ni + nj + -2) * 16 < 0?((16 < 0?-((-(nk + ni + nj + -2) + 16 + 1) / 16) : -((-(nk + ni + nj + -2) + 16 - 1) / 16))) : (nk + ni + nj + -2) / 16)))); c1++) {
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nk + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nk + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
}
}
if (ni >= 0 && nj <= -1 && nk >= ((0 > -1 * nm + 1?0 : -1 * nm + 1)) && nm >= 0) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((ni + nm + -1) * 16 < 0?((16 < 0?-((-(ni + nm + -1) + 16 + 1) / 16) : -((-(ni + nm + -1) + 16 - 1) / 16))) : (ni + nm + -1) / 16)); c1++) {
if (c1 <= (((((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = 0; c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) < nm + -1?((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) < nl + -1?((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)) : nl + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
#pragma omp simd
for (c4 = nk; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
for (c3 = ni; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((ni * 16 < 0?-(-ni / 16) : ((16 < 0?(-ni + - 16 - 1) / - 16 : (ni + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))) {
for (c2 = (nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))); c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
}
if (nj <= -1 && nk >= 1 && nm <= -1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nk + -1?16 * c2 + 15 : nk + -1)); c4++) {
A[c3][c4] = ((double )c3) * c4 / ni;
}
}
}
}
}
if (ni >= 0 && nj >= 0 && nk <= -1 && nm >= 1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((nj + nm + -1) * 16 < 0?((16 < 0?-((-(nj + nm + -1) + 16 + 1) / 16) : -((-(nj + nm + -1) + 16 - 1) / 16))) : (nj + nm + -1) / 16)); c1++) {
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
}
if (ni >= 0 && nj <= -1 && nk <= -1 && nl >= 1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
if (ni <= -1 && nj >= ((0 > -1 * nm + 1?0 : -1 * nm + 1)) && nk >= ((0 > -1 * nm + 1?0 : -1 * nm + 1)) && nm >= 0) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((((nk + nj + nm + -1) * 16 < 0?((16 < 0?-((-(nk + nj + nm + -1) + 16 + 1) / 16) : -((-(nk + nj + nm + -1) + 16 - 1) / 16))) : (nk + nj + nm + -1) / 16)) < (((nk + nj + 2 * nm + -2) * 16 < 0?((16 < 0?-((-(nk + nj + 2 * nm + -2) + 16 + 1) / 16) : -((-(nk + nj + 2 * nm + -2) + 16 - 1) / 16))) : (nk + nj + 2 * nm + -2) / 16))?(((nk + nj + nm + -1) * 16 < 0?((16 < 0?-((-(nk + nj + nm + -1) + 16 + 1) / 16) : -((-(nk + nj + nm + -1) + 16 - 1) / 16))) : (nk + nj + nm + -1) / 16)) : (((nk + nj + 2 * nm + -2) * 16 < 0?((16 < 0?-((-(nk + nj + 2 * nm + -2) + 16 + 1) / 16) : -((-(nk + nj + 2 * nm + -2) + 16 - 1) / 16))) : (nk + nj + 2 * nm + -2) / 16)))); c1++) {
if (c1 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)) < nm + -1?((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) < nm + -1?((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nl > nm?nl : nm); c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = (nj > nl?nj : nl); c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = (nj > nm?nj : nm); c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
for (c3 = nj; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
if (c1 == c2) {
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c1 + 15 < nl + -1?16 * c1 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
for (c3 = (nj > nm?nj : nm); c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = (nk > nm?nk : nm); c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = (nj > nk?nj : nk); c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)))) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= 16 * c2 + 15; c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= 16 * c2 + 15; c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nk + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nm + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nm + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) < nm + -1?((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) < nl + -1?((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)) : nl + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
#pragma omp simd
for (c4 = nj; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
for (c3 = nk; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16))) {
for (c2 = (((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nj; c3 <= 16 * c1 + 15; c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))))) {
for (c2 = 0; c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((nk * 16 < 0?-(-nk / 16) : ((16 < 0?(-nk + - 16 - 1) / - 16 : (nk + 16 - 1) / 16))))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = (nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))); c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))) {
for (c2 = (((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) > ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))?((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16)))) : ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))); c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
}
if (ni <= -1 && nj >= 1 && nm <= -1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nk + -1?16 * c1 + 15 : nk + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c4++) {
B[c3][c4] = ((double )c3) * (c4 + 1) / nj;
}
}
}
}
}
if (ni <= -1 && nj <= -1 && nk >= 0 && nl >= 1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
if (ni <= -1 && nj >= 0 && nk <= -1 && nm >= 1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((nj + nm + -1) * 16 < 0?((16 < 0?-((-(nj + nm + -1) + 16 + 1) / 16) : -((-(nj + nm + -1) + 16 - 1) / 16))) : (nj + nm + -1) / 16)); c1++) {
if (c1 <= (((((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) < nm + -1?((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)) : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) < nm + -1?((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)) : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
#pragma omp simd
for (c4 = nl; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
#pragma omp simd
for (c4 = nm; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
for (c3 = nm; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
for (c3 = nj; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)) && c1 >= ((nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c2 = (0 > ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))?0 : ((nl * 16 < 0?-(-nl / 16) : ((16 < 0?(-nl + - 16 - 1) / - 16 : (nl + 16 - 1) / 16))))); c2 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nm + -1?16 * c2 + 15 : nm + -1)); c4++) {
C[c3][c4] = ((double )c3) * (c4 + 3) / nl;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)) && c1 >= ((nj * 16 < 0?-(-nj / 16) : ((16 < 0?(-nj + - 16 - 1) / - 16 : (nj + 16 - 1) / 16))))) {
for (c2 = 0; c2 <= (((((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) < (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))?(((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)) : (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)))); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
if (c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16))) {
for (c2 = (nm * 16 < 0?-(-nm / 16) : ((16 < 0?(-nm + - 16 - 1) / - 16 : (nm + 16 - 1) / 16))); c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
}
if (ni <= -1 && nj <= -1 && nk <= -1 && nl >= 1) {
#pragma omp parallel for private(c2, c4, c3)
for (c1 = 0; c1 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < nm + -1?16 * c1 + 15 : nm + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c4++) {
D[c3][c4] = ((double )c3) * (c4 + 2) / nk;
}
}
}
}
}
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static void print_array(int ni,int nl,double G[128 + 0][128 + 0])
{
int i;
int j;
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++) {
fprintf(stderr,"%0.2lf ",G[i][j]);
if ((i * ni + j) % 20 == 0)
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static void kernel_3mm(int ni,int nj,int nk,int nl,int nm,double E[128 + 0][128 + 0],double A[128 + 0][128 + 0],double B[128 + 0][128 + 0],double F[128 + 0][128 + 0],double C[128 + 0][128 + 0],double D[128 + 0][128 + 0],double G[128 + 0][128 + 0])
{
// int i;
// int j;
// int k;
//#pragma scop
{
int c5;
int c10;
int c2;
int c1;
int c6;
int c7;
if (ni >= 0 && nj >= 0 && nl >= 1) {
#pragma omp parallel for private(c7, c2, c10)
for (c1 = 0; c1 <= (((nj + ni + -1) * 16 < 0?((16 < 0?-((-(nj + ni + -1) + 16 + 1) / 16) : -((-(nj + ni + -1) + 16 - 1) / 16))) : (nj + ni + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
if (c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16))) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c10++) {
G[c10][c7] = 0;
}
}
}
if (c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16))) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c10++) {
F[c10][c7] = 0;
}
}
}
}
}
}
if (ni <= -1 && nl >= 1) {
#pragma omp parallel for private(c7, c2, c10)
for (c1 = 0; c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c10++) {
F[c10][c7] = 0;
}
}
}
}
}
if (nj <= -1 && nl >= 1) {
#pragma omp parallel for private(c7, c2, c10)
for (c1 = 0; c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c10++) {
G[c10][c7] = 0;
}
}
}
}
}
if (nl >= 1 && nm >= 1) {
#pragma omp parallel for private(c7, c6, c2, c10, c5)
for (c1 = 0; c1 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c2++) {
for (c5 = 0; c5 <= (((nm + -1) * 16 < 0?((16 < 0?-((-(nm + -1) + 16 + 1) / 16) : -((-(nm + -1) + 16 - 1) / 16))) : (nm + -1) / 16)); c5++) {
for (c6 = 16 * c5; c6 <= ((16 * c5 + 15 < nm + -1?16 * c5 + 15 : nm + -1)); c6++) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nl + -1?16 * c2 + 15 : nl + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < nj + -1?16 * c1 + 15 : nj + -1)); c10++) {
F[c10][c7] += C[c10][c6] * D[c6][c7];
}
}
}
}
}
}
}
if (nj >= 1) {
#pragma omp parallel for private(c7, c2, c10)
for (c1 = 0; c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c2++) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c10++) {
E[c10][c7] = 0;
}
}
}
}
}
if (nj >= 1) {
#pragma omp parallel for private(c7, c6, c2, c10, c5)
for (c1 = 0; c1 <= (((ni + -1) * 16 < 0?((16 < 0?-((-(ni + -1) + 16 + 1) / 16) : -((-(ni + -1) + 16 - 1) / 16))) : (ni + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((nj + -1) * 16 < 0?((16 < 0?-((-(nj + -1) + 16 + 1) / 16) : -((-(nj + -1) + 16 - 1) / 16))) : (nj + -1) / 16)); c2++) {
for (c5 = 0; c5 <= (((nk + -1) * 16 < 0?((16 < 0?-((-(nk + -1) + 16 + 1) / 16) : -((-(nk + -1) + 16 - 1) / 16))) : (nk + -1) / 16)); c5++) {
for (c6 = 16 * c5; c6 <= ((16 * c5 + 15 < nk + -1?16 * c5 + 15 : nk + -1)); c6++) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c10++) {
E[c10][c7] += A[c10][c6] * B[c6][c7];
}
}
}
}
for (c5 = 0; c5 <= (((nl + -1) * 16 < 0?((16 < 0?-((-(nl + -1) + 16 + 1) / 16) : -((-(nl + -1) + 16 - 1) / 16))) : (nl + -1) / 16)); c5++) {
for (c6 = 16 * c5; c6 <= ((16 * c5 + 15 < nl + -1?16 * c5 + 15 : nl + -1)); c6++) {
for (c7 = 16 * c2; c7 <= ((16 * c2 + 15 < nj + -1?16 * c2 + 15 : nj + -1)); c7++) {
#pragma omp simd
for (c10 = 16 * c1; c10 <= ((16 * c1 + 15 < ni + -1?16 * c1 + 15 : ni + -1)); c10++) {
G[c10][c6] += E[c10][c7] * F[c7][c6];
}
}
}
}
}
}
}
}
//#pragma endscop
}
int main(int argc,char **argv)
{
/* Retrieve problem size. */
int ni = 128;
int nj = 128;
int nk = 128;
int nl = 128;
int nm = 128;
/* Variable declaration/allocation. */
double (*E)[128 + 0][128 + 0];
E = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
double (*A)[128 + 0][128 + 0];
A = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
double (*B)[128 + 0][128 + 0];
B = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
double (*F)[128 + 0][128 + 0];
F = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
double (*C)[128 + 0][128 + 0];
C = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
double (*D)[128 + 0][128 + 0];
D = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
double (*G)[128 + 0][128 + 0];
G = ((double (*)[128 + 0][128 + 0])(polybench_alloc_data(((128 + 0) * (128 + 0)),(sizeof(double )))));
;
/* Initialize array(s). */
init_array(ni,nj,nk,nl,nm, *A, *B, *C, *D);
/* Start timer. */
polybench_timer_start();
;
/* Run kernel. */
kernel_3mm(ni,nj,nk,nl,nm, *E, *A, *B, *F, *C, *D, *G);
/* Stop and print timer. */
polybench_timer_stop();
;
polybench_timer_print();
;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
if (argc > 42 && !strcmp(argv[0],""))
print_array(ni,nl, *G);
/* Be clean. */
free(((void *)E));
;
free(((void *)A));
;
free(((void *)B));
;
free(((void *)F));
;
free(((void *)C));
;
free(((void *)D));
;
free(((void *)G));
;
return 0;
}
|
rwpng.c | /*---------------------------------------------------------------------------
pngquant: RGBA -> RGBA-palette quantization program rwpng.c
---------------------------------------------------------------------------
© 1998-2000 by Greg Roelofs.
© 2009-2014 by Kornel Lesiński.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "png.h"
#include "rwpng.h"
#if USE_LCMS
#include "lcms2.h"
#endif
#ifndef Z_BEST_COMPRESSION
#define Z_BEST_COMPRESSION 9
#endif
#ifndef Z_BEST_SPEED
#define Z_BEST_SPEED 1
#endif
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_max_threads() 1
#endif
static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg);
static void rwpng_warning_stderr_handler(png_structp png_ptr, png_const_charp msg);
static void rwpng_warning_silent_handler(png_structp png_ptr, png_const_charp msg);
int rwpng_read_image24_cocoa(FILE *infile, png24_image *mainprog_ptr);
void rwpng_version_info(FILE *fp)
{
const char *pngver = png_get_header_ver(NULL);
#if USE_COCOA
fprintf(fp, " Using libpng %s and Apple Cocoa image reader.\n", pngver);
#elif USE_LCMS
fprintf(fp, " Using libpng %s with Little CMS color profile support.\n", pngver);
#else
fprintf(fp, " Using libpng %s and Apple Cocoa image reader.\n", pngver);
#endif
#if PNG_LIBPNG_VER < 10600
if (strcmp(pngver, "1.3.") < 0) {
fputs("\nWARNING: Your version of libpng is outdated and may produce corrupted files.\n"
"Please recompile pngquant with a newer version of libpng (1.5 or later).\n", fp);
}
#endif
}
struct rwpng_read_data {
FILE *const fp;
png_size_t bytes_read;
};
static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
struct rwpng_read_data *read_data = (struct rwpng_read_data *)png_get_io_ptr(png_ptr);
png_size_t read = fread(data, 1, length, read_data->fp);
if (!read) {
png_error(png_ptr, "Read error");
}
read_data->bytes_read += read;
}
struct rwpng_write_state {
FILE *outfile;
png_size_t maximum_file_size;
png_size_t bytes_written;
pngquant_error retval;
};
static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
struct rwpng_write_state *write_state = (struct rwpng_write_state *)png_get_io_ptr(png_ptr);
if (SUCCESS != write_state->retval) {
return;
}
if (write_state->maximum_file_size && write_state->bytes_written + length > write_state->maximum_file_size) {
write_state->retval = TOO_LARGE_FILE;
}
if (!fwrite(data, 1, length, write_state->outfile)) {
write_state->retval = CANT_WRITE_ERROR;
}
write_state->bytes_written += length;
}
static void user_flush_data(png_structp png_ptr)
{
// libpng never calls this :(
}
static png_bytepp rwpng_create_row_pointers(png_infop info_ptr, png_structp png_ptr, unsigned char *base, unsigned int height, unsigned int rowbytes)
{
if (!rowbytes) {
rowbytes = png_get_rowbytes(png_ptr, info_ptr);
}
png_bytepp row_pointers = malloc(height * sizeof(row_pointers[0]));
if (!row_pointers) return NULL;
for(unsigned int row = 0; row < height; ++row) {
row_pointers[row] = base + row * rowbytes;
}
return row_pointers;
}
static int read_chunk_callback(png_structp png_ptr, png_unknown_chunkp in_chunk)
{
if (0 == memcmp("iCCP", in_chunk->name, 5) ||
0 == memcmp("cHRM", in_chunk->name, 5) ||
0 == memcmp("gAMA", in_chunk->name, 5)) {
return 0; // not handled
}
struct rwpng_chunk **head = (struct rwpng_chunk **)png_get_user_chunk_ptr(png_ptr);
struct rwpng_chunk *chunk = malloc(sizeof(struct rwpng_chunk));
memcpy(chunk->name, in_chunk->name, 5);
chunk->size = in_chunk->size;
chunk->location = in_chunk->location;
chunk->data = in_chunk->size ? malloc(in_chunk->size) : NULL;
if (in_chunk->size) {
memcpy(chunk->data, in_chunk->data, in_chunk->size);
}
chunk->next = *head;
*head = chunk;
return 1; // marks as "handled", libpng won't store it
}
/*
retval:
0 = success
21 = bad sig
22 = bad IHDR
24 = insufficient memory
25 = libpng error (via longjmp())
26 = wrong PNG color type (no alpha channel)
*/
pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose)
{
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
png_size_t rowbytes;
int color_type, bit_depth;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler);
if (!png_ptr) {
return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */
}
/* setjmp() must be called in every function that calls a non-trivial
* libpng function */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */
}
#if PNG_LIBPNG_VER > 10400
/* copy standard chunks too */
png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)"pHYs\0iTXt\0tEXt\0zTXt", 4);
#endif
png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback);
struct rwpng_read_data read_data = {infile, 0};
png_set_read_fn(png_ptr, &read_data, user_read_data);
png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */
/* alternatively, could make separate calls to png_get_image_width(),
* etc., but want bit_depth and color_type for later [don't care about
* compression_type and filter_type => NULLs] */
png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height,
&bit_depth, &color_type, NULL, NULL, NULL);
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */
if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
#ifdef PNG_READ_FILLER_SUPPORTED
png_set_expand(png_ptr);
png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER);
#else
fprintf(stderr, "pngquant readpng: image is neither RGBA nor GA\n");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
mainprog_ptr->retval = 26;
return mainprog_ptr->retval;
#endif
}
if (bit_depth == 16) {
png_set_strip_16(png_ptr);
}
if (!(color_type & PNG_COLOR_MASK_COLOR)) {
png_set_gray_to_rgb(png_ptr);
}
/* get source gamma for gamma correction, or use sRGB default */
double gamma = 0.45455;
if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
png_get_gAMA(png_ptr, info_ptr, &gamma);
if (gamma < 0 && gamma > 1.0) {
fprintf(stderr, "pngquant readpng: ignored out-of-range gamma %f\n", gamma);
gamma = 0.45455;
}
}
mainprog_ptr->gamma = gamma;
png_set_interlace_handling(png_ptr);
/* all transformations have been registered; now update info_ptr data,
* get rowbytes and channels, and allocate image memory */
png_read_update_info(png_ptr, info_ptr);
rowbytes = png_get_rowbytes(png_ptr, info_ptr);
if ((mainprog_ptr->rgba_data = malloc(rowbytes*mainprog_ptr->height)) == NULL) {
fprintf(stderr, "pngquant readpng: unable to allocate image data\n");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return PNG_OUT_OF_MEMORY_ERROR;
}
png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);
/* now we can go ahead and just read the whole image */
png_read_image(png_ptr, row_pointers);
/* and we're done! (png_read_end() can be omitted if no processing of
* post-IDAT text/time/etc. is desired) */
png_read_end(png_ptr, NULL);
#if USE_LCMS
#if PNG_LIBPNG_VER < 10500
png_charp ProfileData;
#else
png_bytep ProfileData;
#endif
png_uint_32 ProfileLen;
cmsHPROFILE hInProfile = NULL;
/* color_type is read from the image before conversion to RGBA */
int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR;
mainprog_ptr->lcms_status = NONE;
/* embedded ICC profile */
if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) {
hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen);
cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile);
/* only RGB (and GRAY) valid for PNGs */
if (colorspace == cmsSigRgbData && COLOR_PNG) {
mainprog_ptr->lcms_status = ICCP;
} else {
if (colorspace == cmsSigGrayData && !COLOR_PNG) {
mainprog_ptr->lcms_status = ICCP_WARN_GRAY;
}
cmsCloseProfile(hInProfile);
hInProfile = NULL;
}
}
/* build RGB profile from cHRM and gAMA */
if (hInProfile == NULL && COLOR_PNG &&
!png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) &&
png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&
png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) {
cmsCIExyY WhitePoint;
cmsCIExyYTRIPLE Primaries;
png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y,
&Primaries.Red.x, &Primaries.Red.y,
&Primaries.Green.x, &Primaries.Green.y,
&Primaries.Blue.x, &Primaries.Blue.y);
WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0;
cmsToneCurve *GammaTable[3];
GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma);
hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable);
cmsFreeToneCurve(GammaTable[0]);
mainprog_ptr->lcms_status = GAMA_CHRM;
}
/* transform image to sRGB colorspace */
if (hInProfile != NULL) {
cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile();
cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8,
hOutProfile, TYPE_RGBA_8,
INTENT_PERCEPTUAL,
omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0);
#pragma omp parallel for \
if (mainprog_ptr->height*mainprog_ptr->width > 8000) \
schedule(static)
for (unsigned int i = 0; i < mainprog_ptr->height; i++) {
/* It is safe to use the same block for input and output,
when both are of the same TYPE. */
cmsDoTransform(hTransform, row_pointers[i],
row_pointers[i],
mainprog_ptr->width);
}
cmsDeleteTransform(hTransform);
cmsCloseProfile(hOutProfile);
cmsCloseProfile(hInProfile);
mainprog_ptr->gamma = 0.45455;
}
#endif
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
mainprog_ptr->file_size = read_data.bytes_read;
mainprog_ptr->row_pointers = (unsigned char **)row_pointers;
return SUCCESS;
}
static void rwpng_free_chunks(struct rwpng_chunk *chunk) {
if (!chunk) return;
rwpng_free_chunks(chunk->next);
free(chunk->data);
free(chunk);
}
void rwpng_free_image24(png24_image *image)
{
free(image->row_pointers);
image->row_pointers = NULL;
free(image->rgba_data);
image->rgba_data = NULL;
rwpng_free_chunks(image->chunks);
image->chunks = NULL;
}
void rwpng_free_image8(png8_image *image)
{
free(image->indexed_data);
image->indexed_data = NULL;
free(image->row_pointers);
image->row_pointers = NULL;
rwpng_free_chunks(image->chunks);
image->chunks = NULL;
}
pngquant_error rwpng_read_image24(FILE *infile, png24_image *input_image_p, int verbose)
{
#if USE_COCOA
return rwpng_read_image24_cocoa(infile, input_image_p);
#else
return rwpng_read_image24_libpng(infile, input_image_p, verbose);
#endif
}
static pngquant_error rwpng_write_image_init(rwpng_png_image *mainprog_ptr, png_structpp png_ptr_p, png_infopp info_ptr_p, int fast_compression)
{
/* could also replace libpng warning-handler (final NULL), but no need: */
*png_ptr_p = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, NULL);
if (!(*png_ptr_p)) {
return LIBPNG_INIT_ERROR; /* out of memory */
}
*info_ptr_p = png_create_info_struct(*png_ptr_p);
if (!(*info_ptr_p)) {
png_destroy_write_struct(png_ptr_p, NULL);
return LIBPNG_INIT_ERROR; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or exit immediately, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(png_ptr_p, info_ptr_p);
return LIBPNG_INIT_ERROR; /* libpng error (via longjmp()) */
}
png_set_compression_level(*png_ptr_p, fast_compression ? Z_BEST_SPEED : Z_BEST_COMPRESSION);
png_set_compression_mem_level(*png_ptr_p, fast_compression ? 9 : 5); // judging by optipng results, smaller mem makes libpng compress slightly better
return SUCCESS;
}
void rwpng_write_end(png_infopp info_ptr_p, png_structpp png_ptr_p, png_bytepp row_pointers)
{
png_write_info(*png_ptr_p, *info_ptr_p);
png_set_packing(*png_ptr_p);
png_write_image(*png_ptr_p, row_pointers);
png_write_end(*png_ptr_p, NULL);
png_destroy_write_struct(png_ptr_p, info_ptr_p);
}
void rwpng_set_gamma(png_infop info_ptr, png_structp png_ptr, double gamma)
{
/* remap sets gamma to 0.45455 */
png_set_gAMA(png_ptr, info_ptr, gamma);
png_set_sRGB(png_ptr, info_ptr, 0); // 0 = Perceptual
}
pngquant_error rwpng_write_image8(FILE *outfile, const png8_image *mainprog_ptr)
{
png_structp png_ptr;
png_infop info_ptr;
pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, mainprog_ptr->fast_compression);
if (retval) return retval;
struct rwpng_write_state write_state;
write_state = (struct rwpng_write_state){
.outfile = outfile,
.maximum_file_size = mainprog_ptr->maximum_file_size,
.retval = SUCCESS,
};
png_set_write_fn(png_ptr, &write_state, user_write_data, user_flush_data);
// Palette images generally don't gain anything from filtering
png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_VALUE_NONE);
rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma);
/* set the image parameters appropriately */
int sample_depth;
#if PNG_LIBPNG_VER > 10400 /* old libpng corrupts files with low depth */
if (mainprog_ptr->num_palette <= 2)
sample_depth = 1;
else if (mainprog_ptr->num_palette <= 4)
sample_depth = 2;
else if (mainprog_ptr->num_palette <= 16)
sample_depth = 4;
else
#endif
sample_depth = 8;
struct rwpng_chunk *chunk = mainprog_ptr->chunks;
int chunk_num=0;
while(chunk) {
png_unknown_chunk pngchunk = {
.size = chunk->size,
.data = chunk->data,
.location = chunk->location,
};
memcpy(pngchunk.name, chunk->name, 5);
png_set_unknown_chunks(png_ptr, info_ptr, &pngchunk, 1);
#if defined(PNG_HAVE_IHDR) && PNG_LIBPNG_VER < 10600
png_set_unknown_chunk_location(png_ptr, info_ptr, chunk_num, pngchunk.location ? pngchunk.location : PNG_HAVE_IHDR);
#endif
chunk = chunk->next;
chunk_num++;
}
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
sample_depth, PNG_COLOR_TYPE_PALETTE,
0, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_BASE);
png_set_PLTE(png_ptr, info_ptr, &mainprog_ptr->palette[0], mainprog_ptr->num_palette);
if (mainprog_ptr->num_trans > 0) {
png_set_tRNS(png_ptr, info_ptr, mainprog_ptr->trans, mainprog_ptr->num_trans, NULL);
}
rwpng_write_end(&info_ptr, &png_ptr, mainprog_ptr->row_pointers);
return write_state.retval;
}
pngquant_error rwpng_write_image24(FILE *outfile, const png24_image *mainprog_ptr)
{
png_structp png_ptr;
png_infop info_ptr;
pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, 0);
if (retval) return retval;
png_init_io(png_ptr, outfile);
rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma);
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
8, PNG_COLOR_TYPE_RGB_ALPHA,
0, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_BASE);
png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);
rwpng_write_end(&info_ptr, &png_ptr, row_pointers);
free(row_pointers);
return SUCCESS;
}
static void rwpng_warning_stderr_handler(png_structp png_ptr, png_const_charp msg) {
fprintf(stderr, " %s\n", msg);
}
static void rwpng_warning_silent_handler(png_structp png_ptr, png_const_charp msg) {
}
static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg)
{
rwpng_png_image *mainprog_ptr;
/* This function, aside from the extra step of retrieving the "error
* pointer" (below) and the fact that it exists within the application
* rather than within libpng, is essentially identical to libpng's
* default error handler. The second point is critical: since both
* setjmp() and longjmp() are called from the same code, they are
* guaranteed to have compatible notions of how big a jmp_buf is,
* regardless of whether _BSD_SOURCE or anything else has (or has not)
* been defined. */
fprintf(stderr, " error: %s\n", msg);
fflush(stderr);
mainprog_ptr = png_get_error_ptr(png_ptr);
if (mainprog_ptr == NULL) abort();
longjmp(mainprog_ptr->jmpbuf, 1);
}
|
gsrb.ompfor.c | //------------------------------------------------------------------------------------------------------------------------------
// Samuel Williams
// SWWilliams@lbl.gov
// Lawrence Berkeley National Lab
//------------------------------------------------------------------------------------------------------------------------------
#if defined(GSRB_FP)
#warning Overriding default GSRB implementation and using pre-computed 1.0/0.0 FP array for Red-Black to facilitate vectorization...
#elif defined(GSRB_STRIDE2)
#if defined(GSRB_OOP)
#warning Overriding default GSRB implementation and using out-of-place and stride-2 accesses to minimize the number of flops
#else
#warning Overriding default GSRB implementation and using stride-2 accesses to minimize the number of flops
#endif
#elif defined(GSRB_BRANCH)
#if defined(GSRB_OOP)
#warning Overriding default GSRB implementation and using out-of-place implementation with an if-then-else on loop indices...
#else
#warning Overriding default GSRB implementation and using if-then-else on loop indices...
#endif
#else
#define GSRB_STRIDE2 // default implementation
#endif
//------------------------------------------------------------------------------------------------------------------------------
void smooth(level_type * level, int x_id, int rhs_id, double a, double b){
int s;
for(s=0;s<2*NUM_SMOOTHS;s++){ // there are two sweeps per GSRB smooth
// exchange the ghost zone...
#ifdef GSRB_OOP // out-of-place GSRB ping pongs between x and VECTOR_TEMP
if((s&1)==0){exchange_boundary(level, x_id,stencil_get_shape());apply_BCs(level, x_id,stencil_get_shape());}
else{exchange_boundary(level,VECTOR_TEMP,stencil_get_shape());apply_BCs(level,VECTOR_TEMP,stencil_get_shape());}
#else // in-place GSRB only operates on x
exchange_boundary(level, x_id,stencil_get_shape());apply_BCs(level, x_id,stencil_get_shape());
#endif
// apply the smoother...
double _timeStart = getTime();
int box;
for(box=0;box<level->num_my_boxes;box++){ // loop over all boxes this process owns...
const double h2inv = 1.0/(level->h*level->h);
const int ghosts = level->box_ghosts;
const int jStride = level->box_jStride;
const int kStride = level->box_kStride;
const int color000 = (level->my_boxes[box].low.i^level->my_boxes[box].low.j^level->my_boxes[box].low.k^s)&1; // is element 000 red or black on *THIS* sweep
const double * __restrict__ rhs = level->my_boxes[box].vectors[ rhs_id] + ghosts*(1+jStride+kStride);
const double * __restrict__ alpha = level->my_boxes[box].vectors[VECTOR_ALPHA ] + ghosts*(1+jStride+kStride);
const double * __restrict__ beta_i = level->my_boxes[box].vectors[VECTOR_BETA_I] + ghosts*(1+jStride+kStride);
const double * __restrict__ beta_j = level->my_boxes[box].vectors[VECTOR_BETA_J] + ghosts*(1+jStride+kStride);
const double * __restrict__ beta_k = level->my_boxes[box].vectors[VECTOR_BETA_K] + ghosts*(1+jStride+kStride);
const double * __restrict__ Dinv = level->my_boxes[box].vectors[VECTOR_DINV ] + ghosts*(1+jStride+kStride);
#ifdef GSRB_OOP
const double * __restrict__ x_n;
double * __restrict__ x_np1;
if((s&1)==0){x_n = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride);
x_np1 = level->my_boxes[box].vectors[VECTOR_TEMP ] + ghosts*(1+jStride+kStride);}
else{x_n = level->my_boxes[box].vectors[VECTOR_TEMP ] + ghosts*(1+jStride+kStride);
x_np1 = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride);}
#else
const double * __restrict__ x_n = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point
double * __restrict__ x_np1 = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point
#endif
int i,j,k;
#pragma omp parallel for private(i,j,k) schedule(static,1) // chunksize=1 implies the collection of threads gets a slab (spatial locality in k exploited in LLC)
//#pragma omp parallel for private(i,j,k) // Default schedule chunksize implies each thread gets a slab and inter-thread locality may not be exploited
for(k=0;k<level->box_dim;k++){
for(j=0;j<level->box_dim;j++){
#if defined(GSRB_FP)
const double * __restrict__ RedBlack = level->RedBlack_FP + ghosts*(1+jStride) + kStride*((k^color000)&0x1);
for(i=0;i<level->box_dim;i++){
int ij = i + j*jStride;
int ijk = i + j*jStride + k*kStride;
double Ax = apply_op_ijk(x_n);
x_np1[ijk] = x_n[ijk] + RedBlack[ij]*Dinv[ijk]*(rhs[ijk]-Ax);
//x_np1[ijk] = ((i^j^k^color000)&1) ? x_n[ijk] : x_n[ijk] + Dinv[ijk]*(rhs[ijk]-Ax);
} // i
#elif defined(GSRB_STRIDE2)
#ifdef GSRB_OOP
// out-of-place must copy old value...
for(i=0;i<level->box_dim;i++){
int ijk = i + j*jStride + k*kStride;
x_np1[ijk] = x_n[ijk];
} // i copy
#endif
for(i=((j^k^color000)&1);i<level->box_dim;i+=2){ // stride-2 GSRB
int ijk = i + j*jStride + k*kStride;
double Ax = apply_op_ijk(x_n);
x_np1[ijk] = x_n[ijk] + Dinv[ijk]*(rhs[ijk]-Ax);
} // i stencil
#elif defined(GSRB_BRANCH)
for(i=0;i<level->box_dim;i++){
int ijk = i + j*jStride + k*kStride;
if((i^j^k^color000^1)&1){ // looks very clean when [0] is i,j,k=0,0,0
double Ax = apply_op_ijk(x_n);
x_np1[ijk] = x_n[ijk] + Dinv[ijk]*(rhs[ijk]-Ax);
#ifdef GSRB_OOP
}else{
x_np1[ijk] = x_n[ijk]; // copy old value when sweep color != cell color
#endif
}
} // i
#else
#error no GSRB implementation was specified
#endif
}} // j,k
} // boxes
level->timers.smooth += (double)(getTime()-_timeStart);
} // s-loop
}
//------------------------------------------------------------------------------------------------------------------------------
|
dd_temporal.h | #pragma once
#include "./dd_dag.h"
#include "./dd_graph.h"
#include <gmpxx.h>
#include <algorithm>
#include <cassert>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
typedef std::pair<double, double> DensityPrecision;
typedef std::pair<int, int> VertexPair;
typedef CompleteNeighborhoodStructure NeighborhoodStructure;
const int PERMUTATION_SIZE_LIMIT = 100, PERMUTATION_COUNT_LIMIT = 10;
enum SamplingMethod { WIUF, UNIFORM, MIN_DISCARD };
const std::map<SamplingMethod, std::string> SAMPLING_METHOD_NAME = {
{ SamplingMethod::WIUF, "high-prob-sampling" },
{ SamplingMethod::UNIFORM, "local-unif-sampling" },
{ SamplingMethod::MIN_DISCARD, "discard-minimum-sampling" },
};
const std::map<std::string, SamplingMethod> SAMPLING_METHOD_REVERSE_NAME = {
{ "high-prob-sampling", SamplingMethod::WIUF },
{ "local-unif-sampling", SamplingMethod::UNIFORM },
{ "discard-minimum-sampling", SamplingMethod::MIN_DISCARD },
};
inline bool validate_problem_size(const int &n, const int &n0) {
return exp(lgamma(n) - lgamma(n0)) <= 10e8;
}
std::vector<int> generate_permutation(const int &n, const int &n0) {
std::random_device device;
std::mt19937 generator(device());
std::vector<int> S(n);
for (int i = 0; i < n; i++) {
S[i] = i;
}
for (int i = n - 1; i > n0; i--) {
std::uniform_int_distribution<int> swap_distribution(n0, i);
int index = swap_distribution(generator);
std::swap(S[i], S[index]);
}
return S;
}
std::vector<int> decode_permutation(const mpz_class &sigma, const int &n) {
std::vector<int> S(n);
mpz_class value(sigma);
for (int i = 1; i <= n; i++) {
mpz_class base(i + 1), remainder = value % base;
value /= base;
S[n - i] = remainder.get_si();
}
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (S[i] <= S[j]) {
S[j]++;
}
}
}
return S;
}
mpz_class encode_permutation(const std::vector<int> &S) {
int n = S.size();
mpz_class sigma(0);
std::vector<int> V(S);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (V[i] < V[j]) {
V[j]--;
}
}
}
mpz_class base(1);
for (int i = 1; i <= n; i++) {
base *= mpz_class(i);
sigma += mpz_class(V[n - i]) * base;
}
return sigma;
}
void apply_permutation(Graph &G, const std::vector<int> &S) {
std::vector<Vertex> V(get_vertices(G));
for (auto &v : V) {
set_index(G, v, S[get_index(G, v)]);
}
}
std::vector<int> reverse_permutation(const std::vector<int> &S) {
std::vector<int> V(S.size());
for (size_t i = 0; i < S.size(); i++) {
V[S[i]] = i;
}
return V;
}
void normalize_log_probabilities(std::map<mpz_class, long double> &permutations) {
long double max_log_value = -std::numeric_limits<long double>::infinity();
for (const auto &permutation : permutations) {
max_log_value = std::max(max_log_value, permutation.second);
}
long double total_probability = 0.0L;
for (auto &permutation : permutations) {
permutation.second = exp2l(permutation.second - max_log_value);
total_probability += permutation.second;
}
for (auto &permutation : permutations) {
permutation.second /= total_probability;
}
}
std::map<mpz_class, long double> get_log_permutation_probabilities(
Graph &G, const int &n0, const Parameters ¶ms,
NeighborhoodStructure &aux, std::vector<int> &S, const long double &p_sigma) {
std::map<mpz_class, long double> permutations;
if (get_graph_size(G) == n0) {
mpz_class sigma = encode_permutation(S);
permutations.insert(std::make_pair(sigma, p_sigma));
return permutations;
}
std::vector<Vertex> V(get_vertices(G));
Graph H;
for (auto &v : V) {
if (get_index(G, v) < n0) {
continue;
}
long double p_v = get_log_transition_probability(G, params, v, aux);
if (std::isfinite(p_v)) {
std::set<Vertex> neighbors_v(get_neighbors(G, v));
aux.remove_vertex(neighbors_v), S[get_graph_size(G) - 1] = get_index(G, v);
move_vertex(H, G, v);
assert(aux.verify(G));
auto permutations_v =
get_log_permutation_probabilities(G, n0, params, aux, S, p_sigma + p_v);
permutations.insert(permutations_v.begin(), permutations_v.end());
move_vertex(G, H, v), aux.restore_vertex(neighbors_v), S[get_graph_size(G) - 1] = -1;
for (auto &u : neighbors_v) {
add_edge(G, v, u);
}
assert(aux.verify(G));
}
}
return permutations;
}
std::map<mpz_class, long double> get_log_permutation_probabilities(
const Graph &G, const int &n0, const Parameters ¶ms) {
Graph H(G);
NeighborhoodStructure aux(H);
std::vector<int> S(get_graph_size(H), -1);
for (int i = 0; i < n0; i++) {
S[i] = i;
}
return get_log_permutation_probabilities(H, n0, params, aux, S, 0.0L);
}
long double get_log_permutation_probability(
const Graph &G, const int &n0, const Parameters ¶ms, const std::vector<int> &rev_S) {
Graph H(G);
CompleteNeighborhoodStructure aux(H);
long double p_sigma = 0.0L;
std::map<int, Vertex> V;
for (const auto &v : get_vertices(H)) {
V.insert(std::make_pair(rev_S[get_index(H, v)], v));
}
for (int i = V.size() - 1; i >= n0; i--) {
long double p_v = get_log_transition_probability(H, params, V[i], aux);
aux.remove_vertex(get_neighbors(H, V[i])), delete_vertex(H, V[i]);
assert(aux.verify(H));
p_sigma += p_v;
}
return p_sigma;
}
std::tuple<Vertex, double> sample_vertex(
const Graph &G, const int &n0, const Parameters ¶ms, const DAG &perfect_pairs,
const NeighborhoodStructure &aux, const SamplingMethod &algorithm, std::mt19937 &generator) {
std::vector<Vertex> V;
std::vector<long double> omega;
for (const auto &v : get_vertices(G)) {
if (get_index(G, v) < n0) {
continue;
}
if (!perfect_pairs.is_source(get_index(G, v))) {
continue;
}
V.push_back(v);
}
switch (algorithm) {
case WIUF: {
for (const auto &v : V) {
omega.push_back(exp2l(get_log_transition_probability(G, params, v, aux)));
}
long double omega_sum = accumulate(omega.begin(), omega.end(), 0.0L);
std::discrete_distribution<int> choose_vertex(omega.begin(), omega.end());
int index = choose_vertex(generator);
return std::make_tuple(V[index], log2l(omega_sum));
}
case UNIFORM: {
std::vector<int> C(V.size());
std::transform(
V.begin(), V.end(), C.begin(),
[&](const Vertex &v) -> int { return is_feasible(G, params, v, aux); });
int C_sum = accumulate(C.begin(), C.end(), 0);
std::discrete_distribution<int> choose_vertex(C.begin(), C.end());
int index = choose_vertex(generator);
return std::make_tuple(
V[index], log2l(C_sum) + get_log_transition_probability(G, params, V[index], aux));
}
case MIN_DISCARD: {
std::vector<long double> C(V.size());
std::transform(
V.begin(), V.end(), C.begin(),
[&](const Vertex &v) -> long double { return get_discard_score(G, params, v, aux); });
long double C_sum = accumulate(C.begin(), C.end(), 0.0L);
std::discrete_distribution<int> choose_vertex(C.begin(), C.end());
int index = choose_vertex(generator);
return std::make_tuple(
V[index], log2l(C_sum) + get_log_transition_probability(G, params, V[index], aux));
}
default:
throw std::invalid_argument(
"Invalid algorithm: " + SAMPLING_METHOD_NAME.find(algorithm)->second);
}
}
std::pair<mpz_class, long double> get_log_permutation_sample(
const Graph &G, const int &n0, const Parameters ¶ms, const DAG &perfect_pairs_G,
const NeighborhoodStructure &aux_G, const SamplingMethod &algorithm) {
std::random_device device;
std::mt19937 generator(device());
Graph H(G);
NeighborhoodStructure aux(aux_G);
DAG perfect_pairs(perfect_pairs_G);
std::vector<int> S(get_graph_size(H), -1);
for (int i = 0; i < n0; i++) {
S[i] = i;
}
long double p_sigma = 0.0L, pv;
while (get_graph_size(H) > n0) {
Vertex v;
std::tie(v, pv) =
sample_vertex(H, n0, params, perfect_pairs, aux, algorithm, generator);
S[get_graph_size(H) - 1] = get_index(H, v), p_sigma += pv;
assert(aux.verify(H));
perfect_pairs.remove_vertex(get_index(H, v));
aux.remove_vertex(get_neighbors(H, v)), delete_vertex(H, v);
assert(aux.verify(H));
}
return std::make_pair(encode_permutation(S), p_sigma);
}
std::map<mpz_class, long double> get_log_permutation_probabilities_sampling(
const Graph &G, const int &n0, const Parameters ¶ms, const DAG &perfect_pairs,
const SamplingMethod &algorithm, const int &tries) {
std::map<mpz_class, long double> permutations;
NeighborhoodStructure aux(G);
#pragma omp parallel for shared(permutations)
for (int i = 0; i < tries; i++) {
auto sigma_with_probability =
get_log_permutation_sample(G, n0, params, perfect_pairs, aux, algorithm);
auto permutation = permutations.find(sigma_with_probability.first);
if (permutation != permutations.end()) {
permutation->second = add_exp_log(permutation->second, sigma_with_probability.second);
} else {
permutations.insert(sigma_with_probability);
}
#pragma omp critical
{
if ((i + 1) % 10000 == 0) {
std::cerr << "Finished tries " << i + 1 << "/" << tries << std::endl;
}
}
}
return permutations;
}
std::map<VertexPair, long double> get_p_uv_from_permutations(
const std::map<mpz_class, long double> &permutations, const int &n, const int &n0) {
std::map<VertexPair, long double> p_uv;
const long double P_SIGMA_THRESHOLD = 10e-20L;
for (const auto &permutation : permutations) {
if (permutation.second < P_SIGMA_THRESHOLD) {
continue;
}
const auto &S = decode_permutation(permutation.first, n);
for (int j = n0; j < n; j++) {
for (int k = j + 1; k < n; k++) {
p_uv[std::make_pair(S[j], S[k])] += permutation.second;
}
}
}
return p_uv;
}
void print_best_permutations(
const std::map<mpz_class, long double> &permutations, const Graph &G,
const Parameters ¶ms, const int &n0, const std::string &algorithm_name, const int &limit) {
std::priority_queue<std::pair<long double, mpz_class>> Q;
int n = get_graph_size(G);
for (auto &permutation : permutations) {
Q.push(std::make_pair(permutation.second, permutation.first));
}
std::cout << "Best " << std::min(limit, static_cast<int>(Q.size())) << "/" << permutations.size()
<< " permutations for " << algorithm_name << " method:" << std::endl;
for (int i = 0; i < limit && !Q.empty(); i++) {
const auto &permutation = Q.top();
const auto V(decode_permutation(permutation.second, n));
if (n <= PERMUTATION_SIZE_LIMIT) {
for (const auto &v : V) {
std::cout << v << " ";
}
} else {
std::cout << "Permutation " << i << " ";
}
std::cout << std::setw(20) << std::setprecision(9) << permutation.first << " "
<< std::setw(20) << std::setprecision(9)
<< get_log_permutation_probability(G, n0, params, reverse_permutation(V)) << std::endl;
Q.pop();
}
}
|
generate_local_ranks_parallel.c | #include <omp.h>
#include "utils.h"
#include "algorithm.h"
/**
This sorts regions of SA with the same current_rank by their next_rank-
the value a distance 2^h away. It outputs runs of (curr, next, count)
**/
//create RunRecord triplet and sort
void sort_and_output_group(int * sa_buffer, long * next_ranks_buffer, long current_rank,
int start_interval, int end_interval, FILE *runsFP){
int i;
tsort(&sa_buffer[start_interval], next_ranks_buffer, end_interval-start_interval);
RunRecord output;
output.currentRank = current_rank;
output.count = 1;
output.nextRank = next_ranks_buffer[sa_buffer[start_interval]];
//find runs and write them to output
for (i = start_interval+1; i < end_interval; i++) {
if (next_ranks_buffer[sa_buffer[i]] != output.nextRank) {
Fwrite (&output, sizeof(RunRecord), 1, runsFP);
output.count = 1;
output.nextRank = next_ranks_buffer[sa_buffer[i]];
}
else {
output.count++;
}
}
Fwrite (&output, sizeof(RunRecord), 1, runsFP);
}
int generate_local_runs_parallel (char * rank_dir, char * runs_dir, int total_chunks,
int chunk_id, int h) {
//Determine which additional chunk must be loaded
int size_order = 0;
while((WORKING_CHUNK_SIZE >> size_order) > 1) {size_order++;}
int next_chunk_dist = h > size_order ? 1<<(h-size_order) : 0;
//printf("%d,%d\n",size_order,next_chunk_dist);
if ((next_chunk_dist + chunk_id) > total_chunks-1){
// #pragma omp barrier
// #pragma omp barrier
return EMPTY;
}
char runs_file_name [MAX_PATH_LENGTH];
FILE *runsFP = NULL;
sprintf (runs_file_name, "%s/runs_%d", runs_dir, chunk_id);
OpenBinaryFileAppend(&runsFP, runs_file_name);
int i, r, total_records = 0;
FILE *currentFP = NULL;
FILE *nextFP = NULL;
FILE *saFP = NULL;
// FILE *summaryFP = NULL;
// char summary_file_name [MAX_PATH_LENGTH];
char current_ranks_file_name [MAX_PATH_LENGTH];
char next_ranks_file_name [MAX_PATH_LENGTH];
char sa_file_name [MAX_PATH_LENGTH];
//allocate buffers
long *current_ranks_buffer = (long *) Calloc ((WORKING_CHUNK_SIZE) *sizeof (long));
long *next_ranks_buffer = (long *) Calloc ((WORKING_CHUNK_SIZE) *sizeof (long));
int *sa_buffer = (int *) Calloc ((WORKING_CHUNK_SIZE) *sizeof (int));
// sprintf (summary_file_name, "%s/merge_summary", runs_dir);
sprintf (current_ranks_file_name, "%s/ranks_%d", rank_dir, chunk_id);
sprintf (sa_file_name, "%s/sa_%d", rank_dir, chunk_id);
//open current rank and sa file
OpenBinaryFileRead (¤tFP, current_ranks_file_name);
OpenBinaryFileReadWrite (&saFP, sa_file_name);
// OpenBinaryFileWrite (&summaryFP, summary_file_name);
//handle reading next_rank
if (next_chunk_dist) {
sprintf (next_ranks_file_name, "%s/ranks_%d", rank_dir, chunk_id+next_chunk_dist);
OpenBinaryFileRead (&nextFP, next_ranks_file_name);
fread (next_ranks_buffer, sizeof (long), WORKING_CHUNK_SIZE, nextFP);
} else{
sprintf (next_ranks_file_name, "%s/ranks_%d", rank_dir, chunk_id);
OpenBinaryFileRead (&nextFP, next_ranks_file_name);
if(fseek(nextFP, (1 << h)*sizeof(long), SEEK_SET)) {
printf ("Fseek failed trying to move to position %d in ranks file\n", (1 << h));
exit (1);
}
r = fread (next_ranks_buffer, sizeof (long), WORKING_CHUNK_SIZE, nextFP);
fclose(nextFP);
if (chunk_id+1 < total_chunks) {
sprintf (next_ranks_file_name, "%s/ranks_%d", rank_dir, chunk_id+1);
OpenBinaryFileRead (&nextFP, next_ranks_file_name);
fread (next_ranks_buffer + r, sizeof (long), (1<<h), nextFP);
fclose (nextFP);
}
}
//offset next rank by 2^h
//read file by chunk, sort and generate triplet for each chunk
total_records=fread (current_ranks_buffer, sizeof (long), WORKING_CHUNK_SIZE, currentFP);
fclose (currentFP);
// fread (next_ranks_buffer, sizeof (long), WORKING_CHUNK_SIZE, nextFP);
r = fread (sa_buffer, sizeof (int), WORKING_CHUNK_SIZE, saFP);
if (r != total_records) {
printf("Unexpected error: SA has different size %d than ranks array %d\n", r, total_records);
return FAILURE;
}
// printf("Thread %d got here", omp_get_thread_num());
// #pragma omp barrier
int finished = 1;
int start_interval = 0;
int end_interval;
long previous_rank = current_ranks_buffer[sa_buffer[0]];
long current_rank;
//Read through current_ranks_buffer until it changes. Then sort based on next_rank.
for (i=1; i < total_records; i++) {
current_rank = current_ranks_buffer[sa_buffer[i]];
if (current_rank != previous_rank) {
if (previous_rank > 0) {
finished = 0;
end_interval = i;
//sort, generate runs
sort_and_output_group(sa_buffer, next_ranks_buffer, previous_rank,
start_interval, end_interval, runsFP);
}
start_interval = i;
previous_rank = current_rank;
}
}
if (previous_rank > 0) {
finished = 0;
end_interval = total_records;
sort_and_output_group(sa_buffer, next_ranks_buffer, previous_rank,
start_interval, end_interval, runsFP);
}
fclose(runsFP);
runsFP = NULL;
// if (chunk_empty == 0) {
// finished = 0;
// Fwrite (&pos_infile, sizeof(int), 1, summaryFP);
// }
//return pointer to the beginning of the sa chunk
// #pragma omp barrier
fseek ( saFP, -(total_records )*sizeof(int), SEEK_CUR );
Fwrite (sa_buffer, sizeof(int), total_records, saFP);
// pos_infile += total_records;
fclose(saFP);
// fclose (summaryFP);
free (sa_buffer);
free (current_ranks_buffer);
free (next_ranks_buffer);
if (finished)
return EMPTY;
return SUCCESS;
}
int main(int argc, char ** argv){
char * rank_dir;
char * runs_dir;
int h, chunk_id, total_chunks;
if (argc<5) {
puts ("Run ./generate_local_runs <rank_dir> <runs_dir> <total_chunks> <order>");
return FAILURE;
}
//Read inputs
rank_dir = argv[1];
runs_dir = argv[2];
total_chunks = atoi(argv[3]);
h = atoi(argv[4]);
int more_runs = EMPTY;
#pragma omp parallel for schedule(static, 1) num_threads(NUM_THREADS) private(chunk_id)
for (chunk_id = 0; chunk_id < total_chunks; chunk_id++){
int result = generate_local_runs_parallel (rank_dir, runs_dir, total_chunks, chunk_id, h);
if (result == FAILURE){
more_runs = FAILURE;
}
if (result != EMPTY && more_runs != FAILURE){
more_runs = SUCCESS;
}
}
return more_runs;
}
|
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] = 256;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<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-63,64)),ceild(24*t2-Nz-252,256)),ceild(24*t3-Ny-252,256));t4<=min(min(min(min(floord(Nt+Nx-4,256),floord(12*t1+Nx+21,256)),floord(24*t2+Nx+20,256)),floord(24*t3+Nx+20,256)),floord(24*t1-24*t2+Nz+Nx+19,256));t4++) {
for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),24*t3-Ny+2),256*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),24*t3+22),256*t4+254),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(256*t4,t5+1);
ubv=min(256*t4+255,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;
}
|
tinyexr.h | /*
Copyright (c) 2014 - 2015, Syoyo Fujita
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __TINYEXR_H__
#define __TINYEXR_H__
//
//
// Do this:
// #define TINYEXR_IMPLEMENTATION
// before you include this file in *one* C or C++ file to create the
// implementation.
//
// // i.e. it should look like this:
// #include ...
// #include ...
// #include ...
// #define TINYEXR_IMPLEMENTATION
// #include "tinyexr.h"
//
//
#include <stddef.h> // for size_t
#ifdef __cplusplus
extern "C" {
#endif
// pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
#define TINYEXR_PIXELTYPE_UINT (0)
#define TINYEXR_PIXELTYPE_HALF (1)
#define TINYEXR_PIXELTYPE_FLOAT (2)
#define TINYEXR_MAX_ATTRIBUTES (128)
#define TINYEXR_COMPRESSIONTYPE_NONE (0)
//#define TINYEXR_COMPRESSIONTYPE_RLE (1) // not supported yet
#define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
#define TINYEXR_COMPRESSIONTYPE_ZIP (3)
#define TINYEXR_COMPRESSIONTYPE_PIZ (4)
typedef struct _EXRAttribute {
char *name;
char *type;
int size;
unsigned char *value; // uint8_t*
} EXRAttribute;
typedef struct _EXRImage {
// Custom attributes(exludes required attributes(e.g. `channels`,
// `compression`, etc)
EXRAttribute custom_attributes[TINYEXR_MAX_ATTRIBUTES];
int num_custom_attributes;
int num_channels;
const char **channel_names;
unsigned char **images; // image[channels][pixels]
int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
// each channel
int *requested_pixel_types; // Filled initially by
// ParseEXRHeaderFrom(Meomory|File), then users
// can edit it(only valid for HALF pixel type
// channel)
int width;
int height;
float pixel_aspect_ratio;
int compression; // compression type(TINYEXR_COMPRESSIONTYPE_*)
int line_order;
int data_window[4];
int display_window[4];
float screen_window_center[2];
float screen_window_width;
} EXRImage;
typedef struct _DeepImage {
int num_channels;
const char **channel_names;
float ***image; // image[channels][scanlines][samples]
int **offset_table; // offset_table[scanline][offsets]
int width;
int height;
} DeepImage;
// @deprecated { to be removed. }
// Loads single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
// Application must free image data as returned by `out_rgba`
// Result image format is: float x RGBA x width x hight
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadEXR(float **out_rgba, int *width, int *height,
const char *filename, const char **err);
// Parse single-frame OpenEXR header from a file and initialize `EXRImage`
// struct.
// Users then call LoadMultiChannelEXRFromFile to actually load image data into
// `EXRImage`
extern int ParseMultiChannelEXRHeaderFromFile(EXRImage *image,
const char *filename,
const char **err);
// Parse single-frame OpenEXR header from a memory and initialize `EXRImage`
// struct.
// Users then call LoadMultiChannelEXRFromMemory to actually load image data
// into `EXRImage`
extern int ParseMultiChannelEXRHeaderFromMemory(EXRImage *image,
const unsigned char *memory,
const char **err);
// Loads multi-channel, single-frame OpenEXR image from a file.
// Application must setup `ParseMultiChannelEXRHeaderFromFile` before calling
// `LoadMultiChannelEXRFromFile`.
// Application can free EXRImage using `FreeExrImage`
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadMultiChannelEXRFromFile(EXRImage *image, const char *filename,
const char **err);
// Loads multi-channel, single-frame OpenEXR image from a memory.
// Application must setup `EXRImage` with `ParseMultiChannelEXRHeaderFromMemory`
// before calling `LoadMultiChannelEXRFromMemory`.
// Application can free EXRImage using `FreeExrImage`
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadMultiChannelEXRFromMemory(EXRImage *image,
const unsigned char *memory,
const char **err);
// Saves floating point RGBA image as OpenEXR.
// Image is compressed using EXRImage.compression value.
// Return 0 if success
// Returns error string in `err` when there's an error
// extern int SaveEXR(const float *in_rgba, int width, int height,
// const char *filename, const char **err);
// Saves multi-channel, single-frame OpenEXR image to a file.
// `compression_type` is one of TINYEXR_COMPRESSIONTYPE_*.
// Returns 0 if success
// Returns error string in `err` when there's an error
extern int SaveMultiChannelEXRToFile(const EXRImage *image,
const char *filename, const char **err);
// Saves multi-channel, single-frame OpenEXR image to a memory.
// Image is compressed using EXRImage.compression value.
// Return the number of bytes if succes.
// Retruns 0 if success, negative number when failed.
// Returns error string in `err` when there's an error
extern size_t SaveMultiChannelEXRToMemory(const EXRImage *image,
unsigned char **memory,
const char **err);
// Loads single-frame OpenEXR deep image.
// Application must free memory of variables in DeepImage(image, offset_table)
// Returns 0 if success
// Returns error string in `err` when there's an error
extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
const char **err);
// NOT YET IMPLEMENTED:
// Saves single-frame OpenEXR deep image.
// Return 0 if success
// Returns error string in `err` when there's an error
// extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
// const char **err);
// NOT YET IMPLEMENTED:
// Loads multi-part OpenEXR deep image.
// Application must free memory of variables in DeepImage(image, offset_table)
// extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
// char *filename,
// const char **err);
// Initialize of EXRImage struct
extern void InitEXRImage(EXRImage *exrImage);
// Free's internal data of EXRImage struct
// Returns 0 if success.
extern int FreeEXRImage(EXRImage *exrImage);
// For emscripten.
// Parse single-frame OpenEXR header from memory.
// Return 0 if success
extern int ParseEXRHeaderFromMemory(EXRAttribute *customAttributes,
int *numCustomAttributes, int *width,
int *height, const unsigned char *memory);
// For emscripten.
// Loads single-frame OpenEXR image from memory. Assume EXR image contains
// RGB(A) channels.
// `out_rgba` must have enough memory(at least sizeof(float) x 4(RGBA) x width x
// hight)
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadEXRFromMemory(float *out_rgba, const unsigned char *memory,
const char **err);
#ifdef __cplusplus
}
#endif
#ifdef TINYEXR_IMPLEMENTATION
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include "tinyexr.h"
#ifdef _OPENMP
#include <omp.h>
#endif
namespace {
namespace miniz {
/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
reading/writing/appending, PNG writing
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
http://www.ietf.org/rfc/rfc1951.txt
Most API's defined in miniz.c are optional. For example, to disable the
archive related functions just define
MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
(see the list below for more macros).
* Change History
10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
release with Zip64 support (almost there!):
- Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
(thanks kahmyong.moon@hp.com) which could cause locate files to not find
files. This bug
would only have occured in earlier versions if you explicitly used this
flag, OR if you used mz_zip_extract_archive_file_to_heap() or
mz_zip_add_mem_to_archive_file_in_place()
(which used this flag). If you can't switch to v1.15 but want to fix
this bug, just remove the uses of this flag from both helper funcs (and of
course don't use the flag).
- Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
pUser_read_buf is not NULL and compressed size is > uncompressed size
- Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
compressed data from directory entries, to account for weird zipfiles which
contain zero-size compressed data on dir entries.
Hopefully this fix won't cause any issues on weird zip archives,
because it assumes the low 16-bits of zip external attributes are DOS
attributes (which I believe they always are in practice).
- Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
internal attributes, just the filename and external attributes
- mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
- Added cmake support for Linux builds which builds all the examples,
tested with clang v3.3 and gcc v4.6.
- Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
- Merged MZ_FORCEINLINE fix from hdeanclark
- Fix <time.h> include before config #ifdef, thanks emil.brink
- Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
(super useful for OpenGL apps), and explicit control over the compression
level (so you can
set it to 1 for real-time compression).
- Merged in some compiler fixes from paulharris's github repro.
- Retested this build under Windows (VS 2010, including static analysis),
tcc 0.9.26, gcc v4.6 and clang v3.3.
- Added example6.c, which dumps an image of the mandelbrot set to a PNG
file.
- Modified example2 to help test the
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
- In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
possible src file fclose() leak if alignment bytes+local header file write
faiiled
- In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
Was pushing the wrong central dir header offset, appears harmless in this
release, but it became a problem in the zip64 branch
5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
#include <time.h> (thanks fermtect).
5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix
mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
- Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
re-ran a randomized regression test on ~500k files.
- Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
- Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
(static analysis) option and fixed all warnings (except for the silly
"Use of the comma-operator in a tested expression.." analysis warning,
which I purposely use to work around a MSVC compiler warning).
- Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
tested Linux executables. The codeblocks workspace is compatible with
Linux+Win32/x64.
- Added miniz_tester solution/project, which is a useful little app
derived from LZHAM's tester app that I use as part of the regression test.
- Ran miniz.c and tinfl.c through another series of regression testing on
~500,000 files and archives.
- Modified example5.c so it purposely disables a bunch of high-level
functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
MINIZ_NO_STDIO bug report.)
- Fix ftell() usage in examples so they exit with an error on files which
are too large (a limitation of the examples, not miniz itself).
4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
minor level_and_flags issues in the archive API's.
level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
Dawson <bruced@valvesoftware.com> for the feedback/bug report.
5/28/11 v1.11 - Added statement from unlicense.org
5/27/11 v1.10 - Substantial compressor optimizations:
- Level 1 is now ~4x faster than before. The L1 compressor's throughput
now varies between 70-110MB/sec. on a
- Core i7 (actual throughput varies depending on the type of data, and x64
vs. x86).
- Improved baseline L2-L9 compression perf. Also, greatly improved
compression perf. issues on some file types.
- Refactored the compression code for better readability and
maintainability.
- Added level 10 compression level (L10 has slightly better ratio than
level 9, but could have a potentially large
drop in throughput on some files).
5/15/11 v1.09 - Initial stable release.
* Low-level Deflate/Inflate implementation notes:
Compression: Use the "tdefl" API's. The compressor supports raw, static,
and dynamic blocks, lazy or
greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
It performs and compresses
approximately as well as zlib.
Decompression: Use the "tinfl" API's. The entire decompressor is
implemented as a single function
coroutine: see tinfl_decompress(). It supports decompression into a 32KB
(or larger power of 2) wrapping buffer, or into a memory
block large enough to hold the entire file.
The low-level tdefl/tinfl API's do not make any use of dynamic memory
allocation.
* zlib-style API notes:
miniz.c implements a fairly large subset of zlib. There's enough
functionality present for it to be a drop-in
zlib replacement in many apps:
The z_stream struct, optional memory allocation callbacks
deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
inflateInit/inflateInit2/inflate/inflateEnd
compress, compress2, compressBound, uncompress
CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
routines.
Supports raw deflate streams or standard zlib streams with adler-32
checking.
Limitations:
The callback API's are not implemented yet. No support for gzip headers or
zlib static dictionaries.
I've tried to closely emulate zlib's various flavors of stream flushing
and return status codes, but
there are no guarantees that miniz.c pulls this off perfectly.
* PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
originally written by
Alex Evans. Supports 1-4 bytes/pixel images.
* ZIP archive API notes:
The ZIP archive API's where designed with simplicity and efficiency in
mind, with just enough abstraction to
get the job done with minimal fuss. There are simple API's to retrieve file
information, read files from
existing archives, create new archives, append new files to existing
archives, or clone archive data from
one archive to another. It supports archives located in memory or the heap,
on disk (using stdio.h),
or you can specify custom file read/write callbacks.
- Archive reading: Just call this function to read a single file from a
disk archive:
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
For more complex cases, use the "mz_zip_reader" functions. Upon opening an
archive, the entire central
directory is located and read as-is into memory, and subsequent file access
only occurs when reading individual files.
- Archives file scanning: The simple way is to use this function to scan a
loaded archive for a specific file:
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
The locate operation can optionally check file comments too, which (as one
example) can be used to identify
multiple versions of the same file in an archive. This function uses a
simple linear search through the central
directory, so it's not very fast.
Alternately, you can iterate through all the files in an archive (using
mz_zip_reader_get_num_files()) and
retrieve detailed info on each file by calling mz_zip_reader_file_stat().
- Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
immediately writes compressed file data
to disk and builds an exact image of the central directory in memory. The
central directory image is written
all at once at the end of the archive file when the archive is finalized.
The archive writer can optionally align each file's local header and file
data to any power of 2 alignment,
which can be useful when the archive will be read from optical media. Also,
the writer supports placing
arbitrary data blobs at the very beginning of ZIP archives. Archives
written using either feature are still
readable by any ZIP tool.
- Archive appending: The simple way to add a single file to an archive is
to call this function:
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
const char *pArchive_name,
const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
comment_size, mz_uint level_and_flags);
The archive will be created if it doesn't already exist, otherwise it'll be
appended to.
Note the appending is done in-place and is not an atomic operation, so if
something goes wrong
during the operation it's possible the archive could be left without a
central directory (although the local
file headers and file data will be fine, so the archive will be
recoverable).
For more complex archive modification scenarios:
1. The safest way is to use a mz_zip_reader to read the existing archive,
cloning only those bits you want to
preserve into a new archive using using the
mz_zip_writer_add_from_zip_reader() function (which compiles the
compressed file data as-is). When you're done, delete the old archive and
rename the newly written archive, and
you're done. This is safe but requires a bunch of temporary disk space or
heap memory.
2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
mz_zip_writer_init_from_reader(),
append new files as needed, then finalize the archive which will write an
updated central directory to the
original archive. (This is basically what
mz_zip_add_mem_to_archive_file_in_place() does.) There's a
possibility that the archive's central directory could be lost with this
method if anything goes wrong, though.
- ZIP archive support limitations:
No zip64 or spanning support. Extraction functions can only handle
unencrypted, stored or deflated files.
Requires streams capable of seeking.
* This is a header file library, like stb_image.c. To get only a header file,
either cut and paste the
below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
include miniz.c from it.
* Important: For best perf. be sure to customize the below macros for your
target platform:
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_LITTLE_ENDIAN 1
#define MINIZ_HAS_64BIT_REGISTERS 1
* On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
including miniz.c to ensure miniz
uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
able to process large files
(i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
*/
#ifndef MINIZ_HEADER_INCLUDED
#define MINIZ_HEADER_INCLUDED
#include <stdlib.h>
// Defines to completely disable specific portions of miniz.c:
// If all macros here are defined the only functionality remaining will be
// CRC-32, adler-32, tinfl, and tdefl.
// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
// stdio for file I/O.
//#define MINIZ_NO_STDIO
// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
// to get the current time, or
// get/set file times, and the C run-time funcs that get/set times won't be
// called.
// The current downside is the times written to your archives will be from 1979.
//#define MINIZ_NO_TIME
// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
//#define MINIZ_NO_ARCHIVE_APIS
// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
// API's.
//#define MINIZ_NO_ARCHIVE_WRITING_APIS
// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
// API's.
//#define MINIZ_NO_ZLIB_APIS
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
// conflicts against stock zlib.
//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
// user alloc/free/realloc
// callbacks to the zlib and archive API's, and a few stand-alone helper API's
// which don't provide custom user
// functions (such as tdefl_compress_mem_to_heap() and
// tinfl_decompress_mem_to_heap()) won't work.
//#define MINIZ_NO_MALLOC
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
// on Linux
#define MINIZ_NO_TIME
#endif
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__i386) || defined(__i486__) || defined(__i486) || \
defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if defined(__sparcv9)
// Big endian
#else
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#endif
#if MINIZ_X86_OR_X64_CPU
// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
// integer loads and stores from unaligned addresses.
//#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
0 // disable to suppress compiler warnings
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
defined(__x86_64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
// reasonably fast (and don't involve compiler generated calls to helper
// functions).
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API Definitions.
// For more compatibility with zlib, miniz.c uses unsigned long for some
// parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
typedef unsigned long mz_ulong;
// mz_free() internally uses the MZ_FREE() macro (which by default calls free()
// unless you've modified the MZ_MALLOC macro) to release a block allocated from
// the heap.
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
// mz_adler32() returns the initial adler-32 value to use when called with
// ptr==NULL.
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
// mz_crc32() returns the initial CRC-32 value to use when called with
// ptr==NULL.
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
// Compression strategies.
enum {
MZ_DEFAULT_STRATEGY = 0,
MZ_FILTERED = 1,
MZ_HUFFMAN_ONLY = 2,
MZ_RLE = 3,
MZ_FIXED = 4
};
// Method
#define MZ_DEFLATED 8
#ifndef MINIZ_NO_ZLIB_APIS
// Heap allocation callbacks.
// Note that mz_alloc_func parameter types purpsosely differ from zlib's:
// items/size is size_t, not unsigned long.
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
size_t size);
#define MZ_VERSION "9.1.15"
#define MZ_VERNUM 0x91F0
#define MZ_VER_MAJOR 9
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 15
#define MZ_VER_SUBREVISION 0
// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
// other values are for advanced use (refer to the zlib docs).
enum {
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
// Return status codes. MZ_PARAM_ERROR is non-standard.
enum {
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
// Compression levels: 0-9 are the standard zlib-style levels, 10 is best
// possible compression (not zlib compatible, and may be very slow),
// MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
enum {
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
// Window bits
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
// Compression/decompression stream struct.
typedef struct mz_stream_s {
const unsigned char *next_in; // pointer to next byte to read
unsigned int avail_in; // number of bytes available at next_in
mz_ulong total_in; // total number of bytes consumed so far
unsigned char *next_out; // pointer to next byte to write
unsigned int avail_out; // number of bytes that can be written to next_out
mz_ulong total_out; // total number of bytes produced so far
char *msg; // error msg (unused)
struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
mz_alloc_func
zalloc; // optional heap allocation function (defaults to malloc)
mz_free_func zfree; // optional heap free function (defaults to free)
void *opaque; // heap alloc function user pointer
int data_type; // data_type (unused)
mz_ulong adler; // adler32 of the source or uncompressed data
mz_ulong reserved; // not used
} mz_stream;
typedef mz_stream *mz_streamp;
// Returns the version string of miniz.c.
const char *mz_version(void);
// mz_deflateInit() initializes a compressor with default options:
// Parameters:
// pStream must point to an initialized mz_stream struct.
// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
// level 1 enables a specially optimized compression function that's been
// optimized purely for performance, not ratio.
// (This special func. is currently only enabled when
// MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if the input parameters are bogus.
// MZ_MEM_ERROR on out of memory.
int mz_deflateInit(mz_streamp pStream, int level);
// mz_deflateInit2() is like mz_deflate(), except with more control:
// Additional parameters:
// method must be MZ_DEFLATED
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
// zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
// header or footer)
// mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy);
// Quickly resets a compressor without having to reallocate anything. Same as
// calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
int mz_deflateReset(mz_streamp pStream);
// mz_deflate() compresses the input to output, consuming as much of the input
// and producing as much output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
// MZ_FINISH.
// Return values:
// MZ_OK on success (when flushing, or if more input is needed but not
// available, and/or there's more output to be written but the output buffer
// is full).
// MZ_STREAM_END if all input has been consumed and all output bytes have been
// written. Don't call mz_deflate() on the stream anymore.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input and/or
// output buffers are empty. (Fill up the input buffer or free up some output
// space and try again.)
int mz_deflate(mz_streamp pStream, int flush);
// mz_deflateEnd() deinitializes a compressor:
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
int mz_deflateEnd(mz_streamp pStream);
// mz_deflateBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by deflate(), assuming flush is set to only
// MZ_NO_FLUSH or MZ_FINISH.
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
// Single-call compression functions mz_compress() and mz_compress2():
// Returns MZ_OK on success, or one of the error codes from mz_deflate() on
// failure.
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level);
// mz_compressBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by calling mz_compress().
mz_ulong mz_compressBound(mz_ulong source_len);
// Initializes a decompressor.
int mz_inflateInit(mz_streamp pStream);
// mz_inflateInit2() is like mz_inflateInit() with an additional option that
// controls the window size and whether or not the stream has been wrapped with
// a zlib header/footer:
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
// -MZ_DEFAULT_WINDOW_BITS (raw deflate).
int mz_inflateInit2(mz_streamp pStream, int window_bits);
// Decompresses the input stream to the output, consuming only as much of the
// input as needed, and writing as much to the output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
// On the first call, if flush is MZ_FINISH it's assumed the input and output
// buffers are both sized large enough to decompress the entire stream in a
// single call (this is slightly faster).
// MZ_FINISH implies that there are no more source bytes available beside
// what's already in the input buffer, and that the output buffer is large
// enough to hold the rest of the decompressed data.
// Return values:
// MZ_OK on success. Either more input is needed but not available, and/or
// there's more output to be written but the output buffer is full.
// MZ_STREAM_END if all needed input has been consumed and all output bytes
// have been written. For zlib streams, the adler-32 of the decompressed data
// has also been verified.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_DATA_ERROR if the deflate stream is invalid.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input buffer is
// empty but the inflater needs more input to continue, or if the output
// buffer is not large enough. Call mz_inflate() again
// with more input data, or with more room in the output buffer (except when
// using single call decompression, described above).
int mz_inflate(mz_streamp pStream, int flush);
// Deinitializes a decompressor.
int mz_inflateEnd(mz_streamp pStream);
// Single-call decompression.
// Returns MZ_OK on success, or one of the error codes from mz_inflate() on
// failure.
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
// Returns a string description of the specified error code, or NULL if the
// error code is invalid.
const char *mz_error(int err);
// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
// as a drop-in replacement for the subset of zlib that miniz.c supports.
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
// use zlib in the same project.
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Types and macros
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef long long mz_int64;
typedef unsigned long long mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
// An attempt to work around MSVC's spammy "warning C4127: conditional
// expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// ------------------- ZIP archive reading/writing
#ifndef MINIZ_NO_ARCHIVE_APIS
enum {
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
};
typedef struct {
mz_uint32 m_file_index;
mz_uint32 m_central_dir_ofs;
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
time_t m_time;
#endif
mz_uint32 m_crc32;
mz_uint64 m_comp_size;
mz_uint64 m_uncomp_size;
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
mz_uint64 m_local_header_ofs;
mz_uint32 m_comment_size;
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n);
typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum {
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef struct mz_zip_archive_tag {
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
mz_uint m_total_files;
mz_zip_mode m_zip_mode;
mz_uint m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
void *m_pIO_opaque;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef enum {
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
} mz_zip_flags;
// ZIP archive reading
// Inits a ZIP archive reader.
// These functions read and validate the archive's central directory.
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
mz_uint32 flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint32 flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags);
#endif
// Returns the total number of files in the archive.
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
// Returns detailed information about an archive file entry.
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat);
// Determines if an archive file entry is a directory entry.
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index);
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index);
// Retrieves the filename of an archive file entry.
// Returns the number of bytes written to pFilename, or if filename_buf_size is
// 0 this function returns the number of bytes needed to fully store the
// filename.
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size);
// Attempts to locates a file in the archive's central directory.
// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
// Returns -1 if the file cannot be found.
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
// Extracts a archive file to a memory buffer using no memory allocation.
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
// Extracts a archive file to a memory buffer.
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags);
// Extracts a archive file to a dynamically allocated heap buffer.
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags);
// Extracts a archive file using a callback function to output the file's data.
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
#ifndef MINIZ_NO_STDIO
// Extracts a archive file to a disk file and sets its last accessed and
// modified times.
// This function only extracts files, not archive directory records.
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags);
#endif
// Ends archive reading, freeing all allocations, and closing the input archive
// file if mz_zip_reader_init_file() was used.
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
// ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
// Inits a ZIP archive writer.
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning);
#endif
// Converts a ZIP archive reader object into a writer object, to allow efficient
// in-place file appends to occur on an existing archive.
// For archives opened using mz_zip_reader_init_file, pFilename must be the
// archive's filename so it can be reopened for writing. If the file can't be
// reopened, mz_zip_reader_end() will be called.
// For archives opened using mz_zip_reader_init_mem, the memory block must be
// growable using the realloc callback (which defaults to realloc unless you've
// overridden it).
// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
// user provided m_pWrite function cannot be NULL.
// Note: In-place archive modification is not recommended unless you know what
// you're doing, because if execution stops or something goes wrong before
// the archive is finalized the file's central directory will be hosed.
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename);
// Adds the contents of a memory buffer to an archive. These functions record
// the current local time into the archive.
// To add a directory entry, call this method with an archive name ending in a
// forwardslash with empty buffer.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags);
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32);
#ifndef MINIZ_NO_STDIO
// Adds the contents of a disk file to an archive. This function also records
// the disk file's modified time into the archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size, mz_uint level_and_flags);
#endif
// Adds a file to an archive by fully cloning the data from another archive.
// This function fully clones the source file's compressed data (no
// recompression), along with its full filename, extra data, and comment fields.
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint file_index);
// Finalizes the archive by writing the central directory records followed by
// the end of central directory record.
// After an archive is finalized, the only valid call on the mz_zip_archive
// struct is mz_zip_writer_end().
// An archive must be manually finalized by calling this function for it to be
// valid.
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
size_t *pSize);
// Ends archive writing, freeing all allocations, and closing the output file if
// mz_zip_writer_init_file() was used.
// Note for the archive to be valid, it must have been finalized before ending.
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
// Misc. high-level helper functions:
// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
// appends a memory blob to a ZIP archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags);
// Reads a single file from an archive into a heap block.
// Returns NULL on failure.
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
// ------------------- Low-level Decompression API Definitions
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
// ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
// input is a raw deflate stream.
// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
// beyond the end of the supplied input buffer. If clear, the input buffer
// contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
// enough to hold the entire decompressed stream. If clear, the output buffer is
// at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
// decompressed bytes.
enum {
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
// allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
// to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger
// than src_buf_len on uncompressible data.
// The caller must call mz_free() on the returned block when it's no longer
// needed.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
// in memory.
// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
// written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an
// internal 32KB buffer, and a user provided callback function will be called to
// flush the buffer.
// Returns 1 on success or 0 on failure.
typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag;
typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum {
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) \
do { \
(r)->m_state = 0; \
} \
MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function
// actually needed for decompression. All the other functions are just
// high-level helpers for improved usability.
// This is a universal API, i.e. it can be used as a building block to build any
// desired higher level decompression API. In the limit case, it can be called
// once per every byte input or output.
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum {
TINFL_MAX_HUFF_TABLES = 3,
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10,
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct {
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag {
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
m_check_adler32, m_dist, m_counter, m_num_extra,
m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4],
m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
// ------------------- Low-level Compression API Definitions
// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
// slower, and raw/dynamic blocks will be output more frequently).
#define TDEFL_LESS_MEMORY 0
// tdefl_init() compression flags logically OR'd together (low 12 bits contain
// the max. number of probes per dictionary search):
// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
// per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
// compression), 4095=Huffman+LZ (slowest/best compression).
enum {
TDEFL_HUFFMAN_ONLY = 0,
TDEFL_DEFAULT_MAX_PROBES = 128,
TDEFL_MAX_PROBES_MASK = 0xFFF
};
// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
// the deflate data, and the Adler-32 of the source data at the end. Otherwise,
// you'll get raw deflate data.
// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
// when not writing zlib headers).
// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
// efficient lazy parsing.
// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
// initialization time to the minimum, but the output may vary from run to run
// given the same input (depending on the contents of memory).
// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
// The low 12 bits are reserved to control the max # of hash probes per
// dictionary lookup (see TDEFL_MAX_PROBES_MASK).
enum {
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
// High level compression functions:
// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
// allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of source block to compress.
// flags: The max match finder probes (default is 128) logically OR'd against
// the above flags. Higher probes are slower but improve compression.
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pOut_len will be set to the compressed data's size, which could be larger
// than src_buf_len on uncompressible data.
// The caller must free() the returned block when it's no longer needed.
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
// tdefl_compress_mem_to_mem() compresses a block in memory to another block in
// memory.
// Returns 0 on failure.
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
// Compresses an image to a compressed PNG file in memory.
// On entry:
// pImage, w, h, and num_chans describe the image to compress. num_chans may be
// 1, 2, 3, or 4.
// The image pitch in bytes per scanline will be w*num_chans. The leftmost
// pixel on the top scanline is stored first in memory.
// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
// If flip is true, the image will be flipped on the Y axis (useful for OpenGL
// apps).
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pLen_out will be set to the size of the PNG image file.
// The caller must mz_free() the returned heap block (which will typically be
// larger than *pLen_out) when it's no longer needed.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out);
// Output stream interface. The compressor uses this interface to write
// compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
void *pUser);
// tdefl_compress_mem_to_output() compresses a block to an output stream. The
// above helpers use this function internally.
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
enum {
TDEFL_MAX_HUFF_TABLES = 3,
TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
TDEFL_LZ_DICT_SIZE = 32768,
TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
TDEFL_MIN_MATCH_LEN = 3,
TDEFL_MAX_MATCH_LEN = 258
};
// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
// output block (using static/fixed Huffman codes).
#if TDEFL_LESS_MEMORY
enum {
TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 12,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#else
enum {
TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 15,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#endif
// The low-level tdefl functions below may be used directly if the above helper
// functions aren't flexible enough. The low-level functions don't make any heap
// allocations, unlike the above helper functions.
typedef enum {
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1,
} tdefl_status;
// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
typedef enum {
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
// tdefl's compression state structure.
typedef struct {
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
// Initializes the compressor.
// There is no corresponding deinit() function because the tdefl API's do not
// dynamically allocate memory.
// pBut_buf_func: If NULL, output data will be supplied to the specified
// callback. In this case, the user should call the tdefl_compress_buffer() API
// for compression.
// If pBut_buf_func is NULL the user should always call the tdefl_compress()
// API.
// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
// etc.)
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
// Compresses a block of data, consuming as much of the specified input buffer
// as possible, and writing as much compressed data to the specified output
// buffer as possible.
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush);
// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
// non-NULL tdefl_put_buf_func_ptr.
// tdefl_compress_buffer() always consumes the entire input buffer.
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
// defined, because it uses some of its macros.
#ifndef MINIZ_NO_ZLIB_APIS
// Create tdefl_compress() flags given zlib-style compression parameters.
// level may range from [0,10] (where 10 is absolute max compression, but may be
// much slower on some files)
// window_bits may be -15 (raw deflate) or 15 (zlib)
// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
// MZ_RLE, or MZ_FIXED
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy);
#endif // #ifndef MINIZ_NO_ZLIB_APIS
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_INCLUDED
// ------------------- End of Header: Implementation follows. (If you only want
// the header, define MINIZ_HEADER_FILE_ONLY.)
#ifndef MINIZ_HEADER_FILE_ONLY
typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
#include <string.h>
#include <assert.h>
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void) x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
#else
#define MZ_READ_LE16(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#endif
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API's
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
size_t block_len = buf_len % 5552;
if (!ptr)
return MZ_ADLER32_INIT;
while (buf_len) {
for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i)
s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
return (s2 << 16) + s1;
}
// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
// implementation that balances processor cache usage against speed":
// http://www.geocities.com/malbrain/
mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
static const mz_uint32 s_crc32[16] = {
0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
mz_uint32 crcu32 = (mz_uint32)crc;
if (!ptr)
return MZ_CRC32_INIT;
crcu32 = ~crcu32;
while (buf_len--) {
mz_uint8 b = *ptr++;
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
}
return ~crcu32;
}
void mz_free(void *p) { MZ_FREE(p); }
#ifndef MINIZ_NO_ZLIB_APIS
static void *def_alloc_func(void *opaque, size_t items, size_t size) {
(void)opaque, (void)items, (void)size;
return MZ_MALLOC(items * size);
}
static void def_free_func(void *opaque, void *address) {
(void)opaque, (void)address;
MZ_FREE(address);
}
static void *def_realloc_func(void *opaque, void *address, size_t items,
size_t size) {
(void)opaque, (void)address, (void)items, (void)size;
return MZ_REALLOC(address, items * size);
}
const char *mz_version(void) { return MZ_VERSION; }
int mz_deflateInit(mz_streamp pStream, int level) {
return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
MZ_DEFAULT_STRATEGY);
}
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy) {
tdefl_compressor *pComp;
mz_uint comp_flags =
TDEFL_COMPUTE_ADLER32 |
tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
if (!pStream)
return MZ_STREAM_ERROR;
if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
(-window_bits != MZ_DEFAULT_WINDOW_BITS)))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = MZ_ADLER32_INIT;
pStream->msg = NULL;
pStream->reserved = 0;
pStream->total_in = 0;
pStream->total_out = 0;
if (!pStream->zalloc)
pStream->zalloc = def_alloc_func;
if (!pStream->zfree)
pStream->zfree = def_free_func;
pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
sizeof(tdefl_compressor));
if (!pComp)
return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pComp;
if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
mz_deflateEnd(pStream);
return MZ_PARAM_ERROR;
}
return MZ_OK;
}
int mz_deflateReset(mz_streamp pStream) {
if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
(!pStream->zfree))
return MZ_STREAM_ERROR;
pStream->total_in = pStream->total_out = 0;
tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
((tdefl_compressor *)pStream->state)->m_flags);
return MZ_OK;
}
int mz_deflate(mz_streamp pStream, int flush) {
size_t in_bytes, out_bytes;
mz_ulong orig_total_in, orig_total_out;
int mz_status = MZ_OK;
if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
(!pStream->next_out))
return MZ_STREAM_ERROR;
if (!pStream->avail_out)
return MZ_BUF_ERROR;
if (flush == MZ_PARTIAL_FLUSH)
flush = MZ_SYNC_FLUSH;
if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
TDEFL_STATUS_DONE)
return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
orig_total_in = pStream->total_in;
orig_total_out = pStream->total_out;
for (;;) {
tdefl_status defl_status;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
pStream->next_in, &in_bytes, pStream->next_out,
&out_bytes, (tdefl_flush)flush);
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (defl_status < 0) {
mz_status = MZ_STREAM_ERROR;
break;
} else if (defl_status == TDEFL_STATUS_DONE) {
mz_status = MZ_STREAM_END;
break;
} else if (!pStream->avail_out)
break;
else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
if ((flush) || (pStream->total_in != orig_total_in) ||
(pStream->total_out != orig_total_out))
break;
return MZ_BUF_ERROR; // Can't make forward progress without some input.
}
}
return mz_status;
}
int mz_deflateEnd(mz_streamp pStream) {
if (!pStream)
return MZ_STREAM_ERROR;
if (pStream->state) {
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
(void)pStream;
// This is really over conservative. (And lame, but it's actually pretty
// tricky to compute a true upper bound given the way tdefl's blocking works.)
return MZ_MAX(128 + (source_len * 110) / 100,
128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
}
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level) {
int status;
mz_stream stream;
memset(&stream, 0, sizeof(stream));
// In case mz_ulong is 64-bits (argh I hate longs).
if ((source_len | *pDest_len) > 0xFFFFFFFFU)
return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_deflateInit(&stream, level);
if (status != MZ_OK)
return status;
status = mz_deflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END) {
mz_deflateEnd(&stream);
return (status == MZ_OK) ? MZ_BUF_ERROR : status;
}
*pDest_len = stream.total_out;
return mz_deflateEnd(&stream);
}
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len) {
return mz_compress2(pDest, pDest_len, pSource, source_len,
MZ_DEFAULT_COMPRESSION);
}
mz_ulong mz_compressBound(mz_ulong source_len) {
return mz_deflateBound(NULL, source_len);
}
typedef struct {
tinfl_decompressor m_decomp;
mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
int m_window_bits;
mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
tinfl_status m_last_status;
} inflate_state;
int mz_inflateInit2(mz_streamp pStream, int window_bits) {
inflate_state *pDecomp;
if (!pStream)
return MZ_STREAM_ERROR;
if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
(-window_bits != MZ_DEFAULT_WINDOW_BITS))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = 0;
pStream->msg = NULL;
pStream->total_in = 0;
pStream->total_out = 0;
pStream->reserved = 0;
if (!pStream->zalloc)
pStream->zalloc = def_alloc_func;
if (!pStream->zfree)
pStream->zfree = def_free_func;
pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
sizeof(inflate_state));
if (!pDecomp)
return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pDecomp;
tinfl_init(&pDecomp->m_decomp);
pDecomp->m_dict_ofs = 0;
pDecomp->m_dict_avail = 0;
pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
pDecomp->m_first_call = 1;
pDecomp->m_has_flushed = 0;
pDecomp->m_window_bits = window_bits;
return MZ_OK;
}
int mz_inflateInit(mz_streamp pStream) {
return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
}
int mz_inflate(mz_streamp pStream, int flush) {
inflate_state *pState;
mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
size_t in_bytes, out_bytes, orig_avail_in;
tinfl_status status;
if ((!pStream) || (!pStream->state))
return MZ_STREAM_ERROR;
if (flush == MZ_PARTIAL_FLUSH)
flush = MZ_SYNC_FLUSH;
if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState = (inflate_state *)pStream->state;
if (pState->m_window_bits > 0)
decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
orig_avail_in = pStream->avail_in;
first_call = pState->m_first_call;
pState->m_first_call = 0;
if (pState->m_last_status < 0)
return MZ_DATA_ERROR;
if (pState->m_has_flushed && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState->m_has_flushed |= (flush == MZ_FINISH);
if ((flush == MZ_FINISH) && (first_call)) {
// MZ_FINISH on the first call implies that the input and output buffers are
// large enough to hold the entire compressed/decompressed file.
decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
pStream->next_out, pStream->next_out, &out_bytes,
decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (status < 0)
return MZ_DATA_ERROR;
else if (status != TINFL_STATUS_DONE) {
pState->m_last_status = TINFL_STATUS_FAILED;
return MZ_BUF_ERROR;
}
return MZ_STREAM_END;
}
// flush != MZ_FINISH then we must assume there's more input.
if (flush != MZ_FINISH)
decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
if (pState->m_dict_avail) {
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
return ((pState->m_last_status == TINFL_STATUS_DONE) &&
(!pState->m_dict_avail))
? MZ_STREAM_END
: MZ_OK;
}
for (;;) {
in_bytes = pStream->avail_in;
out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
status = tinfl_decompress(
&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pState->m_dict_avail = (mz_uint)out_bytes;
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
if (status < 0)
return MZ_DATA_ERROR; // Stream is corrupted (there could be some
// uncompressed data left in the output dictionary -
// oh well).
else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
// without supplying more input or by setting flush
// to MZ_FINISH.
else if (flush == MZ_FINISH) {
// The output buffer MUST be large to hold the remaining uncompressed data
// when flush==MZ_FINISH.
if (status == TINFL_STATUS_DONE)
return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
// status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
// at least 1 more byte on the way. If there's no more room left in the
// output buffer then something is wrong.
else if (!pStream->avail_out)
return MZ_BUF_ERROR;
} else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
(!pStream->avail_out) || (pState->m_dict_avail))
break;
}
return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
? MZ_STREAM_END
: MZ_OK;
}
int mz_inflateEnd(mz_streamp pStream) {
if (!pStream)
return MZ_STREAM_ERROR;
if (pStream->state) {
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len) {
mz_stream stream;
int status;
memset(&stream, 0, sizeof(stream));
// In case mz_ulong is 64-bits (argh I hate longs).
if ((source_len | *pDest_len) > 0xFFFFFFFFU)
return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_inflateInit(&stream);
if (status != MZ_OK)
return status;
status = mz_inflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END) {
mz_inflateEnd(&stream);
return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
: status;
}
*pDest_len = stream.total_out;
return mz_inflateEnd(&stream);
}
const char *mz_error(int err) {
static struct {
int m_err;
const char *m_pDesc;
} s_error_descs[] = {{MZ_OK, ""},
{MZ_STREAM_END, "stream end"},
{MZ_NEED_DICT, "need dictionary"},
{MZ_ERRNO, "file error"},
{MZ_STREAM_ERROR, "stream error"},
{MZ_DATA_ERROR, "data error"},
{MZ_MEM_ERROR, "out of memory"},
{MZ_BUF_ERROR, "buf error"},
{MZ_VERSION_ERROR, "version error"},
{MZ_PARAM_ERROR, "parameter error"}};
mz_uint i;
for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
if (s_error_descs[i].m_err == err)
return s_error_descs[i].m_pDesc;
return NULL;
}
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Low-level Decompression (completely independent from all
// compression API's)
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN \
switch (r->m_state) { \
case 0:
#define TINFL_CR_RETURN(state_index, result) \
do { \
status = result; \
r->m_state = state_index; \
goto common_exit; \
case state_index: \
; \
} \
MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) \
do { \
for (;;) { \
TINFL_CR_RETURN(state_index, result); \
} \
} \
MZ_MACRO_END
#define TINFL_CR_FINISH }
// TODO: If the caller has indicated that there's no more input, and we attempt
// to read beyond the input buf, then something is wrong with the input because
// the inflator never
// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
// the stream with 0's in this scenario.
#define TINFL_GET_BYTE(state_index, c) \
do { \
if (pIn_buf_cur >= pIn_buf_end) { \
for (;;) { \
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
if (pIn_buf_cur < pIn_buf_end) { \
c = *pIn_buf_cur++; \
break; \
} \
} else { \
c = 0; \
break; \
} \
} \
} else \
c = *pIn_buf_cur++; \
} \
MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) \
do { \
mz_uint c; \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) \
do { \
if (num_bits < (mz_uint)(n)) { \
TINFL_NEED_BITS(state_index, n); \
} \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) \
do { \
if (num_bits < (mz_uint)(n)) { \
TINFL_NEED_BITS(state_index, n); \
} \
b = bit_buf & ((1 << (n)) - 1); \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
// remaining in the input buffer falls below 2.
// It reads just enough bytes from the input stream that are needed to decode
// the next Huffman code (and absolutely no more). It works by trying to fully
// decode a
// Huffman code by using whatever bits are currently present in the bit buffer.
// If this fails, it reads another byte, and tries again until it succeeds or
// until the
// bit buffer contains >=15 bits (deflate's max. Huffman code size).
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do { \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) { \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) \
break; \
} else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); \
if (temp >= 0) \
break; \
} \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < 15);
// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
// than you would initially expect because the zlib API expects the decompressor
// to never read
// beyond the final byte of the deflate stream. (In other words, when this macro
// wants to read another byte from the input, it REALLY needs another byte in
// order to fully
// decode the next Huffman code.) Handling this properly is particularly
// important on raw deflate (non-zlib) streams, which aren't followed by a byte
// aligned adler-32.
// The slow path is only executed at the very end of the input buffer.
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
do { \
int temp; \
mz_uint code_len, c; \
if (num_bits < 15) { \
if ((pIn_buf_end - pIn_buf_cur) < 2) { \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} else { \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
(((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
pIn_buf_cur += 2; \
num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
0) \
code_len = temp >> 9, temp &= 511; \
else { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while (temp < 0); \
} \
sym = temp; \
bit_buf >>= code_len; \
num_bits -= code_len; \
} \
MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags) {
static const int s_length_base[31] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
4, 4, 5, 5, 5, 5, 0, 0, 0};
static const int s_dist_base[32] = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
static const mz_uint8 s_length_dezigzag[19] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
static const int s_min_table_sizes[3] = {257, 1, 4};
tinfl_status status = TINFL_STATUS_FAILED;
mz_uint32 num_bits, dist, counter, num_extra;
tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next,
*const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next,
*const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask =
(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
? (size_t)-1
: ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
dist_from_out_buf_start;
// Ensure the output buffer's size is a power of 2, unless the output buffer
// is large enough to hold the entire output file (in which case it doesn't
// matter).
if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
(pOut_buf_next < pOut_buf_start)) {
*pIn_buf_size = *pOut_buf_size = 0;
return TINFL_STATUS_BAD_PARAM;
}
num_bits = r->m_num_bits;
bit_buf = r->m_bit_buf;
dist = r->m_dist;
counter = r->m_counter;
num_extra = r->m_num_extra;
dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
TINFL_GET_BYTE(1, r->m_zhdr0);
TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
(r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
((out_buf_size_mask + 1) <
(size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
if (counter) {
TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
}
}
do {
TINFL_GET_BITS(3, r->m_final, 3);
r->m_type = r->m_final >> 1;
if (r->m_type == 0) {
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter) {
if (num_bits)
TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
else
TINFL_GET_BYTE(7, r->m_raw_header[counter]);
}
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
(mz_uint)(0xFFFF ^
(r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
}
while ((counter) && (num_bits)) {
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter) {
size_t n;
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
}
while (pIn_buf_cur >= pIn_buf_end) {
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
} else {
TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
}
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
(size_t)(pIn_buf_end - pIn_buf_cur)),
counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
pIn_buf_cur += n;
pOut_buf_cur += n;
counter -= (mz_uint)n;
}
} else if (r->m_type == 3) {
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
} else {
if (r->m_type == 1) {
mz_uint8 *p = r->m_tables[0].m_code_size;
mz_uint i;
r->m_table_sizes[0] = 288;
r->m_table_sizes[1] = 32;
TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for (i = 0; i <= 143; ++i)
*p++ = 8;
for (; i <= 255; ++i)
*p++ = 9;
for (; i <= 279; ++i)
*p++ = 7;
for (; i <= 287; ++i)
*p++ = 8;
} else {
for (counter = 0; counter < 3; counter++) {
TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
r->m_table_sizes[counter] += s_min_table_sizes[counter];
}
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
mz_uint s;
TINFL_GET_BITS(14, s, 3);
r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
}
r->m_table_sizes[2] = 19;
}
for (; (int)r->m_type >= 0; r->m_type--) {
int tree_next, tree_cur;
tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17],
total_syms[16];
pTable = &r->m_tables[r->m_type];
MZ_CLEAR_OBJ(total_syms);
MZ_CLEAR_OBJ(pTable->m_look_up);
MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0;
next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i) {
used_syms += total_syms[i];
next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
}
if ((65536 != total) && (used_syms > 1)) {
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0;
sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
mz_uint rev_code = 0, l, cur_code,
code_size = pTable->m_code_size[sym_index];
if (!code_size)
continue;
cur_code = next_code[code_size]++;
for (l = code_size; l > 0; l--, cur_code >>= 1)
rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS) {
mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
pTable->m_look_up[rev_code] = k;
rev_code += (1 << code_size);
}
continue;
}
if (0 ==
(tree_cur = pTable->m_look_up[rev_code &
(TINFL_FAST_LOOKUP_SIZE - 1)])) {
pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
(mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1]) {
pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
} else
tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1);
pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2) {
for (counter = 0;
counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
mz_uint s;
TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
if (dist < 16) {
r->m_len_codes[counter++] = (mz_uint8)dist;
continue;
}
if ((dist == 16) && (!counter)) {
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16];
TINFL_GET_BITS(18, s, num_extra);
s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter,
(dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
r->m_table_sizes[0]);
TINFL_MEMCPY(r->m_tables[1].m_code_size,
r->m_len_codes + r->m_table_sizes[0],
r->m_table_sizes[1]);
}
}
for (;;) {
mz_uint8 *pSrc;
for (;;) {
if (((pIn_buf_end - pIn_buf_cur) < 4) ||
((pOut_buf_end - pOut_buf_cur) < 2)) {
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256)
break;
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)counter;
} else {
int sym2;
mz_uint code_len;
#if TINFL_USE_64BIT_BITBUF
if (num_bits < 30) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 4;
num_bits += 32;
}
#else
if (num_bits < 15) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 =
r->m_tables[0]
.m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
0)
code_len = sym2 >> 9;
else {
code_len = TINFL_FAST_LOOKUP_BITS;
do {
sym2 = r->m_tables[0]
.m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
counter = sym2;
bit_buf >>= code_len;
num_bits -= code_len;
if (counter & 256)
break;
#if !TINFL_USE_64BIT_BITBUF
if (num_bits < 15) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 =
r->m_tables[0]
.m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
0)
code_len = sym2 >> 9;
else {
code_len = TINFL_FAST_LOOKUP_BITS;
do {
sym2 = r->m_tables[0]
.m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
bit_buf >>= code_len;
num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256) {
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256)
break;
num_extra = s_length_extra[counter - 257];
counter = s_length_base[counter - 257];
if (num_extra) {
mz_uint extra_bits;
TINFL_GET_BITS(25, extra_bits, num_extra);
counter += extra_bits;
}
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist];
dist = s_dist_base[dist];
if (num_extra) {
mz_uint extra_bits;
TINFL_GET_BITS(27, extra_bits, num_extra);
dist += extra_bits;
}
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) &&
(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start +
((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
while (counter--) {
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ =
pOut_buf_start[(dist_from_out_buf_start++ - dist) &
out_buf_size_mask];
}
continue;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
else if ((counter >= 9) && (counter <= dist)) {
const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
do {
((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
pOut_buf_cur += 8;
} while ((pSrc += 8) < pSrc_end);
if ((counter &= 7) < 3) {
if (counter) {
pOut_buf_cur[0] = pSrc[0];
if (counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
continue;
}
}
#endif
do {
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3;
pSrc += 3;
} while ((int)(counter -= 3) > 2);
if ((int)counter > 0) {
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
} while (!(r->m_final & 1));
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
TINFL_SKIP_BITS(32, num_bits & 7);
for (counter = 0; counter < 4; ++counter) {
mz_uint s;
if (num_bits)
TINFL_GET_BITS(41, s, 8);
else
TINFL_GET_BYTE(42, s);
r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
}
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
r->m_num_bits = num_bits;
r->m_bit_buf = bit_buf;
r->m_dist = dist;
r->m_counter = counter;
r->m_num_extra = num_extra;
r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next;
*pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags &
(TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
(status >= 0)) {
const mz_uint8 *ptr = pOut_buf_next;
size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
s2 = r->m_check_adler32 >> 16;
size_t block_len = buf_len % 5552;
while (buf_len) {
for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i)
s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1;
if ((status == TINFL_STATUS_DONE) &&
(decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
(r->m_check_adler32 != r->m_z_adler32))
status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
// Higher level helper functions.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags) {
tinfl_decompressor decomp;
void *pBuf = NULL, *pNew_buf;
size_t src_buf_ofs = 0, out_buf_capacity = 0;
*pOut_len = 0;
tinfl_init(&decomp);
for (;;) {
size_t src_buf_size = src_buf_len - src_buf_ofs,
dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
tinfl_status status = tinfl_decompress(
&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
(mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
&dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
src_buf_ofs += src_buf_size;
*pOut_len += dst_buf_size;
if (status == TINFL_STATUS_DONE)
break;
new_out_buf_capacity = out_buf_capacity * 2;
if (new_out_buf_capacity < 128)
new_out_buf_capacity = 128;
pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
if (!pNew_buf) {
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
pBuf = pNew_buf;
out_buf_capacity = new_out_buf_capacity;
}
return pBuf;
}
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags) {
tinfl_decompressor decomp;
tinfl_status status;
tinfl_init(&decomp);
status =
tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
(mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
(flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
: out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict)
return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for (;;) {
size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status =
tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
&in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags &
~(TINFL_FLAG_HAS_MORE_INPUT |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) &&
(!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
// ------------------- Low-level Compression (independent from all decompression
// API's)
// Purposely making these tables static for faster init and thread safety.
static const mz_uint16 s_tdefl_len_sym[256] = {
257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
285};
static const mz_uint8 s_tdefl_len_extra[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
static const mz_uint8 s_tdefl_small_dist_sym[512] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
static const mz_uint8 s_tdefl_small_dist_extra[512] = {
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
static const mz_uint8 s_tdefl_large_dist_sym[128] = {
0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
static const mz_uint8 s_tdefl_large_dist_extra[128] = {
0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
// values.
typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
tdefl_sym_freq *pSyms0,
tdefl_sym_freq *pSyms1) {
mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
MZ_CLEAR_OBJ(hist);
for (i = 0; i < num_syms; i++) {
mz_uint freq = pSyms0[i].m_key;
hist[freq & 0xFF]++;
hist[256 + ((freq >> 8) & 0xFF)]++;
}
while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
total_passes--;
for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
const mz_uint32 *pHist = &hist[pass << 8];
mz_uint offsets[256], cur_ofs = 0;
for (i = 0; i < 256; i++) {
offsets[i] = cur_ofs;
cur_ofs += pHist[i];
}
for (i = 0; i < num_syms; i++)
pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
pCur_syms[i];
{
tdefl_sym_freq *t = pCur_syms;
pCur_syms = pNew_syms;
pNew_syms = t;
}
}
return pCur_syms;
}
// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
// alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
int root, leaf, next, avbl, used, dpth;
if (n == 0)
return;
else if (n == 1) {
A[0].m_key = 1;
return;
}
A[0].m_key += A[1].m_key;
root = 0;
leaf = 2;
for (next = 1; next < n - 1; next++) {
if (leaf >= n || A[root].m_key < A[leaf].m_key) {
A[next].m_key = A[root].m_key;
A[root++].m_key = (mz_uint16)next;
} else
A[next].m_key = A[leaf++].m_key;
if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
A[root++].m_key = (mz_uint16)next;
} else
A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
}
A[n - 2].m_key = 0;
for (next = n - 3; next >= 0; next--)
A[next].m_key = A[A[next].m_key].m_key + 1;
avbl = 1;
used = dpth = 0;
root = n - 2;
next = n - 1;
while (avbl > 0) {
while (root >= 0 && (int)A[root].m_key == dpth) {
used++;
root--;
}
while (avbl > used) {
A[next--].m_key = (mz_uint16)(dpth);
avbl--;
}
avbl = 2 * used;
dpth++;
used = 0;
}
}
// Limits canonical Huffman code table's max code size.
enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
int code_list_len,
int max_code_size) {
int i;
mz_uint32 total = 0;
if (code_list_len <= 1)
return;
for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
pNum_codes[max_code_size] += pNum_codes[i];
for (i = max_code_size; i > 0; i--)
total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
while (total != (1UL << max_code_size)) {
pNum_codes[max_code_size]--;
for (i = max_code_size - 1; i > 0; i--)
if (pNum_codes[i]) {
pNum_codes[i]--;
pNum_codes[i + 1] += 2;
break;
}
total--;
}
}
static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
int table_len, int code_size_limit,
int static_table) {
int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
MZ_CLEAR_OBJ(num_codes);
if (static_table) {
for (i = 0; i < table_len; i++)
num_codes[d->m_huff_code_sizes[table_num][i]]++;
} else {
tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
*pSyms;
int num_used_syms = 0;
const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
for (i = 0; i < table_len; i++)
if (pSym_count[i]) {
syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
}
pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
for (i = 0; i < num_used_syms; i++)
num_codes[pSyms[i].m_key]++;
tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
code_size_limit);
MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
for (l = num_codes[i]; l > 0; l--)
d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
}
next_code[1] = 0;
for (j = 0, i = 2; i <= code_size_limit; i++)
next_code[i] = j = ((j + num_codes[i - 1]) << 1);
for (i = 0; i < table_len; i++) {
mz_uint rev_code = 0, code, code_size;
if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0)
continue;
code = next_code[code_size]++;
for (l = code_size; l > 0; l--, code >>= 1)
rev_code = (rev_code << 1) | (code & 1);
d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
}
}
#define TDEFL_PUT_BITS(b, l) \
do { \
mz_uint bits = b; \
mz_uint len = l; \
MZ_ASSERT(bits <= ((1U << len) - 1U)); \
d->m_bit_buffer |= (bits << d->m_bits_in); \
d->m_bits_in += len; \
while (d->m_bits_in >= 8) { \
if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
*d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
d->m_bit_buffer >>= 8; \
d->m_bits_in -= 8; \
} \
} \
MZ_MACRO_END
#define TDEFL_RLE_PREV_CODE_SIZE() \
{ \
if (rle_repeat_count) { \
if (rle_repeat_count < 3) { \
d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
while (rle_repeat_count--) \
packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
} else { \
d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 16; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_repeat_count - 3); \
} \
rle_repeat_count = 0; \
} \
}
#define TDEFL_RLE_ZERO_CODE_SIZE() \
{ \
if (rle_z_count) { \
if (rle_z_count < 3) { \
d->m_huff_count[2][0] = \
(mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
while (rle_z_count--) \
packed_code_sizes[num_packed_code_sizes++] = 0; \
} else if (rle_z_count <= 10) { \
d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 17; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_z_count - 3); \
} else { \
d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 18; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_z_count - 11); \
} \
rle_z_count = 0; \
} \
}
static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
static void tdefl_start_dynamic_block(tdefl_compressor *d) {
int num_lit_codes, num_dist_codes, num_bit_lengths;
mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
rle_repeat_count, packed_code_sizes_index;
mz_uint8
code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
prev_code_size = 0xFF;
d->m_huff_count[0][256] = 1;
tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
if (d->m_huff_code_sizes[0][num_lit_codes - 1])
break;
for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
if (d->m_huff_code_sizes[1][num_dist_codes - 1])
break;
memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
num_dist_codes);
total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
num_packed_code_sizes = 0;
rle_z_count = 0;
rle_repeat_count = 0;
memset(&d->m_huff_count[2][0], 0,
sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
for (i = 0; i < total_code_sizes_to_pack; i++) {
mz_uint8 code_size = code_sizes_to_pack[i];
if (!code_size) {
TDEFL_RLE_PREV_CODE_SIZE();
if (++rle_z_count == 138) {
TDEFL_RLE_ZERO_CODE_SIZE();
}
} else {
TDEFL_RLE_ZERO_CODE_SIZE();
if (code_size != prev_code_size) {
TDEFL_RLE_PREV_CODE_SIZE();
d->m_huff_count[2][code_size] =
(mz_uint16)(d->m_huff_count[2][code_size] + 1);
packed_code_sizes[num_packed_code_sizes++] = code_size;
} else if (++rle_repeat_count == 6) {
TDEFL_RLE_PREV_CODE_SIZE();
}
}
prev_code_size = code_size;
}
if (rle_repeat_count) {
TDEFL_RLE_PREV_CODE_SIZE();
} else {
TDEFL_RLE_ZERO_CODE_SIZE();
}
tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
TDEFL_PUT_BITS(2, 2);
TDEFL_PUT_BITS(num_lit_codes - 257, 5);
TDEFL_PUT_BITS(num_dist_codes - 1, 5);
for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
if (d->m_huff_code_sizes
[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
break;
num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
for (i = 0; (int)i < num_bit_lengths; i++)
TDEFL_PUT_BITS(
d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
for (packed_code_sizes_index = 0;
packed_code_sizes_index < num_packed_code_sizes;) {
mz_uint code = packed_code_sizes[packed_code_sizes_index++];
MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
if (code >= 16)
TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
"\02\03\07"[code - 16]);
}
}
static void tdefl_start_static_block(tdefl_compressor *d) {
mz_uint i;
mz_uint8 *p = &d->m_huff_code_sizes[0][0];
for (i = 0; i <= 143; ++i)
*p++ = 8;
for (; i <= 255; ++i)
*p++ = 9;
for (; i <= 279; ++i)
*p++ = 7;
for (; i <= 287; ++i)
*p++ = 8;
memset(d->m_huff_code_sizes[1], 5, 32);
tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
TDEFL_PUT_BITS(1, 2);
}
static const mz_uint mz_bitmasks[17] = {
0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
MINIZ_HAS_64BIT_REGISTERS
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
mz_uint flags;
mz_uint8 *pLZ_codes;
mz_uint8 *pOutput_buf = d->m_pOutput_buf;
mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
mz_uint64 bit_buffer = d->m_bit_buffer;
mz_uint bits_in = d->m_bits_in;
#define TDEFL_PUT_BITS_FAST(b, l) \
{ \
bit_buffer |= (((mz_uint64)(b)) << bits_in); \
bits_in += (l); \
}
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
flags >>= 1) {
if (flags == 1)
flags = *pLZ_codes++ | 0x100;
if (flags & 1) {
mz_uint s0, s1, n0, n1, sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0],
match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
s_tdefl_len_extra[match_len]);
// This sequence coaxes MSVC into using cmov's vs. jmp's.
s0 = s_tdefl_small_dist_sym[match_dist & 511];
n0 = s_tdefl_small_dist_extra[match_dist & 511];
s1 = s_tdefl_large_dist_sym[match_dist >> 8];
n1 = s_tdefl_large_dist_extra[match_dist >> 8];
sym = (match_dist < 512) ? s0 : s1;
num_extra_bits = (match_dist < 512) ? n0 : n1;
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
num_extra_bits);
} else {
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
flags >>= 1;
lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
flags >>= 1;
lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
}
}
}
if (pOutput_buf >= d->m_pOutput_buf_end)
return MZ_FALSE;
*(mz_uint64 *)pOutput_buf = bit_buffer;
pOutput_buf += (bits_in >> 3);
bit_buffer >>= (bits_in & ~7);
bits_in &= 7;
}
#undef TDEFL_PUT_BITS_FAST
d->m_pOutput_buf = pOutput_buf;
d->m_bits_in = 0;
d->m_bit_buffer = 0;
while (bits_in) {
mz_uint32 n = MZ_MIN(bits_in, 16);
TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
bit_buffer >>= n;
bits_in -= n;
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
#else
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
mz_uint flags;
mz_uint8 *pLZ_codes;
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
flags >>= 1) {
if (flags == 1)
flags = *pLZ_codes++ | 0x100;
if (flags & 1) {
mz_uint sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0],
match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
s_tdefl_len_extra[match_len]);
if (match_dist < 512) {
sym = s_tdefl_small_dist_sym[match_dist];
num_extra_bits = s_tdefl_small_dist_extra[match_dist];
} else {
sym = s_tdefl_large_dist_sym[match_dist >> 8];
num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
}
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
} else {
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
}
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
// MINIZ_HAS_64BIT_REGISTERS
static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
if (static_block)
tdefl_start_static_block(d);
else
tdefl_start_dynamic_block(d);
return tdefl_compress_lz_codes(d);
}
static int tdefl_flush_block(tdefl_compressor *d, int flush) {
mz_uint saved_bit_buf, saved_bits_in;
mz_uint8 *pSaved_output_buf;
mz_bool comp_block_succeeded = MZ_FALSE;
int n, use_raw_block =
((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
(d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
mz_uint8 *pOutput_buf_start =
((d->m_pPut_buf_func == NULL) &&
((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
: d->m_output_buf;
d->m_pOutput_buf = pOutput_buf_start;
d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
MZ_ASSERT(!d->m_output_flush_remaining);
d->m_output_flush_ofs = 0;
d->m_output_flush_remaining = 0;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
TDEFL_PUT_BITS(0x78, 8);
TDEFL_PUT_BITS(0x01, 8);
}
TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
pSaved_output_buf = d->m_pOutput_buf;
saved_bit_buf = d->m_bit_buffer;
saved_bits_in = d->m_bits_in;
if (!use_raw_block)
comp_block_succeeded =
tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
(d->m_total_lz_bytes < 48));
// If the block gets expanded, forget the current contents of the output
// buffer and send a raw block instead.
if (((use_raw_block) ||
((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
d->m_total_lz_bytes))) &&
((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
mz_uint i;
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
TDEFL_PUT_BITS(0, 2);
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
}
for (i = 0; i < d->m_total_lz_bytes; ++i) {
TDEFL_PUT_BITS(
d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
8);
}
}
// Check for the extremely unlikely (if not impossible) case of the compressed
// block not fitting into the output buffer when using dynamic codes.
else if (!comp_block_succeeded) {
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
tdefl_compress_block(d, MZ_TRUE);
}
if (flush) {
if (flush == TDEFL_FINISH) {
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
mz_uint i, a = d->m_adler32;
for (i = 0; i < 4; i++) {
TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
a <<= 8;
}
}
} else {
mz_uint i, z = 0;
TDEFL_PUT_BITS(0, 3);
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, z ^= 0xFFFF) {
TDEFL_PUT_BITS(z & 0xFFFF, 16);
}
}
}
MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
memset(&d->m_huff_count[0][0], 0,
sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0,
sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
d->m_total_lz_bytes = 0;
d->m_block_index++;
if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
if (d->m_pPut_buf_func) {
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
} else if (pOutput_buf_start == d->m_output_buf) {
int bytes_to_copy = (int)MZ_MIN(
(size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
bytes_to_copy);
d->m_out_buf_ofs += bytes_to_copy;
if ((n -= bytes_to_copy) != 0) {
d->m_output_flush_ofs = bytes_to_copy;
d->m_output_flush_remaining = n;
}
} else {
d->m_out_buf_ofs += n;
}
}
return d->m_output_flush_remaining;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
static MZ_FORCEINLINE void
tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
mz_uint max_match_len, mz_uint *pMatch_dist,
mz_uint *pMatch_len) {
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
s01 = TDEFL_READ_UNALIGNED_WORD(s);
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len)
return;
for (;;) {
for (;;) {
if (--num_probes_left == 0)
return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || \
((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist)
break;
q = (const mz_uint16 *)(d->m_dict + probe_pos);
if (TDEFL_READ_UNALIGNED_WORD(q) != s01)
continue;
p = s;
probe_len = 32;
do {
} while (
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(--probe_len > 0));
if (!probe_len) {
*pMatch_dist = dist;
*pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
break;
} else if ((probe_len = ((mz_uint)(p - s) * 2) +
(mz_uint)(*(const mz_uint8 *)p ==
*(const mz_uint8 *)q)) > match_len) {
*pMatch_dist = dist;
if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
max_match_len)
break;
c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
}
}
}
#else
static MZ_FORCEINLINE void
tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
mz_uint max_match_len, mz_uint *pMatch_dist,
mz_uint *pMatch_len) {
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint8 *s = d->m_dict + pos, *p, *q;
mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len)
return;
for (;;) {
for (;;) {
if (--num_probes_left == 0)
return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || \
((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if ((d->m_dict[probe_pos + match_len] == c0) && \
(d->m_dict[probe_pos + match_len - 1] == c1)) \
break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist)
break;
p = s;
q = d->m_dict + probe_pos;
for (probe_len = 0; probe_len < max_match_len; probe_len++)
if (*p++ != *q++)
break;
if (probe_len > match_len) {
*pMatch_dist = dist;
if ((*pMatch_len = match_len = probe_len) == max_match_len)
return;
c0 = d->m_dict[pos + match_len];
c1 = d->m_dict[pos + match_len - 1];
}
}
}
#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
// Faster, minimally featured LZRW1-style match+parse loop with better
// register utilization. Intended for applications where raw throughput is
// valued more highly than ratio.
mz_uint lookahead_pos = d->m_lookahead_pos,
lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
total_lz_bytes = d->m_total_lz_bytes,
num_flags_left = d->m_num_flags_left;
mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
mz_uint dst_pos =
(lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
d->m_src_buf_left -= num_bytes_to_process;
lookahead_size += num_bytes_to_process;
while (num_bytes_to_process) {
mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
d->m_pSrc += n;
dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
num_bytes_to_process -= n;
}
dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
break;
while (lookahead_size >= 4) {
mz_uint cur_match_dist, cur_match_len = 1;
mz_uint8 *pCur_dict = d->m_dict + cur_pos;
mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
mz_uint hash =
(first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
TDEFL_LEVEL1_HASH_SIZE_MASK;
mz_uint probe_pos = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)lookahead_pos;
if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
dict_size) &&
((*(const mz_uint32 *)(d->m_dict +
(probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
0xFFFFFF) == first_trigram)) {
const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
mz_uint32 probe_len = 32;
do {
} while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(--probe_len > 0));
cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
(mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
if (!probe_len)
cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 8U * 1024U))) {
cur_match_len = 1;
*pLZ_code_buf++ = (mz_uint8)first_trigram;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
d->m_huff_count[0][(mz_uint8)first_trigram]++;
} else {
mz_uint32 s0, s1;
cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 1) &&
(cur_match_dist <= TDEFL_LZ_DICT_SIZE));
cur_match_dist--;
pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
*(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
pLZ_code_buf += 3;
*pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
TDEFL_MIN_MATCH_LEN]]++;
}
} else {
*pLZ_code_buf++ = (mz_uint8)first_trigram;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
d->m_huff_count[0][(mz_uint8)first_trigram]++;
}
if (--num_flags_left == 0) {
num_flags_left = 8;
pLZ_flags = pLZ_code_buf++;
}
total_lz_bytes += cur_match_len;
lookahead_pos += cur_match_len;
dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
MZ_ASSERT(lookahead_size >= cur_match_len);
lookahead_size -= cur_match_len;
if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
int n;
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
total_lz_bytes = d->m_total_lz_bytes;
pLZ_code_buf = d->m_pLZ_code_buf;
pLZ_flags = d->m_pLZ_flags;
num_flags_left = d->m_num_flags_left;
}
}
while (lookahead_size) {
mz_uint8 lit = d->m_dict[cur_pos];
total_lz_bytes++;
*pLZ_code_buf++ = lit;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
if (--num_flags_left == 0) {
num_flags_left = 8;
pLZ_flags = pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
lookahead_pos++;
dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
lookahead_size--;
if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
int n;
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
total_lz_bytes = d->m_total_lz_bytes;
pLZ_code_buf = d->m_pLZ_code_buf;
pLZ_flags = d->m_pLZ_flags;
num_flags_left = d->m_num_flags_left;
}
}
}
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
return MZ_TRUE;
}
#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
mz_uint8 lit) {
d->m_total_lz_bytes++;
*d->m_pLZ_code_buf++ = lit;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
if (--d->m_num_flags_left == 0) {
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
}
static MZ_FORCEINLINE void
tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) {
mz_uint32 s0, s1;
MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
(match_dist <= TDEFL_LZ_DICT_SIZE));
d->m_total_lz_bytes += match_len;
d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
match_dist -= 1;
d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
d->m_pLZ_code_buf += 3;
*d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
if (--d->m_num_flags_left == 0) {
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
s0 = s_tdefl_small_dist_sym[match_dist & 511];
s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
if (match_len >= TDEFL_MIN_MATCH_LEN)
d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
}
static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
const mz_uint8 *pSrc = d->m_pSrc;
size_t src_buf_left = d->m_src_buf_left;
tdefl_flush flush = d->m_flush;
while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
// Update dictionary and hash chains. Keeps the lookahead size equal to
// TDEFL_MAX_MATCH_LEN.
if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
TDEFL_LZ_DICT_SIZE_MASK,
ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
<< TDEFL_LZ_HASH_SHIFT) ^
d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
src_buf_left -= num_bytes_to_process;
d->m_lookahead_size += num_bytes_to_process;
while (pSrc != pSrc_end) {
mz_uint8 c = *pSrc++;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
ins_pos++;
}
} else {
while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
mz_uint8 c = *pSrc++;
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
TDEFL_LZ_DICT_SIZE_MASK;
src_buf_left--;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
<< (TDEFL_LZ_HASH_SHIFT * 2)) ^
(d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
<< TDEFL_LZ_HASH_SHIFT) ^
c) &
(TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
}
}
}
d->m_dict_size =
MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
break;
// Simple lazy/greedy parsing state machine.
len_to_move = 1;
cur_match_dist = 0;
cur_match_len =
d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
cur_match_len = 0;
while (cur_match_len < d->m_lookahead_size) {
if (d->m_dict[cur_pos + cur_match_len] != c)
break;
cur_match_len++;
}
if (cur_match_len < TDEFL_MIN_MATCH_LEN)
cur_match_len = 0;
else
cur_match_dist = 1;
}
} else {
tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
d->m_lookahead_size, &cur_match_dist, &cur_match_len);
}
if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 8U * 1024U)) ||
(cur_pos == cur_match_dist) ||
((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
cur_match_dist = cur_match_len = 0;
}
if (d->m_saved_match_len) {
if (cur_match_len > d->m_saved_match_len) {
tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
if (cur_match_len >= 128) {
tdefl_record_match(d, cur_match_len, cur_match_dist);
d->m_saved_match_len = 0;
len_to_move = cur_match_len;
} else {
d->m_saved_lit = d->m_dict[cur_pos];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
} else {
tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
len_to_move = d->m_saved_match_len - 1;
d->m_saved_match_len = 0;
}
} else if (!cur_match_dist)
tdefl_record_literal(d,
d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
(cur_match_len >= 128)) {
tdefl_record_match(d, cur_match_len, cur_match_dist);
len_to_move = cur_match_len;
} else {
d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
// Move the lookahead forward by len_to_move bytes.
d->m_lookahead_pos += len_to_move;
MZ_ASSERT(d->m_lookahead_size >= len_to_move);
d->m_lookahead_size -= len_to_move;
d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
// Check if it's time to flush the current LZ codes to the internal output
// buffer.
if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
((d->m_total_lz_bytes > 31 * 1024) &&
(((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
d->m_total_lz_bytes) ||
(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
int n;
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
}
}
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
return MZ_TRUE;
}
static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
if (d->m_pIn_buf_size) {
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
}
if (d->m_pOut_buf_size) {
size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
d->m_output_flush_remaining);
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
d->m_output_buf + d->m_output_flush_ofs, n);
d->m_output_flush_ofs += (mz_uint)n;
d->m_output_flush_remaining -= (mz_uint)n;
d->m_out_buf_ofs += n;
*d->m_pOut_buf_size = d->m_out_buf_ofs;
}
return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
: TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush) {
if (!d) {
if (pIn_buf_size)
*pIn_buf_size = 0;
if (pOut_buf_size)
*pOut_buf_size = 0;
return TDEFL_STATUS_BAD_PARAM;
}
d->m_pIn_buf = pIn_buf;
d->m_pIn_buf_size = pIn_buf_size;
d->m_pOut_buf = pOut_buf;
d->m_pOut_buf_size = pOut_buf_size;
d->m_pSrc = (const mz_uint8 *)(pIn_buf);
d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
d->m_out_buf_ofs = 0;
d->m_flush = flush;
if (((d->m_pPut_buf_func != NULL) ==
((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
(d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
(d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
(pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
(pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
if (pIn_buf_size)
*pIn_buf_size = 0;
if (pOut_buf_size)
*pOut_buf_size = 0;
return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
}
d->m_wants_to_finish |= (flush == TDEFL_FINISH);
if ((d->m_output_flush_remaining) || (d->m_finished))
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
TDEFL_RLE_MATCHES)) == 0)) {
if (!tdefl_compress_fast(d))
return d->m_prev_return_status;
} else
#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
{
if (!tdefl_compress_normal(d))
return d->m_prev_return_status;
}
if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
(pIn_buf))
d->m_adler32 =
(mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
d->m_pSrc - (const mz_uint8 *)pIn_buf);
if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
(!d->m_output_flush_remaining)) {
if (tdefl_flush_block(d, flush) < 0)
return d->m_prev_return_status;
d->m_finished = (flush == TDEFL_FINISH);
if (flush == TDEFL_FULL_FLUSH) {
MZ_CLEAR_OBJ(d->m_hash);
MZ_CLEAR_OBJ(d->m_next);
d->m_dict_size = 0;
}
}
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
}
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush) {
MZ_ASSERT(d->m_pPut_buf_func);
return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
}
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
d->m_pPut_buf_func = pPut_buf_func;
d->m_pPut_buf_user = pPut_buf_user;
d->m_flags = (mz_uint)(flags);
d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))
MZ_CLEAR_OBJ(d->m_hash);
d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_pOutput_buf = d->m_output_buf;
d->m_pOutput_buf_end = d->m_output_buf;
d->m_prev_return_status = TDEFL_STATUS_OKAY;
d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
d->m_adler32 = 1;
d->m_pIn_buf = NULL;
d->m_pOut_buf = NULL;
d->m_pIn_buf_size = NULL;
d->m_pOut_buf_size = NULL;
d->m_flush = TDEFL_NO_FLUSH;
d->m_pSrc = NULL;
d->m_src_buf_left = 0;
d->m_out_buf_ofs = 0;
memset(&d->m_huff_count[0][0], 0,
sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0,
sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
return TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
return d->m_prev_return_status;
}
mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
tdefl_compressor *pComp;
mz_bool succeeded;
if (((buf_len) && (!pBuf)) || (!pPut_buf_func))
return MZ_FALSE;
pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
if (!pComp)
return MZ_FALSE;
succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
TDEFL_STATUS_OKAY);
succeeded =
succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
TDEFL_STATUS_DONE);
MZ_FREE(pComp);
return succeeded;
}
typedef struct {
size_t m_size, m_capacity;
mz_uint8 *m_pBuf;
mz_bool m_expandable;
} tdefl_output_buffer;
static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
void *pUser) {
tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
size_t new_size = p->m_size + len;
if (new_size > p->m_capacity) {
size_t new_capacity = p->m_capacity;
mz_uint8 *pNew_buf;
if (!p->m_expandable)
return MZ_FALSE;
do {
new_capacity = MZ_MAX(128U, new_capacity << 1U);
} while (new_size > new_capacity);
pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
if (!pNew_buf)
return MZ_FALSE;
p->m_pBuf = pNew_buf;
p->m_capacity = new_capacity;
}
memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
p->m_size = new_size;
return MZ_TRUE;
}
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags) {
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_len)
return MZ_FALSE;
else
*pOut_len = 0;
out_buf.m_expandable = MZ_TRUE;
if (!tdefl_compress_mem_to_output(
pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
return NULL;
*pOut_len = out_buf.m_size;
return out_buf.m_pBuf;
}
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags) {
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_buf)
return 0;
out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
out_buf.m_capacity = out_buf_len;
if (!tdefl_compress_mem_to_output(
pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
return 0;
return out_buf.m_size;
}
#ifndef MINIZ_NO_ZLIB_APIS
static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
128, 256, 512, 768, 1500};
// level may actually range from [0,10] (10 is a "hidden" max level, where we
// want a bit more compression and it's fine if throughput to fall off a cliff
// on some files).
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy) {
mz_uint comp_flags =
s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
if (window_bits > 0)
comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
if (!level)
comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
else if (strategy == MZ_FILTERED)
comp_flags |= TDEFL_FILTER_MATCHES;
else if (strategy == MZ_HUFFMAN_ONLY)
comp_flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == MZ_FIXED)
comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
else if (strategy == MZ_RLE)
comp_flags |= TDEFL_RLE_MATCHES;
return comp_flags;
}
#endif // MINIZ_NO_ZLIB_APIS
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4204) // nonstandard extension used : non-constant
// aggregate initializer (also supported by GNU
// C and C99, so no big deal)
#pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
// 'int', possible loss of data
#pragma warning(disable : 4267) // 'argument': conversion from '__int64' to 'int',
// possible loss of data
#pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
// deprecated. Instead, use the ISO C and C++
// conformant name: _strdup.
#endif
// Simple PNG writer function by Alex Evans, 2011. Released into the public
// domain: https://gist.github.com/908299, more context at
// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
// This is actually a modification of Alex's original code so PNG files
// generated by this function pass pngcheck.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip) {
// Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
// defined.
static const mz_uint s_tdefl_png_num_probes[11] = {
0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
tdefl_compressor *pComp =
(tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
tdefl_output_buffer out_buf;
int i, bpl = w * num_chans, y, z;
mz_uint32 c;
*pLen_out = 0;
if (!pComp)
return NULL;
MZ_CLEAR_OBJ(out_buf);
out_buf.m_expandable = MZ_TRUE;
out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
MZ_FREE(pComp);
return NULL;
}
// write dummy header
for (z = 41; z; --z)
tdefl_output_buffer_putter(&z, 1, &out_buf);
// compress image data
tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf,
s_tdefl_png_num_probes[MZ_MIN(10, level)] |
TDEFL_WRITE_ZLIB_HEADER);
for (y = 0; y < h; ++y) {
tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
tdefl_compress_buffer(pComp,
(mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
bpl, TDEFL_NO_FLUSH);
}
if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
TDEFL_STATUS_DONE) {
MZ_FREE(pComp);
MZ_FREE(out_buf.m_pBuf);
return NULL;
}
// write real header
*pLen_out = out_buf.m_size - 41;
{
static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
mz_uint8 pnghdr[41] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0,
(mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0,
0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16),
(mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41,
0x54};
c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
for (i = 0; i < 4; ++i, c <<= 8)
((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
memcpy(out_buf.m_pBuf, pnghdr, 41);
}
// write footer (IDAT CRC-32, followed by IEND chunk)
if (!tdefl_output_buffer_putter(
"\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
*pLen_out = 0;
MZ_FREE(pComp);
MZ_FREE(out_buf.m_pBuf);
return NULL;
}
c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
*pLen_out + 4);
for (i = 0; i < 4; ++i, c <<= 8)
(out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
// compute final size of file, grab compressed data buffer and return
*pLen_out += 57;
MZ_FREE(pComp);
return out_buf.m_pBuf;
}
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out) {
// Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
// can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
// where #defined out)
return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
pLen_out, 6, MZ_FALSE);
}
// ------------------- .ZIP archive reading
#ifndef MINIZ_NO_ARCHIVE_APIS
#ifdef MINIZ_NO_STDIO
#define MZ_FILE void *
#else
#include <stdio.h>
#include <sys/stat.h>
#if defined(_MSC_VER) || defined(__MINGW64__)
static FILE *mz_fopen(const char *pFilename, const char *pMode) {
FILE *pFile = NULL;
fopen_s(&pFile, pFilename, pMode);
return pFile;
}
static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
FILE *pFile = NULL;
if (freopen_s(&pFile, pPath, pMode, pStream))
return NULL;
return pFile;
}
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN mz_fopen
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 _ftelli64
#define MZ_FSEEK64 _fseeki64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN mz_freopen
#define MZ_DELETE_FILE remove
#elif defined(__MINGW32__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__TINYC__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftell
#define MZ_FSEEK64 fseek
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen64(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT stat64
#define MZ_FILE_STAT stat64
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
#define MZ_DELETE_FILE remove
#else
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello
#define MZ_FSEEK64 fseeko
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#endif // #ifdef _MSC_VER
#endif // #ifdef MINIZ_NO_STDIO
#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
// Various ZIP archive enums. To completely avoid cross platform compiler
// alignment and platform endian issues, miniz.c doesn't use structs for any of
// this stuff.
enum {
// ZIP archive identifiers and record sizes
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
// Central directory header record offsets
MZ_ZIP_CDH_SIG_OFS = 0,
MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
MZ_ZIP_CDH_METHOD_OFS = 10,
MZ_ZIP_CDH_FILE_TIME_OFS = 12,
MZ_ZIP_CDH_FILE_DATE_OFS = 14,
MZ_ZIP_CDH_CRC32_OFS = 16,
MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
MZ_ZIP_CDH_DISK_START_OFS = 34,
MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
// Local directory header offsets
MZ_ZIP_LDH_SIG_OFS = 0,
MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
MZ_ZIP_LDH_METHOD_OFS = 8,
MZ_ZIP_LDH_FILE_TIME_OFS = 10,
MZ_ZIP_LDH_FILE_DATE_OFS = 12,
MZ_ZIP_LDH_CRC32_OFS = 14,
MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
// End of central directory offsets
MZ_ZIP_ECDH_SIG_OFS = 0,
MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
};
typedef struct {
void *m_p;
size_t m_size, m_capacity;
mz_uint m_element_size;
} mz_zip_array;
struct mz_zip_internal_state_tag {
mz_zip_array m_central_dir;
mz_zip_array m_central_dir_offsets;
mz_zip_array m_sorted_central_dir_offsets;
MZ_FILE *m_pFile;
void *m_pMem;
size_t m_mem_size;
size_t m_mem_capacity;
};
#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
(array_ptr)->m_element_size = element_size
#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
((element_type *)((array_ptr)->m_p))[index]
static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
mz_zip_array *pArray) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
memset(pArray, 0, sizeof(mz_zip_array));
}
static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
mz_zip_array *pArray,
size_t min_new_capacity,
mz_uint growing) {
void *pNew_p;
size_t new_capacity = min_new_capacity;
MZ_ASSERT(pArray->m_element_size);
if (pArray->m_capacity >= min_new_capacity)
return MZ_TRUE;
if (growing) {
new_capacity = MZ_MAX(1, pArray->m_capacity);
while (new_capacity < min_new_capacity)
new_capacity *= 2;
}
if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
pArray->m_element_size, new_capacity)))
return MZ_FALSE;
pArray->m_p = pNew_p;
pArray->m_capacity = new_capacity;
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray,
size_t new_capacity, mz_uint growing) {
if (new_capacity > pArray->m_capacity) {
if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
return MZ_FALSE;
}
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size,
mz_uint growing) {
if (new_size > pArray->m_capacity) {
if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
return MZ_FALSE;
}
pArray->m_size = new_size;
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) {
return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray,
const void *pElements, size_t n) {
size_t orig_size = pArray->m_size;
if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
return MZ_FALSE;
memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
pElements, n * pArray->m_element_size);
return MZ_TRUE;
}
#ifndef MINIZ_NO_TIME
static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_isdst = -1;
tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
tm.tm_mon = ((dos_date >> 5) & 15) - 1;
tm.tm_mday = dos_date & 31;
tm.tm_hour = (dos_time >> 11) & 31;
tm.tm_min = (dos_time >> 5) & 63;
tm.tm_sec = (dos_time << 1) & 62;
return mktime(&tm);
}
static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
mz_uint16 *pDOS_date) {
#ifdef _MSC_VER
struct tm tm_struct;
struct tm *tm = &tm_struct;
errno_t err = localtime_s(tm, &time);
if (err) {
*pDOS_date = 0;
*pDOS_time = 0;
return;
}
#else
struct tm *tm = localtime(&time);
#endif
*pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
((tm->tm_sec) >> 1));
*pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
((tm->tm_mon + 1) << 5) + tm->tm_mday);
}
#endif
#ifndef MINIZ_NO_STDIO
static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
mz_uint16 *pDOS_time,
mz_uint16 *pDOS_date) {
#ifdef MINIZ_NO_TIME
(void)pFilename;
*pDOS_date = *pDOS_time = 0;
#else
struct MZ_FILE_STAT_STRUCT file_stat;
// On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
// bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
return MZ_FALSE;
mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
#endif // #ifdef MINIZ_NO_TIME
return MZ_TRUE;
}
#ifndef MINIZ_NO_TIME
static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
time_t modified_time) {
struct utimbuf t;
t.actime = access_time;
t.modtime = modified_time;
return !utime(pFilename, &t);
}
#endif // #ifndef MINIZ_NO_TIME
#endif // #ifndef MINIZ_NO_STDIO
static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
mz_uint32 flags) {
(void)flags;
if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
return MZ_FALSE;
if (!pZip->m_pAlloc)
pZip->m_pAlloc = def_alloc_func;
if (!pZip->m_pFree)
pZip->m_pFree = def_free_func;
if (!pZip->m_pRealloc)
pZip->m_pRealloc = def_realloc_func;
pZip->m_zip_mode = MZ_ZIP_MODE_READING;
pZip->m_archive_size = 0;
pZip->m_central_directory_file_ofs = 0;
pZip->m_total_files = 0;
if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
return MZ_FALSE;
memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
sizeof(mz_uint8));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
sizeof(mz_uint32));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
sizeof(mz_uint32));
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
const mz_zip_array *pCentral_dir_offsets,
mz_uint l_index, mz_uint r_index) {
const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
l_index)),
*pE;
const mz_uint8 *pR =
&MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
mz_uint8 l = 0, r = 0;
pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pE = pL + MZ_MIN(l_len, r_len);
while (pL < pE) {
if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
break;
pL++;
pR++;
}
return (pL == pE) ? (l_len < r_len) : (l < r);
}
#define MZ_SWAP_UINT32(a, b) \
do { \
mz_uint32 t = a; \
a = b; \
b = t; \
} \
MZ_MACRO_END
// Heap sort of lowercased filenames, used to help accelerate plain central
// directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
// but it could allocate memory.)
static void
mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) {
mz_zip_internal_state *pState = pZip->m_pState;
const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
const mz_zip_array *pCentral_dir = &pState->m_central_dir;
mz_uint32 *pIndices =
&MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32,
0);
const int size = pZip->m_total_files;
int start = (size - 2) >> 1, end;
while (start >= 0) {
int child, root = start;
for (;;) {
if ((child = (root << 1) + 1) >= size)
break;
child +=
(((child + 1) < size) &&
(mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[child], pIndices[child + 1])));
if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[root], pIndices[child]))
break;
MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
root = child;
}
start--;
}
end = size - 1;
while (end > 0) {
int child, root = 0;
MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
for (;;) {
if ((child = (root << 1) + 1) >= end)
break;
child +=
(((child + 1) < end) &&
mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[child], pIndices[child + 1]));
if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[root], pIndices[child]))
break;
MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
root = child;
}
end--;
}
}
static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
mz_uint32 flags) {
mz_uint cdir_size, num_this_disk, cdir_disk_index;
mz_uint64 cdir_ofs;
mz_int64 cur_file_ofs;
const mz_uint8 *p;
mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
mz_bool sort_central_dir =
((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
// Basic sanity checks - reject files which are too small, and check the first
// 4 bytes of the file to make sure a local header is there.
if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
// Find the end of central directory record by scanning the file from the end
// towards the beginning.
cur_file_ofs =
MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
for (;;) {
int i,
n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
return MZ_FALSE;
for (i = n - 4; i >= 0; --i)
if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
break;
if (i >= 0) {
cur_file_ofs += i;
break;
}
if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
(0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
return MZ_FALSE;
cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
}
// Read and verify the end of central directory record.
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
((pZip->m_total_files =
MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
return MZ_FALSE;
num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
if (((num_this_disk | cdir_disk_index) != 0) &&
((num_this_disk != 1) || (cdir_disk_index != 1)))
return MZ_FALSE;
if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
return MZ_FALSE;
pZip->m_central_directory_file_ofs = cdir_ofs;
if (pZip->m_total_files) {
mz_uint i, n;
// Read the entire central directory into a heap block, and allocate another
// heap block to hold the unsorted central dir file record offsets, and
// another to hold the sorted indices.
if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
MZ_FALSE)) ||
(!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
pZip->m_total_files, MZ_FALSE)))
return MZ_FALSE;
if (sort_central_dir) {
if (!mz_zip_array_resize(pZip,
&pZip->m_pState->m_sorted_central_dir_offsets,
pZip->m_total_files, MZ_FALSE))
return MZ_FALSE;
}
if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
pZip->m_pState->m_central_dir.m_p,
cdir_size) != cdir_size)
return MZ_FALSE;
// Now create an index into the central directory file records, do some
// basic sanity checking on each record, and check for zip64 entries (which
// are not yet supported).
p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
mz_uint total_header_size, comp_size, decomp_size, disk_index;
if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
(MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
return MZ_FALSE;
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
i) =
(mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
if (sort_central_dir)
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
mz_uint32, i) = i;
comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
(decomp_size != comp_size)) ||
(decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
(comp_size == 0xFFFFFFFF))
return MZ_FALSE;
disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
if ((disk_index != num_this_disk) && (disk_index != 1))
return MZ_FALSE;
if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
return MZ_FALSE;
if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
n)
return MZ_FALSE;
n -= total_header_size;
p += total_header_size;
}
}
if (sort_central_dir)
mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
return MZ_TRUE;
}
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
mz_uint32 flags) {
if ((!pZip) || (!pZip->m_pRead))
return MZ_FALSE;
if (!mz_zip_reader_init_internal(pZip, flags))
return MZ_FALSE;
pZip->m_archive_size = size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
size_t s = (file_ofs >= pZip->m_archive_size)
? 0
: (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
return s;
}
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint32 flags) {
if (!mz_zip_reader_init_internal(pZip, flags))
return MZ_FALSE;
pZip->m_archive_size = size;
pZip->m_pRead = mz_zip_mem_read_func;
pZip->m_pIO_opaque = pZip;
#ifdef __cplusplus
pZip->m_pState->m_pMem = const_cast<void *>(pMem);
#else
pZip->m_pState->m_pMem = (void *)pMem;
#endif
pZip->m_pState->m_mem_size = size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
if (((mz_int64)file_ofs < 0) ||
(((cur_ofs != (mz_int64)file_ofs)) &&
(MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
return 0;
return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
}
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags) {
mz_uint64 file_size;
MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
if (!pFile)
return MZ_FALSE;
if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
MZ_FCLOSE(pFile);
return MZ_FALSE;
}
file_size = MZ_FTELL64(pFile);
if (!mz_zip_reader_init_internal(pZip, flags)) {
MZ_FCLOSE(pFile);
return MZ_FALSE;
}
pZip->m_pRead = mz_zip_file_read_func;
pZip->m_pIO_opaque = pZip;
pZip->m_pState->m_pFile = pFile;
pZip->m_archive_size = file_size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
return pZip ? pZip->m_total_files : 0;
}
static MZ_FORCEINLINE const mz_uint8 *
mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) {
if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return NULL;
return &MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets,
mz_uint32, file_index));
}
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index) {
mz_uint m_bit_flag;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p)
return MZ_FALSE;
m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
return (m_bit_flag & 1);
}
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index) {
mz_uint filename_len, external_attr;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p)
return MZ_FALSE;
// First see if the filename ends with a '/' character.
filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
if (filename_len) {
if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
return MZ_TRUE;
}
// Bugfix: This code was also checking if the internal attribute was non-zero,
// which wasn't correct.
// Most/all zip writers (hopefully) set DOS file/directory attributes in the
// low 16-bits, so check for the DOS directory flag and ignore the source OS
// ID in the created by field.
// FIXME: Remove this check? Is it necessary - we already check the filename.
external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
if ((external_attr & 0x10) != 0)
return MZ_TRUE;
return MZ_FALSE;
}
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat) {
mz_uint n;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if ((!p) || (!pStat))
return MZ_FALSE;
// Unpack the central directory record.
pStat->m_file_index = file_index;
pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
#ifndef MINIZ_NO_TIME
pStat->m_time =
mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
#endif
pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
// Copy as much of the filename and comment as possible.
n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
pStat->m_filename[n] = '\0';
n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
pStat->m_comment_size = n;
memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
n);
pStat->m_comment[n] = '\0';
return MZ_TRUE;
}
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size) {
mz_uint n;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p) {
if (filename_buf_size)
pFilename[0] = '\0';
return 0;
}
n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
if (filename_buf_size) {
n = MZ_MIN(n, filename_buf_size - 1);
memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
pFilename[n] = '\0';
}
return n + 1;
}
static MZ_FORCEINLINE mz_bool
mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len,
mz_uint flags) {
mz_uint i;
if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
return 0 == memcmp(pA, pB, len);
for (i = 0; i < len; ++i)
if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
return MZ_FALSE;
return MZ_TRUE;
}
static MZ_FORCEINLINE int
mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array,
const mz_zip_array *pCentral_dir_offsets,
mz_uint l_index, const char *pR, mz_uint r_len) {
const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
l_index)),
*pE;
mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
mz_uint8 l = 0, r = 0;
pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pE = pL + MZ_MIN(l_len, r_len);
while (pL < pE) {
if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
break;
pL++;
pR++;
}
return (pL == pE) ? (int)(l_len - r_len) : (l - r);
}
static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
const char *pFilename) {
mz_zip_internal_state *pState = pZip->m_pState;
const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
const mz_zip_array *pCentral_dir = &pState->m_central_dir;
mz_uint32 *pIndices =
&MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32,
0);
const int size = pZip->m_total_files;
const mz_uint filename_len = (mz_uint)strlen(pFilename);
int l = 0, h = size - 1;
while (l <= h) {
int m = (l + h) >> 1, file_index = pIndices[m],
comp =
mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
file_index, pFilename, filename_len);
if (!comp)
return file_index;
else if (comp < 0)
l = m + 1;
else
h = m - 1;
}
return -1;
}
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags) {
mz_uint file_index;
size_t name_len, comment_len;
if ((!pZip) || (!pZip->m_pState) || (!pName) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return -1;
if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
(!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
return mz_zip_reader_locate_file_binary_search(pZip, pName);
name_len = strlen(pName);
if (name_len > 0xFFFF)
return -1;
comment_len = pComment ? strlen(pComment) : 0;
if (comment_len > 0xFFFF)
return -1;
for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
const mz_uint8 *pHeader =
&MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets,
mz_uint32, file_index));
mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
const char *pFilename =
(const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
if (filename_len < name_len)
continue;
if (comment_len) {
mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
file_comment_len =
MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
const char *pFile_comment = pFilename + filename_len + file_extra_len;
if ((file_comment_len != comment_len) ||
(!mz_zip_reader_string_equal(pComment, pFile_comment,
file_comment_len, flags)))
continue;
}
if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
int ofs = filename_len - 1;
do {
if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
(pFilename[ofs] == ':'))
break;
} while (--ofs >= 0);
ofs++;
pFilename += ofs;
filename_len -= ofs;
}
if ((filename_len == name_len) &&
(mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
return file_index;
}
return -1;
}
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size) {
int status = TINFL_STATUS_DONE;
mz_uint64 needed_size, cur_file_ofs, comp_remaining,
out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
mz_zip_archive_file_stat file_stat;
void *pRead_buf;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
tinfl_decompressor inflator;
if ((buf_size) && (!pBuf))
return MZ_FALSE;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
return MZ_FALSE;
// Empty file, or a directory (but not always a directory - I've seen odd zips
// with directories that have compressed data which inflates to 0 bytes)
if (!file_stat.m_comp_size)
return MZ_TRUE;
// Entry is a subdirectory (I've seen old zips with dir entries which have
// compressed deflate data which inflates to 0 bytes, but these entries claim
// to uncompress to 512 bytes in the headers).
// I'm torn how to handle this case - should it fail instead?
if (mz_zip_reader_is_file_a_directory(pZip, file_index))
return MZ_TRUE;
// Encryption and patch files are not supported.
if (file_stat.m_bit_flag & (1 | 32))
return MZ_FALSE;
// This function only supports stored and deflate.
if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
(file_stat.m_method != MZ_DEFLATED))
return MZ_FALSE;
// Ensure supplied output buffer is large enough.
needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
: file_stat.m_uncomp_size;
if (buf_size < needed_size)
return MZ_FALSE;
// Read and parse the local directory entry.
cur_file_ofs = file_stat.m_local_header_ofs;
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
return MZ_FALSE;
if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
// The file is stored or the caller has requested the compressed data.
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
(size_t)needed_size) != needed_size)
return MZ_FALSE;
return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
(size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
}
// Decompress the file either directly from memory or from a file input
// buffer.
tinfl_init(&inflator);
if (pZip->m_pState->m_pMem) {
// Read directly from the archive in memory.
pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
read_buf_size = read_buf_avail = file_stat.m_comp_size;
comp_remaining = 0;
} else if (pUser_read_buf) {
// Use a user provided read buffer.
if (!user_read_buf_size)
return MZ_FALSE;
pRead_buf = (mz_uint8 *)pUser_read_buf;
read_buf_size = user_read_buf_size;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
} else {
// Temporarily allocate a read buffer.
read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
(read_buf_size > 0x7FFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
#endif
return MZ_FALSE;
if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)read_buf_size)))
return MZ_FALSE;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
}
do {
size_t in_buf_size,
out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
read_buf_ofs = 0;
}
in_buf_size = (size_t)read_buf_avail;
status = tinfl_decompress(
&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
(mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
(comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
read_buf_avail -= in_buf_size;
read_buf_ofs += in_buf_size;
out_buf_ofs += out_buf_size;
} while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
if (status == TINFL_STATUS_DONE) {
// Make sure the entire file was decompressed, and check its CRC.
if ((out_buf_ofs != file_stat.m_uncomp_size) ||
(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
(size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
status = TINFL_STATUS_FAILED;
}
if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
return status == TINFL_STATUS_DONE;
}
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0)
return MZ_FALSE;
return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
flags, pUser_read_buf,
user_read_buf_size);
}
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags) {
return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
flags, NULL, 0);
}
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags) {
return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
buf_size, flags, NULL, 0);
}
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags) {
mz_uint64 comp_size, uncomp_size, alloc_size;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
void *pBuf;
if (pSize)
*pSize = 0;
if (!p)
return NULL;
comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
#endif
return NULL;
if (NULL ==
(pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
return NULL;
if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
flags)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return NULL;
}
if (pSize)
*pSize = (size_t)alloc_size;
return pBuf;
}
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0) {
if (pSize)
*pSize = 0;
return MZ_FALSE;
}
return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
}
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags) {
int status = TINFL_STATUS_DONE;
mz_uint file_crc32 = MZ_CRC32_INIT;
mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
out_buf_ofs = 0, cur_file_ofs;
mz_zip_archive_file_stat file_stat;
void *pRead_buf = NULL;
void *pWrite_buf = NULL;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
return MZ_FALSE;
// Empty file, or a directory (but not always a directory - I've seen odd zips
// with directories that have compressed data which inflates to 0 bytes)
if (!file_stat.m_comp_size)
return MZ_TRUE;
// Entry is a subdirectory (I've seen old zips with dir entries which have
// compressed deflate data which inflates to 0 bytes, but these entries claim
// to uncompress to 512 bytes in the headers).
// I'm torn how to handle this case - should it fail instead?
if (mz_zip_reader_is_file_a_directory(pZip, file_index))
return MZ_TRUE;
// Encryption and patch files are not supported.
if (file_stat.m_bit_flag & (1 | 32))
return MZ_FALSE;
// This function only supports stored and deflate.
if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
(file_stat.m_method != MZ_DEFLATED))
return MZ_FALSE;
// Read and parse the local directory entry.
cur_file_ofs = file_stat.m_local_header_ofs;
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
return MZ_FALSE;
// Decompress the file either directly from memory or from a file input
// buffer.
if (pZip->m_pState->m_pMem) {
pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
read_buf_size = read_buf_avail = file_stat.m_comp_size;
comp_remaining = 0;
} else {
read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)read_buf_size)))
return MZ_FALSE;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
}
if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
// The file is stored or the caller has requested the compressed data.
if (pZip->m_pState->m_pMem) {
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
(file_stat.m_comp_size > 0xFFFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) &&
(file_stat.m_comp_size > 0xFFFFFFFF))
#endif
return MZ_FALSE;
if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
(size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
status = TINFL_STATUS_FAILED;
else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
file_crc32 =
(mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
(size_t)file_stat.m_comp_size);
cur_file_ofs += file_stat.m_comp_size;
out_buf_ofs += file_stat.m_comp_size;
comp_remaining = 0;
} else {
while (comp_remaining) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
file_crc32 = (mz_uint32)mz_crc32(
file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
out_buf_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
}
}
} else {
tinfl_decompressor inflator;
tinfl_init(&inflator);
if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
TINFL_LZ_DICT_SIZE)))
status = TINFL_STATUS_FAILED;
else {
do {
mz_uint8 *pWrite_buf_cur =
(mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
size_t in_buf_size,
out_buf_size =
TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
read_buf_ofs = 0;
}
in_buf_size = (size_t)read_buf_avail;
status = tinfl_decompress(
&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
(mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
read_buf_avail -= in_buf_size;
read_buf_ofs += in_buf_size;
if (out_buf_size) {
if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
out_buf_size) {
status = TINFL_STATUS_FAILED;
break;
}
file_crc32 =
(mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
status = TINFL_STATUS_FAILED;
break;
}
}
} while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
(status == TINFL_STATUS_HAS_MORE_OUTPUT));
}
}
if ((status == TINFL_STATUS_DONE) &&
(!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
// Make sure the entire file was decompressed, and check its CRC.
if ((out_buf_ofs != file_stat.m_uncomp_size) ||
(file_crc32 != file_stat.m_crc32))
status = TINFL_STATUS_FAILED;
}
if (!pZip->m_pState->m_pMem)
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
if (pWrite_buf)
pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
return status == TINFL_STATUS_DONE;
}
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0)
return MZ_FALSE;
return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
flags);
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
const void *pBuf, size_t n) {
(void)ofs;
return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
}
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename,
mz_uint flags) {
mz_bool status;
mz_zip_archive_file_stat file_stat;
MZ_FILE *pFile;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
return MZ_FALSE;
pFile = MZ_FOPEN(pDst_filename, "wb");
if (!pFile)
return MZ_FALSE;
status = mz_zip_reader_extract_to_callback(
pZip, file_index, mz_zip_file_write_callback, pFile, flags);
if (MZ_FCLOSE(pFile) == EOF)
return MZ_FALSE;
#ifndef MINIZ_NO_TIME
if (status)
mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
#endif
return status;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return MZ_FALSE;
if (pZip->m_pState) {
mz_zip_internal_state *pState = pZip->m_pState;
pZip->m_pState = NULL;
mz_zip_array_clear(pZip, &pState->m_central_dir);
mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
#ifndef MINIZ_NO_STDIO
if (pState->m_pFile) {
MZ_FCLOSE(pState->m_pFile);
pState->m_pFile = NULL;
}
#endif // #ifndef MINIZ_NO_STDIO
pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
}
pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags) {
int file_index =
mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
if (file_index < 0)
return MZ_FALSE;
return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
}
#endif
// ------------------- .ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
p[0] = (mz_uint8)v;
p[1] = (mz_uint8)(v >> 8);
}
static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
p[0] = (mz_uint8)v;
p[1] = (mz_uint8)(v >> 8);
p[2] = (mz_uint8)(v >> 16);
p[3] = (mz_uint8)(v >> 24);
}
#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
return MZ_FALSE;
if (pZip->m_file_offset_alignment) {
// Ensure user specified file offset alignment is a power of 2.
if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
return MZ_FALSE;
}
if (!pZip->m_pAlloc)
pZip->m_pAlloc = def_alloc_func;
if (!pZip->m_pFree)
pZip->m_pFree = def_free_func;
if (!pZip->m_pRealloc)
pZip->m_pRealloc = def_realloc_func;
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
pZip->m_archive_size = existing_size;
pZip->m_central_directory_file_ofs = 0;
pZip->m_total_files = 0;
if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
return MZ_FALSE;
memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
sizeof(mz_uint8));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
sizeof(mz_uint32));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
sizeof(mz_uint32));
return MZ_TRUE;
}
static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_zip_internal_state *pState = pZip->m_pState;
mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
#ifdef _MSC_VER
if ((!n) ||
((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
#else
if ((!n) ||
((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
#endif
return 0;
if (new_size > pState->m_mem_capacity) {
void *pNew_block;
size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
while (new_capacity < new_size)
new_capacity *= 2;
if (NULL == (pNew_block = pZip->m_pRealloc(
pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
return 0;
pState->m_pMem = pNew_block;
pState->m_mem_capacity = new_capacity;
}
memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
pState->m_mem_size = (size_t)new_size;
return n;
}
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size) {
pZip->m_pWrite = mz_zip_heap_write_func;
pZip->m_pIO_opaque = pZip;
if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
return MZ_FALSE;
if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
size_to_reserve_at_beginning))) {
if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
pZip->m_pState->m_mem_capacity = initial_allocation_size;
}
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
if (((mz_int64)file_ofs < 0) ||
(((cur_ofs != (mz_int64)file_ofs)) &&
(MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
return 0;
return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
}
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning) {
MZ_FILE *pFile;
pZip->m_pWrite = mz_zip_file_write_func;
pZip->m_pIO_opaque = pZip;
if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
return MZ_FALSE;
if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
pZip->m_pState->m_pFile = pFile;
if (size_to_reserve_at_beginning) {
mz_uint64 cur_ofs = 0;
char buf[4096];
MZ_CLEAR_OBJ(buf);
do {
size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
cur_ofs += n;
size_to_reserve_at_beginning -= n;
} while (size_to_reserve_at_beginning);
}
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename) {
mz_zip_internal_state *pState;
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return MZ_FALSE;
// No sense in trying to write to an archive that's already at the support max
// size
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
return MZ_FALSE;
pState = pZip->m_pState;
if (pState->m_pFile) {
#ifdef MINIZ_NO_STDIO
pFilename;
return MZ_FALSE;
#else
// Archive is being read from stdio - try to reopen as writable.
if (pZip->m_pIO_opaque != pZip)
return MZ_FALSE;
if (!pFilename)
return MZ_FALSE;
pZip->m_pWrite = mz_zip_file_write_func;
if (NULL ==
(pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
// The mz_zip_archive is now in a bogus state because pState->m_pFile is
// NULL, so just close it.
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
#endif // #ifdef MINIZ_NO_STDIO
} else if (pState->m_pMem) {
// Archive lives in a memory block. Assume it's from the heap that we can
// resize using the realloc callback.
if (pZip->m_pIO_opaque != pZip)
return MZ_FALSE;
pState->m_mem_capacity = pState->m_mem_size;
pZip->m_pWrite = mz_zip_heap_write_func;
}
// Archive is being read via a user provided read function - make sure the
// user has specified a write function too.
else if (!pZip->m_pWrite)
return MZ_FALSE;
// Start writing new files at the archive's current central directory
// location.
pZip->m_archive_size = pZip->m_central_directory_file_ofs;
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
pZip->m_central_directory_file_ofs = 0;
return MZ_TRUE;
}
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags) {
return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
level_and_flags, 0, 0);
}
typedef struct {
mz_zip_archive *m_pZip;
mz_uint64 m_cur_archive_file_ofs;
mz_uint64 m_comp_size;
} mz_zip_writer_add_state;
static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
void *pUser) {
mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
pState->m_cur_archive_file_ofs, pBuf,
len) != len)
return MZ_FALSE;
pState->m_cur_archive_file_ofs += len;
pState->m_comp_size += len;
return MZ_TRUE;
}
static mz_bool mz_zip_writer_create_local_dir_header(
mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
mz_uint16 dos_time, mz_uint16 dos_date) {
(void)pZip;
memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
return MZ_TRUE;
}
static mz_bool mz_zip_writer_create_central_dir_header(
mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
(void)pZip;
memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
return MZ_TRUE;
}
static mz_bool mz_zip_writer_add_to_central_dir(
mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
const void *pExtra, mz_uint16 extra_size, const void *pComment,
mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
mz_uint32 ext_attributes) {
mz_zip_internal_state *pState = pZip->m_pState;
mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
size_t orig_central_dir_size = pState->m_central_dir.m_size;
mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
// No zip64 support yet
if ((local_header_ofs > 0xFFFFFFFF) ||
(((mz_uint64)pState->m_central_dir.m_size +
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
comment_size) > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_central_dir_header(
pZip, central_dir_header, filename_size, extra_size, comment_size,
uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
dos_date, local_header_ofs, ext_attributes))
return MZ_FALSE;
if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
filename_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
extra_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
comment_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
¢ral_dir_ofs, 1))) {
// Try to push the central directory array back into its original state.
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
return MZ_TRUE;
}
static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
// Basic ZIP archive filename validity checks: Valid filenames cannot start
// with a forward slash, cannot contain a drive letter, and cannot use
// DOS-style backward slashes.
if (*pArchive_name == '/')
return MZ_FALSE;
while (*pArchive_name) {
if ((*pArchive_name == '\\') || (*pArchive_name == ':'))
return MZ_FALSE;
pArchive_name++;
}
return MZ_TRUE;
}
static mz_uint
mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) {
mz_uint32 n;
if (!pZip->m_file_offset_alignment)
return 0;
n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
return (pZip->m_file_offset_alignment - n) &
(pZip->m_file_offset_alignment - 1);
}
static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
mz_uint64 cur_file_ofs, mz_uint32 n) {
char buf[4096];
memset(buf, 0, MZ_MIN(sizeof(buf), n));
while (n) {
mz_uint32 s = MZ_MIN(sizeof(buf), n);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
return MZ_FALSE;
cur_file_ofs += s;
n -= s;
}
return MZ_TRUE;
}
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32) {
mz_uint16 method = 0, dos_time = 0, dos_date = 0;
mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
size_t archive_name_size;
mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
tdefl_compressor *pComp = NULL;
mz_bool store_data_uncompressed;
mz_zip_internal_state *pState;
if ((int)level_and_flags < 0)
level_and_flags = MZ_DEFAULT_LEVEL;
level = level_and_flags & 0xF;
store_data_uncompressed =
((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
if ((!pZip) || (!pZip->m_pState) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
(!pArchive_name) || ((comment_size) && (!pComment)) ||
(pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
return MZ_FALSE;
pState = pZip->m_pState;
if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
return MZ_FALSE;
// No zip64 support yet
if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name))
return MZ_FALSE;
#ifndef MINIZ_NO_TIME
{
time_t cur_time;
time(&cur_time);
mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
}
#endif // #ifndef MINIZ_NO_TIME
archive_name_size = strlen(pArchive_name);
if (archive_name_size > 0xFFFF)
return MZ_FALSE;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
comment_size + archive_name_size) > 0xFFFFFFFF))
return MZ_FALSE;
if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
// Set DOS Subdirectory attribute bit.
ext_attributes |= 0x10;
// Subdirectories cannot contain data.
if ((buf_size) || (uncomp_size))
return MZ_FALSE;
}
// Try to do any allocations before writing to the archive, so if an
// allocation fails the file remains unmodified. (A good idea if we're doing
// an in-place modification.)
if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
archive_name_size + comment_size)) ||
(!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
return MZ_FALSE;
if ((!store_data_uncompressed) && (buf_size)) {
if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
return MZ_FALSE;
}
if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
num_alignment_padding_bytes +
sizeof(local_dir_header))) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
local_dir_header_ofs += num_alignment_padding_bytes;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
cur_archive_file_ofs +=
num_alignment_padding_bytes + sizeof(local_dir_header);
MZ_CLEAR_OBJ(local_dir_header);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
archive_name_size) != archive_name_size) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
cur_archive_file_ofs += archive_name_size;
if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
uncomp_crc32 =
(mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
uncomp_size = buf_size;
if (uncomp_size <= 3) {
level = 0;
store_data_uncompressed = MZ_TRUE;
}
}
if (store_data_uncompressed) {
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
buf_size) != buf_size) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
cur_archive_file_ofs += buf_size;
comp_size = buf_size;
if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
method = MZ_DEFLATED;
} else if (buf_size) {
mz_zip_writer_add_state state;
state.m_pZip = pZip;
state.m_cur_archive_file_ofs = cur_archive_file_ofs;
state.m_comp_size = 0;
if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
tdefl_create_comp_flags_from_zip_params(
level, -15, MZ_DEFAULT_STRATEGY)) !=
TDEFL_STATUS_OKAY) ||
(tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
TDEFL_STATUS_DONE)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
comp_size = state.m_comp_size;
cur_archive_file_ofs = state.m_cur_archive_file_ofs;
method = MZ_DEFLATED;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
pComp = NULL;
// no zip64 support yet
if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_local_dir_header(
pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
return MZ_FALSE;
if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
sizeof(local_dir_header)) != sizeof(local_dir_header))
return MZ_FALSE;
if (!mz_zip_writer_add_to_central_dir(
pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
dos_time, dos_date, local_dir_header_ofs, ext_attributes))
return MZ_FALSE;
pZip->m_total_files++;
pZip->m_archive_size = cur_archive_file_ofs;
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags) {
mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
comp_size = 0;
size_t archive_name_size;
mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
MZ_FILE *pSrc_file = NULL;
if ((int)level_and_flags < 0)
level_and_flags = MZ_DEFAULT_LEVEL;
level = level_and_flags & 0xF;
if ((!pZip) || (!pZip->m_pState) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
return MZ_FALSE;
if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name))
return MZ_FALSE;
archive_name_size = strlen(pArchive_name);
if (archive_name_size > 0xFFFF)
return MZ_FALSE;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
comment_size + archive_name_size) > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
return MZ_FALSE;
pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
if (!pSrc_file)
return MZ_FALSE;
MZ_FSEEK64(pSrc_file, 0, SEEK_END);
uncomp_size = MZ_FTELL64(pSrc_file);
MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
if (uncomp_size > 0xFFFFFFFF) {
// No zip64 support yet
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
if (uncomp_size <= 3)
level = 0;
if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
num_alignment_padding_bytes +
sizeof(local_dir_header))) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
local_dir_header_ofs += num_alignment_padding_bytes;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
cur_archive_file_ofs +=
num_alignment_padding_bytes + sizeof(local_dir_header);
MZ_CLEAR_OBJ(local_dir_header);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
archive_name_size) != archive_name_size) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
cur_archive_file_ofs += archive_name_size;
if (uncomp_size) {
mz_uint64 uncomp_remaining = uncomp_size;
void *pRead_buf =
pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
if (!pRead_buf) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
if (!level) {
while (uncomp_remaining) {
mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
n) != n)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
uncomp_crc32 =
(mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
uncomp_remaining -= n;
cur_archive_file_ofs += n;
}
comp_size = uncomp_size;
} else {
mz_bool result = MZ_FALSE;
mz_zip_writer_add_state state;
tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
if (!pComp) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
state.m_pZip = pZip;
state.m_cur_archive_file_ofs = cur_archive_file_ofs;
state.m_comp_size = 0;
if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
tdefl_create_comp_flags_from_zip_params(
level, -15, MZ_DEFAULT_STRATEGY)) !=
TDEFL_STATUS_OKAY) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
for (;;) {
size_t in_buf_size =
(mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
tdefl_status status;
if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
break;
uncomp_crc32 = (mz_uint32)mz_crc32(
uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
uncomp_remaining -= in_buf_size;
status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size,
uncomp_remaining ? TDEFL_NO_FLUSH
: TDEFL_FINISH);
if (status == TDEFL_STATUS_DONE) {
result = MZ_TRUE;
break;
} else if (status != TDEFL_STATUS_OKAY)
break;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
if (!result) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
comp_size = state.m_comp_size;
cur_archive_file_ofs = state.m_cur_archive_file_ofs;
method = MZ_DEFLATED;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
}
MZ_FCLOSE(pSrc_file);
pSrc_file = NULL;
// no zip64 support yet
if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_local_dir_header(
pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
return MZ_FALSE;
if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
sizeof(local_dir_header)) != sizeof(local_dir_header))
return MZ_FALSE;
if (!mz_zip_writer_add_to_central_dir(
pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
dos_time, dos_date, local_dir_header_ofs, ext_attributes))
return MZ_FALSE;
pZip->m_total_files++;
pZip->m_archive_size = cur_archive_file_ofs;
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint file_index) {
mz_uint n, bit_flags, num_alignment_padding_bytes;
mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
size_t orig_central_dir_size;
mz_zip_internal_state *pState;
void *pBuf;
const mz_uint8 *pSrc_central_header;
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
return MZ_FALSE;
if (NULL ==
(pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
return MZ_FALSE;
pState = pZip->m_pState;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
0xFFFFFFFF))
return MZ_FALSE;
cur_src_file_ofs =
MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
cur_dst_file_ofs = pZip->m_archive_size;
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
num_alignment_padding_bytes))
return MZ_FALSE;
cur_dst_file_ofs += num_alignment_padding_bytes;
local_dir_header_ofs = cur_dst_file_ofs;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
comp_bytes_remaining =
n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
if (NULL ==
(pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)MZ_MAX(sizeof(mz_uint32) * 4,
MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
comp_bytes_remaining)))))
return MZ_FALSE;
while (comp_bytes_remaining) {
n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_src_file_ofs += n;
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_dst_file_ofs += n;
comp_bytes_remaining -= n;
}
bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
if (bit_flags & 8) {
// Copy data descriptor
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_src_file_ofs += n;
cur_dst_file_ofs += n;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
// no zip64 support yet
if (cur_dst_file_ofs > 0xFFFFFFFF)
return MZ_FALSE;
orig_central_dir_size = pState->m_central_dir.m_size;
memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
local_dir_header_ofs);
if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
return MZ_FALSE;
n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
if (!mz_zip_array_push_back(
pZip, &pState->m_central_dir,
pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
if (pState->m_central_dir.m_size > 0xFFFFFFFF)
return MZ_FALSE;
n = (mz_uint32)orig_central_dir_size;
if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
pZip->m_total_files++;
pZip->m_archive_size = cur_dst_file_ofs;
return MZ_TRUE;
}
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
mz_zip_internal_state *pState;
mz_uint64 central_dir_ofs, central_dir_size;
mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
return MZ_FALSE;
pState = pZip->m_pState;
// no zip64 support yet
if ((pZip->m_total_files > 0xFFFF) ||
((pZip->m_archive_size + pState->m_central_dir.m_size +
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
return MZ_FALSE;
central_dir_ofs = 0;
central_dir_size = 0;
if (pZip->m_total_files) {
// Write central directory
central_dir_ofs = pZip->m_archive_size;
central_dir_size = pState->m_central_dir.m_size;
pZip->m_central_directory_file_ofs = central_dir_ofs;
if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
pState->m_central_dir.m_p,
(size_t)central_dir_size) != central_dir_size)
return MZ_FALSE;
pZip->m_archive_size += central_dir_size;
}
// Write end of central directory record
MZ_CLEAR_OBJ(hdr);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
pZip->m_total_files);
MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
sizeof(hdr)) != sizeof(hdr))
return MZ_FALSE;
#ifndef MINIZ_NO_STDIO
if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
return MZ_FALSE;
#endif // #ifndef MINIZ_NO_STDIO
pZip->m_archive_size += sizeof(hdr);
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
return MZ_TRUE;
}
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
size_t *pSize) {
if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))
return MZ_FALSE;
if (pZip->m_pWrite != mz_zip_heap_write_func)
return MZ_FALSE;
if (!mz_zip_writer_finalize_archive(pZip))
return MZ_FALSE;
*pBuf = pZip->m_pState->m_pMem;
*pSize = pZip->m_pState->m_mem_size;
pZip->m_pState->m_pMem = NULL;
pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
return MZ_TRUE;
}
mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
mz_zip_internal_state *pState;
mz_bool status = MZ_TRUE;
if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
return MZ_FALSE;
pState = pZip->m_pState;
pZip->m_pState = NULL;
mz_zip_array_clear(pZip, &pState->m_central_dir);
mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
#ifndef MINIZ_NO_STDIO
if (pState->m_pFile) {
MZ_FCLOSE(pState->m_pFile);
pState->m_pFile = NULL;
}
#endif // #ifndef MINIZ_NO_STDIO
if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
pState->m_pMem = NULL;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
return status;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags) {
mz_bool status, created_new_archive = MZ_FALSE;
mz_zip_archive zip_archive;
struct MZ_FILE_STAT_STRUCT file_stat;
MZ_CLEAR_OBJ(zip_archive);
if ((int)level_and_flags < 0)
level_and_flags = MZ_DEFAULT_LEVEL;
if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
((comment_size) && (!pComment)) ||
((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name))
return MZ_FALSE;
if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
// Create a new archive.
if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
return MZ_FALSE;
created_new_archive = MZ_TRUE;
} else {
// Append to an existing archive.
if (!mz_zip_reader_init_file(&zip_archive, pZip_filename,
level_and_flags |
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
return MZ_FALSE;
if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
mz_zip_reader_end(&zip_archive);
return MZ_FALSE;
}
}
status =
mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
pComment, comment_size, level_and_flags, 0, 0);
// Always finalize, even if adding failed for some reason, so we have a valid
// central directory. (This may not always succeed, but we can try.)
if (!mz_zip_writer_finalize_archive(&zip_archive))
status = MZ_FALSE;
if (!mz_zip_writer_end(&zip_archive))
status = MZ_FALSE;
if ((!status) && (created_new_archive)) {
// It's a new archive and something went wrong, so just delete it.
int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
(void)ignoredStatus;
}
return status;
}
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint flags) {
int file_index;
mz_zip_archive zip_archive;
void *p = NULL;
if (pSize)
*pSize = 0;
if ((!pZip_filename) || (!pArchive_name))
return NULL;
MZ_CLEAR_OBJ(zip_archive);
if (!mz_zip_reader_init_file(&zip_archive, pZip_filename,
flags |
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
return NULL;
if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
flags)) >= 0)
p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
mz_zip_reader_end(&zip_archive);
return p;
}
#endif // #ifndef MINIZ_NO_STDIO
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_FILE_ONLY
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
// ---------------------- end of miniz ----------------------------------------
}
bool IsBigEndian(void) {
union {
unsigned int i;
char c[4];
} bint = {0x01020304};
return bint.c[0] == 1;
}
void swap2(unsigned short *val) {
unsigned short tmp = *val;
unsigned char *dst = (unsigned char *)val;
unsigned char *src = (unsigned char *)&tmp;
dst[0] = src[1];
dst[1] = src[0];
}
void swap4(unsigned int *val) {
unsigned int tmp = *val;
unsigned char *dst = (unsigned char *)val;
unsigned char *src = (unsigned char *)&tmp;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
}
void swap8(unsigned long long *val) {
unsigned long long tmp = (*val);
unsigned char *dst = (unsigned char *)val;
unsigned char *src = (unsigned char *)&tmp;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
}
// https://gist.github.com/rygorous/2156668
// Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
union FP32 {
unsigned int u;
float f;
struct {
#if MINIZ_LITTLE_ENDIAN
unsigned int Mantissa : 23;
unsigned int Exponent : 8;
unsigned int Sign : 1;
#else
unsigned int Sign : 1;
unsigned int Exponent : 8;
unsigned int Mantissa : 23;
#endif
} s;
};
union FP16 {
unsigned short u;
struct {
#if MINIZ_LITTLE_ENDIAN
unsigned int Mantissa : 10;
unsigned int Exponent : 5;
unsigned int Sign : 1;
#else
unsigned int Sign : 1;
unsigned int Exponent : 5;
unsigned int Mantissa : 10;
#endif
} s;
};
FP32 half_to_float(FP16 h) {
static const FP32 magic = {113 << 23};
static const unsigned int shifted_exp = 0x7c00
<< 13; // exponent mask after shift
FP32 o;
o.u = (h.u & 0x7fff) << 13; // exponent/mantissa bits
unsigned int exp_ = shifted_exp & o.u; // just the exponent
o.u += (127 - 15) << 23; // exponent adjust
// handle exponent special cases
if (exp_ == shifted_exp) // Inf/NaN?
o.u += (128 - 16) << 23; // extra exp adjust
else if (exp_ == 0) // Zero/Denormal?
{
o.u += 1 << 23; // extra exp adjust
o.f -= magic.f; // renormalize
}
o.u |= (h.u & 0x8000) << 16; // sign bit
return o;
}
FP16 float_to_half_full(FP32 f) {
FP16 o = {0};
// Based on ISPC reference code (with minor modifications)
if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
o.s.Exponent = 0;
else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
{
o.s.Exponent = 31;
o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
} else // Normalized number
{
// Exponent unbias the single, then bias the halfp
int newexp = f.s.Exponent - 127 + 15;
if (newexp >= 31) // Overflow, return signed infinity
o.s.Exponent = 31;
else if (newexp <= 0) // Underflow
{
if ((14 - newexp) <= 24) // Mantissa might be non-zero
{
unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
o.s.Mantissa = mant >> (14 - newexp);
if ((mant >> (13 - newexp)) & 1) // Check for rounding
o.u++; // Round, might overflow into exp bit, but this is OK
}
} else {
o.s.Exponent = newexp;
o.s.Mantissa = f.s.Mantissa >> 13;
if (f.s.Mantissa & 0x1000) // Check for rounding
o.u++; // Round, might overflow to inf, this is OK
}
}
o.s.Sign = f.s.Sign;
return o;
}
// NOTE: From OpenEXR code
// #define IMF_INCREASING_Y 0
// #define IMF_DECREASING_Y 1
// #define IMF_RAMDOM_Y 2
//
// #define IMF_NO_COMPRESSION 0
// #define IMF_RLE_COMPRESSION 1
// #define IMF_ZIPS_COMPRESSION 2
// #define IMF_ZIP_COMPRESSION 3
// #define IMF_PIZ_COMPRESSION 4
// #define IMF_PXR24_COMPRESSION 5
// #define IMF_B44_COMPRESSION 6
// #define IMF_B44A_COMPRESSION 7
const char *ReadString(std::string &s, const char *ptr) {
// Read untile NULL(\0).
const char *p = ptr;
const char *q = ptr;
while ((*q) != 0)
q++;
s = std::string(p, q);
return q + 1; // skip '\0'
}
const char *ReadAttribute(std::string &name, std::string &ty,
std::vector<unsigned char> &data, const char *ptr) {
if ((*ptr) == 0) {
// end of attribute.
return NULL;
}
const char *p = ReadString(name, ptr);
p = ReadString(ty, p);
int dataLen;
memcpy(&dataLen, p, sizeof(int));
p += 4;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dataLen));
}
data.resize(dataLen);
memcpy(&data.at(0), p, dataLen);
p += dataLen;
return p;
}
void WriteAttribute(FILE *fp, const char *name, const char *type,
const unsigned char *data, int len) {
size_t n = fwrite(name, 1, strlen(name) + 1, fp);
assert(n == strlen(name) + 1);
n = fwrite(type, 1, strlen(type) + 1, fp);
assert(n == strlen(type) + 1);
int outLen = len;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&outLen));
}
n = fwrite(&outLen, 1, sizeof(int), fp);
assert(n == sizeof(int));
n = fwrite(data, 1, len, fp);
assert(n == (size_t)len);
(void)n;
}
void WriteAttributeToMemory(std::vector<unsigned char> &out, const char *name,
const char *type, const unsigned char *data,
int len) {
out.insert(out.end(), name, name + strlen(name) + 1);
out.insert(out.end(), type, type + strlen(type) + 1);
int outLen = len;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&outLen));
}
out.insert(out.end(), reinterpret_cast<unsigned char *>(&outLen),
reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
out.insert(out.end(), data, data + len);
}
typedef struct {
std::string name; // less than 255 bytes long
int pixelType;
unsigned char pLinear;
int xSampling;
int ySampling;
} ChannelInfo;
void ReadChannelInfo(std::vector<ChannelInfo> &channels,
const std::vector<unsigned char> &data) {
const char *p = reinterpret_cast<const char *>(&data.at(0));
for (;;) {
if ((*p) == 0) {
break;
}
ChannelInfo info;
p = ReadString(info.name, p);
memcpy(&info.pixelType, p, sizeof(int));
p += 4;
info.pLinear = p[0]; // uchar
p += 1 + 3; // reserved: uchar[3]
memcpy(&info.xSampling, p, sizeof(int)); // int
p += 4;
memcpy(&info.ySampling, p, sizeof(int)); // int
p += 4;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&info.pixelType));
swap4(reinterpret_cast<unsigned int *>(&info.xSampling));
swap4(reinterpret_cast<unsigned int *>(&info.ySampling));
}
channels.push_back(info);
}
}
void WriteChannelInfo(std::vector<unsigned char> &data,
const std::vector<ChannelInfo> &channels) {
size_t sz = 0;
// Calculate total size.
for (size_t c = 0; c < channels.size(); c++) {
sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
sz += 16; // 4 * int
}
data.resize(sz + 1);
unsigned char *p = &data.at(0);
for (size_t c = 0; c < channels.size(); c++) {
memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
p += strlen(channels[c].name.c_str());
(*p) = '\0';
p++;
int pixelType = channels[c].pixelType;
int xSampling = channels[c].xSampling;
int ySampling = channels[c].ySampling;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&pixelType));
swap4(reinterpret_cast<unsigned int *>(&xSampling));
swap4(reinterpret_cast<unsigned int *>(&ySampling));
}
memcpy(p, &pixelType, sizeof(int));
p += sizeof(int);
(*p) = channels[c].pLinear;
p += 4;
memcpy(p, &xSampling, sizeof(int));
p += sizeof(int);
memcpy(p, &ySampling, sizeof(int));
p += sizeof(int);
}
(*p) = '\0';
}
void CompressZip(unsigned char *dst, unsigned long long &compressedSize,
const unsigned char *src, unsigned long srcSize) {
std::vector<unsigned char> tmpBuf(srcSize);
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfZipCompressor.cpp
//
//
// Reorder the pixel data.
//
{
char *t1 = (char *)&tmpBuf.at(0);
char *t2 = (char *)&tmpBuf.at(0) + (srcSize + 1) / 2;
const char *stop = (const char *)src + srcSize;
for (;;) {
if ((const char *)src < stop)
*(t1++) = *(src++);
else
break;
if ((const char *)src < stop)
*(t2++) = *(src++);
else
break;
}
}
//
// Predictor.
//
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + srcSize;
int p = t[-1];
while (t < stop) {
int d = int(t[0]) - p + (128 + 256);
p = t[0];
t[0] = d;
++t;
}
}
//
// Compress the data using miniz
//
miniz::mz_ulong outSize = miniz::mz_compressBound(srcSize);
int ret = miniz::mz_compress(dst, &outSize,
(const unsigned char *)&tmpBuf.at(0), srcSize);
assert(ret == miniz::MZ_OK);
(void)ret;
compressedSize = outSize;
}
void DecompressZip(unsigned char *dst, unsigned long &uncompressedSize,
const unsigned char *src, unsigned long srcSize) {
std::vector<unsigned char> tmpBuf(uncompressedSize);
int ret =
miniz::mz_uncompress(&tmpBuf.at(0), &uncompressedSize, src, srcSize);
assert(ret == miniz::MZ_OK);
(void)ret;
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfZipCompressor.cpp
//
// Predictor.
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + uncompressedSize;
while (t < stop) {
int d = int(t[-1]) + int(t[0]) - 128;
t[0] = d;
++t;
}
}
// Reorder the pixel data.
{
const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
(uncompressedSize + 1) / 2;
char *s = reinterpret_cast<char *>(dst);
char *stop = s + uncompressedSize;
for(;;) {
if (s < stop)
*(s++) = *(t1++);
else
break;
if (s < stop)
*(s++) = *(t2++);
else
break;
}
}
}
//
// PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
//
// -----------------------------------------------------------------
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC)
// (3 clause BSD license)
//
struct PIZChannelData {
unsigned short *start;
unsigned short *end;
int nx;
int ny;
int ys;
int size;
};
//-----------------------------------------------------------------------------
//
// 16-bit Haar Wavelet encoding and decoding
//
// The source code in this file is derived from the encoding
// and decoding routines written by Christian Rouet for his
// PIZ image file format.
//
//-----------------------------------------------------------------------------
//
// Wavelet basis functions without modulo arithmetic; they produce
// the best compression ratios when the wavelet-transformed data are
// Huffman-encoded, but the wavelet transform works only for 14-bit
// data (untransformed data values must be less than (1 << 14)).
//
inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
unsigned short &h) {
short as = a;
short bs = b;
short ms = (as + bs) >> 1;
short ds = as - bs;
l = ms;
h = ds;
}
inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
unsigned short &b) {
short ls = l;
short hs = h;
int hi = hs;
int ai = ls + (hi & 1) + (hi >> 1);
short as = ai;
short bs = ai - hi;
a = as;
b = bs;
}
//
// Wavelet basis functions with modulo arithmetic; they work with full
// 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
// compress the data quite as well.
//
const int NBITS = 16;
const int A_OFFSET = 1 << (NBITS - 1);
const int M_OFFSET = 1 << (NBITS - 1);
const int MOD_MASK = (1 << NBITS) - 1;
inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
unsigned short &h) {
int ao = (a + A_OFFSET) & MOD_MASK;
int m = ((ao + b) >> 1);
int d = ao - b;
if (d < 0)
m = (m + M_OFFSET) & MOD_MASK;
d &= MOD_MASK;
l = m;
h = d;
}
inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
unsigned short &b) {
int m = l;
int d = h;
int bb = (m - (d >> 1)) & MOD_MASK;
int aa = (d + bb - A_OFFSET) & MOD_MASK;
b = bb;
a = aa;
}
//
// 2D Wavelet encoding:
//
void wav2Encode(unsigned short *in, // io: values are transformed in place
int nx, // i : x size
int ox, // i : x offset
int ny, // i : y size
int oy, // i : y offset
unsigned short mx) // i : maximum in[x][y] value
{
bool w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1; // == 1 << level
int p2 = 2; // == 1 << (level+1)
//
// Hierachical loop on smaller dimension n
//
while (p2 <= n) {
unsigned short *py = in;
unsigned short *ey = in + oy * (ny - p2);
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
unsigned short i00, i01, i10, i11;
//
// Y loop
//
for (; py <= ey; py += oy2) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
//
// X loop
//
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
unsigned short *p10 = px + oy1;
unsigned short *p11 = p10 + ox1;
//
// 2D wavelet encoding
//
if (w14) {
wenc14(*px, *p01, i00, i01);
wenc14(*p10, *p11, i10, i11);
wenc14(i00, i10, *px, *p10);
wenc14(i01, i11, *p01, *p11);
} else {
wenc16(*px, *p01, i00, i01);
wenc16(*p10, *p11, i10, i11);
wenc16(i00, i10, *px, *p10);
wenc16(i01, i11, *p01, *p11);
}
}
//
// Encode (1D) odd column (still in Y loop)
//
if (nx & p) {
unsigned short *p10 = px + oy1;
if (w14)
wenc14(*px, *p10, i00, *p10);
else
wenc16(*px, *p10, i00, *p10);
*px = i00;
}
}
//
// Encode (1D) odd line (must loop in X)
//
if (ny & p) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
if (w14)
wenc14(*px, *p01, i00, *p01);
else
wenc16(*px, *p01, i00, *p01);
*px = i00;
}
}
//
// Next level
//
p = p2;
p2 <<= 1;
}
}
//
// 2D Wavelet decoding:
//
void wav2Decode(unsigned short *in, // io: values are transformed in place
int nx, // i : x size
int ox, // i : x offset
int ny, // i : y size
int oy, // i : y offset
unsigned short mx) // i : maximum in[x][y] value
{
bool w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1;
int p2;
//
// Search max level
//
while (p <= n)
p <<= 1;
p >>= 1;
p2 = p;
p >>= 1;
//
// Hierarchical loop on smaller dimension n
//
while (p >= 1) {
unsigned short *py = in;
unsigned short *ey = in + oy * (ny - p2);
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
unsigned short i00, i01, i10, i11;
//
// Y loop
//
for (; py <= ey; py += oy2) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
//
// X loop
//
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
unsigned short *p10 = px + oy1;
unsigned short *p11 = p10 + ox1;
//
// 2D wavelet decoding
//
if (w14) {
wdec14(*px, *p10, i00, i10);
wdec14(*p01, *p11, i01, i11);
wdec14(i00, i01, *px, *p01);
wdec14(i10, i11, *p10, *p11);
} else {
wdec16(*px, *p10, i00, i10);
wdec16(*p01, *p11, i01, i11);
wdec16(i00, i01, *px, *p01);
wdec16(i10, i11, *p10, *p11);
}
}
//
// Decode (1D) odd column (still in Y loop)
//
if (nx & p) {
unsigned short *p10 = px + oy1;
if (w14)
wdec14(*px, *p10, i00, *p10);
else
wdec16(*px, *p10, i00, *p10);
*px = i00;
}
}
//
// Decode (1D) odd line (must loop in X)
//
if (ny & p) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
if (w14)
wdec14(*px, *p01, i00, *p01);
else
wdec16(*px, *p01, i00, *p01);
*px = i00;
}
}
//
// Next level
//
p2 = p;
p >>= 1;
}
}
//-----------------------------------------------------------------------------
//
// 16-bit Huffman compression and decompression.
//
// The source code in this file is derived from the 8-bit
// Huffman compression and decompression routines written
// by Christian Rouet for his PIZ image file format.
//
//-----------------------------------------------------------------------------
// Adds some modification for tinyexr.
const int HUF_ENCBITS = 16; // literal (value) bit length
const int HUF_DECBITS = 14; // decoding bit size (>= 8)
const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
const int HUF_DECMASK = HUF_DECSIZE - 1;
struct HufDec { // short code long code
//-------------------------------
int len : 8; // code length 0
int lit : 24; // lit p size
int *p; // 0 lits
};
inline long long hufLength(long long code) { return code & 63; }
inline long long hufCode(long long code) { return code >> 6; }
inline void outputBits(int nBits, long long bits, long long &c, int &lc,
char *&out) {
c <<= nBits;
lc += nBits;
c |= bits;
while (lc >= 8)
*out++ = (c >> (lc -= 8));
}
inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
while (lc < nBits) {
c = (c << 8) | *(unsigned char *)(in++);
lc += 8;
}
lc -= nBits;
return (c >> lc) & ((1 << nBits) - 1);
}
//
// ENCODING TABLE BUILDING & (UN)PACKING
//
//
// Build a "canonical" Huffman code table:
// - for each (uncompressed) symbol, hcode contains the length
// of the corresponding code (in the compressed data)
// - canonical codes are computed and stored in hcode
// - the rules for constructing canonical codes are as follows:
// * shorter codes (if filled with zeroes to the right)
// have a numerically higher value than longer codes
// * for codes with the same length, numerical values
// increase with numerical symbol values
// - because the canonical code table can be constructed from
// symbol lengths alone, the code table can be transmitted
// without sending the actual code values
// - see http://www.compressconsult.com/huffman/
//
void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
long long n[59];
//
// For each i from 0 through 58, count the
// number of different codes of length i, and
// store the count in n[i].
//
for (int i = 0; i <= 58; ++i)
n[i] = 0;
for (int i = 0; i < HUF_ENCSIZE; ++i)
n[hcode[i]] += 1;
//
// For each i from 58 through 1, compute the
// numerically lowest code with length i, and
// store that code in n[i].
//
long long c = 0;
for (int i = 58; i > 0; --i) {
long long nc = ((c + n[i]) >> 1);
n[i] = c;
c = nc;
}
//
// hcode[i] contains the length, l, of the
// code for symbol i. Assign the next available
// code of length l to the symbol and store both
// l and the code in hcode[i].
//
for (int i = 0; i < HUF_ENCSIZE; ++i) {
int l = hcode[i];
if (l > 0)
hcode[i] = l | (n[l]++ << 6);
}
}
//
// Compute Huffman codes (based on frq input) and store them in frq:
// - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
// - max code length is 58 bits;
// - codes outside the range [im-iM] have a null length (unused values);
// - original frequencies are destroyed;
// - encoding tables are used by hufEncode() and hufBuildDecTable();
//
struct FHeapCompare {
bool operator()(long long *a, long long *b) { return *a > *b; }
};
void hufBuildEncTable(
long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
int *im, // o: min frq index
int *iM) // o: max frq index
{
//
// This function assumes that when it is called, array frq
// indicates the frequency of all possible symbols in the data
// that are to be Huffman-encoded. (frq[i] contains the number
// of occurrences of symbol i in the data.)
//
// The loop below does three things:
//
// 1) Finds the minimum and maximum indices that point
// to non-zero entries in frq:
//
// frq[im] != 0, and frq[i] == 0 for all i < im
// frq[iM] != 0, and frq[i] == 0 for all i > iM
//
// 2) Fills array fHeap with pointers to all non-zero
// entries in frq.
//
// 3) Initializes array hlink such that hlink[i] == i
// for all array entries.
//
int hlink[HUF_ENCSIZE];
long long *fHeap[HUF_ENCSIZE];
*im = 0;
while (!frq[*im])
(*im)++;
int nf = 0;
for (int i = *im; i < HUF_ENCSIZE; i++) {
hlink[i] = i;
if (frq[i]) {
fHeap[nf] = &frq[i];
nf++;
*iM = i;
}
}
//
// Add a pseudo-symbol, with a frequency count of 1, to frq;
// adjust the fHeap and hlink array accordingly. Function
// hufEncode() uses the pseudo-symbol for run-length encoding.
//
(*iM)++;
frq[*iM] = 1;
fHeap[nf] = &frq[*iM];
nf++;
//
// Build an array, scode, such that scode[i] contains the number
// of bits assigned to symbol i. Conceptually this is done by
// constructing a tree whose leaves are the symbols with non-zero
// frequency:
//
// Make a heap that contains all symbols with a non-zero frequency,
// with the least frequent symbol on top.
//
// Repeat until only one symbol is left on the heap:
//
// Take the two least frequent symbols off the top of the heap.
// Create a new node that has first two nodes as children, and
// whose frequency is the sum of the frequencies of the first
// two nodes. Put the new node back into the heap.
//
// The last node left on the heap is the root of the tree. For each
// leaf node, the distance between the root and the leaf is the length
// of the code for the corresponding symbol.
//
// The loop below doesn't actually build the tree; instead we compute
// the distances of the leaves from the root on the fly. When a new
// node is added to the heap, then that node's descendants are linked
// into a single linear list that starts at the new node, and the code
// lengths of the descendants (that is, their distance from the root
// of the tree) are incremented by one.
//
std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
long long scode[HUF_ENCSIZE];
memset(scode, 0, sizeof(long long) * HUF_ENCSIZE);
while (nf > 1) {
//
// Find the indices, mm and m, of the two smallest non-zero frq
// values in fHeap, add the smallest frq to the second-smallest
// frq, and remove the smallest frq value from fHeap.
//
int mm = fHeap[0] - frq;
std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
--nf;
int m = fHeap[0] - frq;
std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
frq[m] += frq[mm];
std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
//
// The entries in scode are linked into lists with the
// entries in hlink serving as "next" pointers and with
// the end of a list marked by hlink[j] == j.
//
// Traverse the lists that start at scode[m] and scode[mm].
// For each element visited, increment the length of the
// corresponding code by one bit. (If we visit scode[j]
// during the traversal, then the code for symbol j becomes
// one bit longer.)
//
// Merge the lists that start at scode[m] and scode[mm]
// into a single list that starts at scode[m].
//
//
// Add a bit to all codes in the first list.
//
for (int j = m; true; j = hlink[j]) {
scode[j]++;
assert(scode[j] <= 58);
if (hlink[j] == j) {
//
// Merge the two lists.
//
hlink[j] = mm;
break;
}
}
//
// Add a bit to all codes in the second list
//
for (int j = mm; true; j = hlink[j]) {
scode[j]++;
assert(scode[j] <= 58);
if (hlink[j] == j)
break;
}
}
//
// Build a canonical Huffman code table, replacing the code
// lengths in scode with (code, code length) pairs. Copy the
// code table from scode into frq.
//
hufCanonicalCodeTable(scode);
memcpy(frq, scode, sizeof(long long) * HUF_ENCSIZE);
}
//
// Pack an encoding table:
// - only code lengths, not actual codes, are stored
// - runs of zeroes are compressed as follows:
//
// unpacked packed
// --------------------------------
// 1 zero 0 (6 bits)
// 2 zeroes 59
// 3 zeroes 60
// 4 zeroes 61
// 5 zeroes 62
// n zeroes (6 or more) 63 n-6 (6 + 8 bits)
//
const int SHORT_ZEROCODE_RUN = 59;
const int LONG_ZEROCODE_RUN = 63;
const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
void hufPackEncTable(const long long *hcode, // i : encoding table [HUF_ENCSIZE]
int im, // i : min hcode index
int iM, // i : max hcode index
char **pcode) // o: ptr to packed table (updated)
{
char *p = *pcode;
long long c = 0;
int lc = 0;
for (; im <= iM; im++) {
int l = hufLength(hcode[im]);
if (l == 0) {
int zerun = 1;
while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
if (hufLength(hcode[im + 1]) > 0)
break;
im++;
zerun++;
}
if (zerun >= 2) {
if (zerun >= SHORTEST_LONG_RUN) {
outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
} else {
outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
}
continue;
}
}
outputBits(6, l, c, lc, p);
}
if (lc > 0)
*p++ = (unsigned char)(c << (8 - lc));
*pcode = p;
}
//
// Unpack an encoding table packed by hufPackEncTable():
//
bool hufUnpackEncTable(const char **pcode, // io: ptr to packed table (updated)
int ni, // i : input size (in bytes)
int im, // i : min hcode index
int iM, // i : max hcode index
long long *hcode) // o: encoding table [HUF_ENCSIZE]
{
memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
const char *p = *pcode;
long long c = 0;
int lc = 0;
for (; im <= iM; im++) {
if (p - *pcode > ni) {
return false;
}
long long l = hcode[im] = getBits(6, c, lc, p); // code length
if (l == (long long)LONG_ZEROCODE_RUN) {
if (p - *pcode > ni) {
return false;
}
int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
if (im + zerun > iM + 1) {
return false;
}
while (zerun--)
hcode[im++] = 0;
im--;
} else if (l >= (long long)SHORT_ZEROCODE_RUN) {
int zerun = l - SHORT_ZEROCODE_RUN + 2;
if (im + zerun > iM + 1) {
return false;
}
while (zerun--)
hcode[im++] = 0;
im--;
}
}
*pcode = const_cast<char *>(p);
hufCanonicalCodeTable(hcode);
return true;
}
//
// DECODING TABLE BUILDING
//
//
// Clear a newly allocated decoding table so that it contains only zeroes.
//
void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
// decoding table [HUF_DECSIZE]
{
for (int i = 0; i < HUF_DECSIZE; i++) {
hdecod[i].len = 0;
hdecod[i].lit = 0;
hdecod[i].p = NULL;
}
// memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
}
//
// Build a decoding hash table based on the encoding table hcode:
// - short codes (<= HUF_DECBITS) are resolved with a single table access;
// - long code entry allocations are not optimized, because long codes are
// unfrequent;
// - decoding tables are used by hufDecode();
//
bool hufBuildDecTable(const long long *hcode, // i : encoding table
int im, // i : min index in hcode
int iM, // i : max index in hcode
HufDec *hdecod) // o: (allocated by caller)
// decoding table [HUF_DECSIZE]
{
//
// Init hashtable & loop on all codes.
// Assumes that hufClearDecTable(hdecod) has already been called.
//
for (; im <= iM; im++) {
long long c = hufCode(hcode[im]);
int l = hufLength(hcode[im]);
if (c >> l) {
//
// Error: c is supposed to be an l-bit code,
// but c contains a value that is greater
// than the largest l-bit number.
//
// invalidTableEntry();
return false;
}
if (l > HUF_DECBITS) {
//
// Long code: add a secondary entry
//
HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
if (pl->len) {
//
// Error: a short code has already
// been stored in table entry *pl.
//
// invalidTableEntry();
return false;
}
pl->lit++;
if (pl->p) {
int *p = pl->p;
pl->p = new int[pl->lit];
for (int i = 0; i < pl->lit - 1; ++i)
pl->p[i] = p[i];
delete[] p;
} else {
pl->p = new int[1];
}
pl->p[pl->lit - 1] = im;
} else if (l) {
//
// Short code: init all primary entries
//
HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
for (long long i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
if (pl->len || pl->p) {
//
// Error: a short code or a long code has
// already been stored in table entry *pl.
//
// invalidTableEntry();
return false;
}
pl->len = l;
pl->lit = im;
}
}
}
return true;
}
//
// Free the long code entries of a decoding table built by hufBuildDecTable()
//
void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
{
for (int i = 0; i < HUF_DECSIZE; i++) {
if (hdecod[i].p) {
delete[] hdecod[i].p;
hdecod[i].p = 0;
}
}
}
//
// ENCODING
//
inline void outputCode(long long code, long long &c, int &lc, char *&out) {
outputBits(hufLength(code), hufCode(code), c, lc, out);
}
inline void sendCode(long long sCode, int runCount, long long runCode,
long long &c, int &lc, char *&out) {
//
// Output a run of runCount instances of the symbol sCount.
// Output the symbols explicitly, or if that is shorter, output
// the sCode symbol once followed by a runCode symbol and runCount
// expressed as an 8-bit number.
//
if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
outputCode(sCode, c, lc, out);
outputCode(runCode, c, lc, out);
outputBits(8, runCount, c, lc, out);
} else {
while (runCount-- >= 0)
outputCode(sCode, c, lc, out);
}
}
//
// Encode (compress) ni values based on the Huffman encoding table hcode:
//
int hufEncode // return: output size (in bits)
(const long long *hcode, // i : encoding table
const unsigned short *in, // i : uncompressed input buffer
const int ni, // i : input buffer size (in bytes)
int rlc, // i : rl code
char *out) // o: compressed output buffer
{
char *outStart = out;
long long c = 0; // bits not yet written to out
int lc = 0; // number of valid bits in c (LSB)
int s = in[0];
int cs = 0;
//
// Loop on input values
//
for (int i = 1; i < ni; i++) {
//
// Count same values or send code
//
if (s == in[i] && cs < 255) {
cs++;
} else {
sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
cs = 0;
}
s = in[i];
}
//
// Send remaining code
//
sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
if (lc)
*out = (c << (8 - lc)) & 0xff;
return (out - outStart) * 8 + lc;
}
//
// DECODING
//
//
// In order to force the compiler to inline them,
// getChar() and getCode() are implemented as macros
// instead of "inline" functions.
//
#define getChar(c, lc, in) \
{ \
c = (c << 8) | *(unsigned char *)(in++); \
lc += 8; \
}
#define getCode(po, rlc, c, lc, in, out, oe) \
{ \
if (po == rlc) { \
if (lc < 8) \
getChar(c, lc, in); \
\
lc -= 8; \
\
unsigned char cs = (c >> lc); \
\
if (out + cs > oe) \
return false; \
\
unsigned short s = out[-1]; \
\
while (cs-- > 0) \
*out++ = s; \
} else if (out < oe) { \
*out++ = po; \
} else { \
return false; \
} \
}
//
// Decode (uncompress) ni bits based on encoding & decoding tables:
//
bool hufDecode(const long long *hcode, // i : encoding table
const HufDec *hdecod, // i : decoding table
const char *in, // i : compressed input buffer
int ni, // i : input size (in bits)
int rlc, // i : run-length code
int no, // i : expected output size (in bytes)
unsigned short *out) // o: uncompressed output buffer
{
long long c = 0;
int lc = 0;
unsigned short *outb = out;
unsigned short *oe = out + no;
const char *ie = in + (ni + 7) / 8; // input byte size
//
// Loop on input bytes
//
while (in < ie) {
getChar(c, lc, in);
//
// Access decoding table
//
while (lc >= HUF_DECBITS) {
const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
if (pl.len) {
//
// Get short code
//
lc -= pl.len;
getCode(pl.lit, rlc, c, lc, in, out, oe);
} else {
if (!pl.p) {
return false;
}
// invalidCode(); // wrong code
//
// Search long code
//
int j;
for (j = 0; j < pl.lit; j++) {
int l = hufLength(hcode[pl.p[j]]);
while (lc < l && in < ie) // get more bits
getChar(c, lc, in);
if (lc >= l) {
if (hufCode(hcode[pl.p[j]]) ==
((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
//
// Found : get long code
//
lc -= l;
getCode(pl.p[j], rlc, c, lc, in, out, oe);
break;
}
}
}
if (j == pl.lit) {
return false;
// invalidCode(); // Not found
}
}
}
}
//
// Get remaining (short) codes
//
int i = (8 - ni) & 7;
c >>= i;
lc -= i;
while (lc > 0) {
const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
if (pl.len) {
lc -= pl.len;
getCode(pl.lit, rlc, c, lc, in, out, oe);
} else {
return false;
// invalidCode(); // wrong (long) code
}
}
if (out - outb != no) {
return false;
}
// notEnoughData ();
return true;
}
void countFrequencies(long long freq[HUF_ENCSIZE],
const unsigned short data[/*n*/], int n) {
for (int i = 0; i < HUF_ENCSIZE; ++i)
freq[i] = 0;
for (int i = 0; i < n; ++i)
++freq[data[i]];
}
void writeUInt(char buf[4], unsigned int i) {
unsigned char *b = (unsigned char *)buf;
b[0] = i;
b[1] = i >> 8;
b[2] = i >> 16;
b[3] = i >> 24;
}
unsigned int readUInt(const char buf[4]) {
const unsigned char *b = (const unsigned char *)buf;
return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
}
//
// EXTERNAL INTERFACE
//
int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) {
if (nRaw == 0)
return 0;
long long freq[HUF_ENCSIZE];
countFrequencies(freq, raw, nRaw);
int im = 0;
int iM = 0;
hufBuildEncTable(freq, &im, &iM);
char *tableStart = compressed + 20;
char *tableEnd = tableStart;
hufPackEncTable(freq, im, iM, &tableEnd);
int tableLength = tableEnd - tableStart;
char *dataStart = tableEnd;
int nBits = hufEncode(freq, raw, nRaw, iM, dataStart);
int dataLength = (nBits + 7) / 8;
writeUInt(compressed, im);
writeUInt(compressed + 4, iM);
writeUInt(compressed + 8, tableLength);
writeUInt(compressed + 12, nBits);
writeUInt(compressed + 16, 0); // room for future extensions
return dataStart + dataLength - compressed;
}
bool hufUncompress(const char compressed[], int nCompressed,
unsigned short raw[], int nRaw) {
if (nCompressed == 0) {
if (nRaw != 0)
return false;
return false;
}
int im = readUInt(compressed);
int iM = readUInt(compressed + 4);
// int tableLength = readUInt (compressed + 8);
int nBits = readUInt(compressed + 12);
if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)
return false;
const char *ptr = compressed + 20;
//
// Fast decoder needs at least 2x64-bits of compressed data, and
// needs to be run-able on this platform. Otherwise, fall back
// to the original decoder
//
// if (FastHufDecoder::enabled() && nBits > 128)
//{
// FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
// fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
//}
// else
{
std::vector<long long> freq(HUF_ENCSIZE);
std::vector<HufDec> hdec(HUF_DECSIZE);
hufClearDecTable(&hdec.at(0));
hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
&freq.at(0));
{
if (nBits > 8 * (nCompressed - (ptr - compressed))) {
return false;
}
hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, nRaw, raw);
}
// catch (...)
//{
// hufFreeDecTable (hdec);
// throw;
//}
hufFreeDecTable(&hdec.at(0));
}
return true;
}
//
// Functions to compress the range of values in the pixel data
//
const int USHORT_RANGE = (1 << 16);
const int BITMAP_SIZE = (USHORT_RANGE >> 3);
void bitmapFromData(const unsigned short data[/*nData*/], int nData,
unsigned char bitmap[BITMAP_SIZE],
unsigned short &minNonZero, unsigned short &maxNonZero) {
for (int i = 0; i < BITMAP_SIZE; ++i)
bitmap[i] = 0;
for (int i = 0; i < nData; ++i)
bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
bitmap[0] &= ~1; // zero is not explicitly stored in
// the bitmap; we assume that the
// data always contain zeroes
minNonZero = BITMAP_SIZE - 1;
maxNonZero = 0;
for (int i = 0; i < BITMAP_SIZE; ++i) {
if (bitmap[i]) {
if (minNonZero > i)
minNonZero = i;
if (maxNonZero < i)
maxNonZero = i;
}
}
}
unsigned short forwardLutFromBitmap(const unsigned char bitmap[BITMAP_SIZE],
unsigned short lut[USHORT_RANGE]) {
int k = 0;
for (int i = 0; i < USHORT_RANGE; ++i) {
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
lut[i] = k++;
else
lut[i] = 0;
}
return k - 1; // maximum value stored in lut[],
} // i.e. number of ones in bitmap minus 1
unsigned short reverseLutFromBitmap(const unsigned char bitmap[BITMAP_SIZE],
unsigned short lut[USHORT_RANGE]) {
int k = 0;
for (int i = 0; i < USHORT_RANGE; ++i) {
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
lut[k++] = i;
}
int n = k - 1;
while (k < USHORT_RANGE)
lut[k++] = 0;
return n; // maximum k where lut[k] is non-zero,
} // i.e. number of ones in bitmap minus 1
void applyLut(const unsigned short lut[USHORT_RANGE],
unsigned short data[/*nData*/], int nData) {
for (int i = 0; i < nData; ++i)
data[i] = lut[data[i]];
}
bool CompressPiz(unsigned char *outPtr, unsigned int &outSize,
const unsigned char *inPtr, size_t inSize,
const std::vector<ChannelInfo> &channelInfo, int dataWidth,
int numLines) {
unsigned char bitmap[BITMAP_SIZE];
unsigned short minNonZero;
unsigned short maxNonZero;
if (IsBigEndian()) {
// @todo { PIZ compression on BigEndian architecture. }
assert(0);
return false;
}
// Assume `inSize` is multiple of 2 or 4.
std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
std::vector<PIZChannelData> channelData(channelInfo.size());
unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
int i = 0;
for (size_t c = 0; c < channelData.size(); c++, i++) {
PIZChannelData &cd = channelData[i];
cd.start = tmpBufferEnd;
cd.end = cd.start;
cd.nx = dataWidth;
cd.ny = numLines;
// cd.ys = c.channel().ySampling;
int pixelSize = sizeof(int); // UINT and FLOAT
if (channelInfo[i].pixelType == TINYEXR_PIXELTYPE_HALF) {
pixelSize = sizeof(short);
}
cd.size = pixelSize / sizeof(short);
tmpBufferEnd += cd.nx * cd.ny * cd.size;
}
const unsigned char *ptr = inPtr;
for (int y = 0; y < numLines; ++y) {
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
// if (modp (y, cd.ys) != 0)
// continue;
int n = cd.nx * cd.size;
memcpy(cd.end, ptr, n * sizeof(unsigned short));
ptr += n * sizeof(unsigned short);
cd.end += n;
}
}
bitmapFromData(&tmpBuffer.at(0), tmpBuffer.size(), bitmap, minNonZero,
maxNonZero);
unsigned short lut[USHORT_RANGE];
unsigned short maxValue = forwardLutFromBitmap(bitmap, lut);
applyLut(lut, &tmpBuffer.at(0), tmpBuffer.size());
//
// Store range compression info in _outBuffer
//
char *buf = reinterpret_cast<char *>(outPtr);
memcpy(buf, &minNonZero, sizeof(unsigned short));
buf += sizeof(unsigned short);
memcpy(buf, &maxNonZero, sizeof(unsigned short));
buf += sizeof(unsigned short);
if (minNonZero <= maxNonZero) {
memcpy(buf, (char *)&bitmap[0] + minNonZero, maxNonZero - minNonZero + 1);
buf += maxNonZero - minNonZero + 1;
}
//
// Apply wavelet encoding
//
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
for (int j = 0; j < cd.size; ++j) {
wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
maxValue);
}
}
//
// Apply Huffman encoding; append the result to _outBuffer
//
// length header(4byte), then huff data. Initialize length header with zero,
// then later fill it by `length`.
char *lengthPtr = buf;
int zero = 0;
memcpy(buf, &zero, sizeof(int));
buf += sizeof(int);
int length = hufCompress(&tmpBuffer.at(0), tmpBuffer.size(), buf);
memcpy(lengthPtr, &length, sizeof(int));
outSize = (reinterpret_cast<unsigned char *>(buf) - outPtr) + length;
return true;
}
bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize,
const std::vector<ChannelInfo> &channelInfo, int dataWidth,
int numLines) {
unsigned char bitmap[BITMAP_SIZE];
unsigned short minNonZero;
unsigned short maxNonZero;
if (IsBigEndian()) {
// @todo { PIZ compression on BigEndian architecture. }
assert(0);
return false;
}
memset(bitmap, 0, BITMAP_SIZE);
const unsigned char *ptr = inPtr;
minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
ptr += 4;
if (maxNonZero >= BITMAP_SIZE) {
return false;
}
if (minNonZero <= maxNonZero) {
memcpy((char *)&bitmap[0] + minNonZero, ptr, maxNonZero - minNonZero + 1);
ptr += maxNonZero - minNonZero + 1;
}
unsigned short lut[USHORT_RANGE];
memset(lut, 0, sizeof(unsigned short) * USHORT_RANGE);
unsigned short maxValue = reverseLutFromBitmap(bitmap, lut);
//
// Huffman decoding
//
int length;
length = *(reinterpret_cast<const int *>(ptr));
ptr += sizeof(int);
std::vector<unsigned short> tmpBuffer(tmpBufSize);
hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer.at(0),
tmpBufSize);
//
// Wavelet decoding
//
std::vector<PIZChannelData> channelData(channelInfo.size());
unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
for (size_t i = 0; i < channelInfo.size(); ++i) {
const ChannelInfo &chan = channelInfo[i];
int pixelSize = sizeof(int); // UINT and FLOAT
if (chan.pixelType == TINYEXR_PIXELTYPE_HALF) {
pixelSize = sizeof(short);
}
channelData[i].start = tmpBufferEnd;
channelData[i].end = channelData[i].start;
channelData[i].nx = dataWidth;
channelData[i].ny = numLines;
// channelData[i].ys = 1;
channelData[i].size = pixelSize / sizeof(short);
tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
}
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
for (int j = 0; j < cd.size; ++j) {
wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
maxValue);
}
}
//
// Expand the pixel data to their original range
//
applyLut(lut, &tmpBuffer.at(0), tmpBufSize);
for (int y = 0; y < numLines; y++) {
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
// if (modp (y, cd.ys) != 0)
// continue;
int n = cd.nx * cd.size;
memcpy(outPtr, cd.end, n * sizeof(unsigned short));
outPtr += n * sizeof(unsigned short);
cd.end += n;
}
}
return true;
}
//
// -----------------------------------------------------------------
//
} // namespace
int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
const char **err) {
if (out_rgba == NULL) {
if (err) {
(*err) = "Invalid argument.\n";
}
return -1;
}
EXRImage exrImage;
InitEXRImage(&exrImage);
{
int ret = ParseMultiChannelEXRHeaderFromFile(&exrImage, filename, err);
if (ret != 0) {
return ret;
}
}
// Read HALF channel as FLOAT.
for (int i = 0; i < exrImage.num_channels; i++) {
if (exrImage.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
exrImage.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
}
}
{
int ret = LoadMultiChannelEXRFromFile(&exrImage, filename, err);
if (ret != 0) {
return ret;
}
}
// RGBA
int idxR = -1;
int idxG = -1;
int idxB = -1;
int idxA = -1;
for (int c = 0; c < exrImage.num_channels; c++) {
if (strcmp(exrImage.channel_names[c], "R") == 0) {
idxR = c;
} else if (strcmp(exrImage.channel_names[c], "G") == 0) {
idxG = c;
} else if (strcmp(exrImage.channel_names[c], "B") == 0) {
idxB = c;
} else if (strcmp(exrImage.channel_names[c], "A") == 0) {
idxA = c;
}
}
if (idxR == -1) {
if (err) {
(*err) = "R channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxG == -1) {
if (err) {
(*err) = "G channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxB == -1) {
if (err) {
(*err) = "B channel not found\n";
}
// @todo { free exrImage }
return -1;
}
(*out_rgba) =
(float *)malloc(4 * sizeof(float) * exrImage.width * exrImage.height);
for (int i = 0; i < exrImage.width * exrImage.height; i++) {
(*out_rgba)[4 * i + 0] =
reinterpret_cast<float **>(exrImage.images)[idxR][i];
(*out_rgba)[4 * i + 1] =
reinterpret_cast<float **>(exrImage.images)[idxG][i];
(*out_rgba)[4 * i + 2] =
reinterpret_cast<float **>(exrImage.images)[idxB][i];
if (idxA > 0) {
(*out_rgba)[4 * i + 3] =
reinterpret_cast<float **>(exrImage.images)[idxA][i];
} else {
(*out_rgba)[4 * i + 3] = 1.0;
}
}
(*width) = exrImage.width;
(*height) = exrImage.height;
// @todo { free exrImage }
return 0;
}
int ParseEXRHeaderFromMemory(EXRAttribute *customAttributes,
int *numCustomAttributes, int *width, int *height,
const unsigned char *memory) {
if (memory == NULL) {
// Invalid argument
return -1;
}
const char *buf = reinterpret_cast<const char *>(memory);
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
// if (err) {
// (*err) = "Header mismatch.";
//}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
// if (err) {
// (*err) = "Unsupported version or scanline.";
//}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int lineOrder = 0; // @fixme
int displayWindow[4] = {-1, -1, -1, -1}; // @fixme
float screenWindowCenter[2] = {0.0f, 0.0f}; // @fixme
float screenWindowWidth = 1.0f; // @fixme
int numChannels = -1;
float pixelAspectRatio = 1.0f; // @fixme
std::vector<ChannelInfo> channels;
std::vector<EXRAttribute> attribs;
if (numCustomAttributes) {
(*numCustomAttributes) = 0;
}
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == TINYEXR_COMPRESSIONTYPE_NONE) {
// mwkm
// 0 : NO_COMPRESSION
// 1 : RLE
// 2 : ZIPS (Single scanline)
// 3 : ZIP (16-line block)
// 4 : PIZ (32-line block)
if (data[0] > TINYEXR_COMPRESSIONTYPE_PIZ) {
// if (err) {
// (*err) = "Unsupported compression type.";
//}
return -5;
}
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
// if (err) {
// (*err) = "Invalid channels format.";
//}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
memcpy(&displayWindow[0], &data.at(0), sizeof(int));
memcpy(&displayWindow[1], &data.at(4), sizeof(int));
memcpy(&displayWindow[2], &data.at(8), sizeof(int));
memcpy(&displayWindow[3], &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&displayWindow[0]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[1]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[2]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[3]));
}
} else if (attrName.compare("lineOrder") == 0) {
memcpy(&lineOrder, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&lineOrder));
}
} else if (attrName.compare("pixelAspectRatio") == 0) {
memcpy(&pixelAspectRatio, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&pixelAspectRatio));
}
} else if (attrName.compare("screenWindowCenter") == 0) {
memcpy(&screenWindowCenter[0], &data.at(0), sizeof(float));
memcpy(&screenWindowCenter[1], &data.at(4), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[0]));
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[1]));
}
} else if (attrName.compare("screenWindowWidth") == 0) {
memcpy(&screenWindowWidth, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowWidth));
}
} else {
// Custom attribute(up to TINYEXR_MAX_ATTRIBUTES)
if (numCustomAttributes &&
((*numCustomAttributes) < TINYEXR_MAX_ATTRIBUTES)) {
EXRAttribute attrib;
attrib.name = strdup(attrName.c_str());
attrib.type = strdup(attrType.c_str());
attrib.size = data.size();
attrib.value = (unsigned char *)malloc(data.size());
memcpy((char *)attrib.value, &data.at(0), data.size());
attribs.push_back(attrib);
}
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
(*width) = dataWidth;
(*height) = dataHeight;
if (numCustomAttributes) {
assert(attribs.size() < TINYEXR_MAX_ATTRIBUTES);
(*numCustomAttributes) = attribs.size();
// Assume the pointer to customAttributes has enough memory to store.
for (int i = 0; i < (int)attribs.size(); i++) {
customAttributes[i] = attribs[i];
}
}
return 0;
}
int LoadEXRFromMemory(float *out_rgba, const unsigned char *memory,
const char **err) {
if (out_rgba == NULL || memory == NULL) {
if (err) {
(*err) = "Invalid argument.\n";
}
return -1;
}
EXRImage exrImage;
InitEXRImage(&exrImage);
int ret = LoadMultiChannelEXRFromMemory(&exrImage, memory, err);
if (ret != 0) {
return ret;
}
// RGBA
int idxR = -1;
int idxG = -1;
int idxB = -1;
int idxA = -1;
for (int c = 0; c < exrImage.num_channels; c++) {
if (strcmp(exrImage.channel_names[c], "R") == 0) {
idxR = c;
} else if (strcmp(exrImage.channel_names[c], "G") == 0) {
idxG = c;
} else if (strcmp(exrImage.channel_names[c], "B") == 0) {
idxB = c;
} else if (strcmp(exrImage.channel_names[c], "A") == 0) {
idxA = c;
}
}
if (idxR == -1) {
if (err) {
(*err) = "R channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxG == -1) {
if (err) {
(*err) = "G channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxB == -1) {
if (err) {
(*err) = "B channel not found\n";
}
// @todo { free exrImage }
return -1;
}
// Assume `out_rgba` have enough memory allocated.
for (int i = 0; i < exrImage.width * exrImage.height; i++) {
out_rgba[4 * i + 0] = reinterpret_cast<float **>(exrImage.images)[idxR][i];
out_rgba[4 * i + 1] = reinterpret_cast<float **>(exrImage.images)[idxG][i];
out_rgba[4 * i + 2] = reinterpret_cast<float **>(exrImage.images)[idxB][i];
if (idxA > 0) {
out_rgba[4 * i + 3] =
reinterpret_cast<float **>(exrImage.images)[idxA][i];
} else {
out_rgba[4 * i + 3] = 1.0;
}
}
return 0;
}
int LoadMultiChannelEXRFromFile(EXRImage *exrImage, const char *filename,
const char **err) {
if (exrImage == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot read file.";
}
return -1;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
(void)ret;
}
return LoadMultiChannelEXRFromMemory(exrImage, &buf.at(0), err);
}
int LoadMultiChannelEXRFromMemory(EXRImage *exrImage,
const unsigned char *memory,
const char **err) {
if (exrImage == NULL || memory == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
const char *buf = reinterpret_cast<const char *>(memory);
const char *head = &buf[0];
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
if (err) {
(*err) = "Header mismatch.";
}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
if (err) {
(*err) = "Unsupported version or scanline.";
}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int numScanlineBlocks = 1; // 16 for ZIP compression.
int compressionType = -1;
int numChannels = -1;
unsigned char lineOrder = 0; // 0 -> increasing y; 1 -> decreasing
std::vector<ChannelInfo> channels;
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == 0) {
// mwkm
// 0 : NO_COMPRESSION
// 1 : RLE
// 2 : ZIPS (Single scanline)
// 3 : ZIP (16-line block)
// 4 : PIZ (32-line block)
if (data[0] != TINYEXR_COMPRESSIONTYPE_NONE &&
data[0] != TINYEXR_COMPRESSIONTYPE_ZIPS &&
data[0] != TINYEXR_COMPRESSIONTYPE_ZIP &&
data[0] != TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Unsupported compression type.";
}
return -5;
}
compressionType = data[0];
if (compressionType == TINYEXR_COMPRESSIONTYPE_ZIP) {
numScanlineBlocks = 16;
} else if (compressionType == TINYEXR_COMPRESSIONTYPE_PIZ) {
numScanlineBlocks = 32;
}
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
if (err) {
(*err) = "Invalid channels format.";
}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
int x, y, w, h;
memcpy(&x, &data.at(0), sizeof(int));
memcpy(&y, &data.at(4), sizeof(int));
memcpy(&w, &data.at(8), sizeof(int));
memcpy(&h, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&x));
swap4(reinterpret_cast<unsigned int *>(&y));
swap4(reinterpret_cast<unsigned int *>(&w));
swap4(reinterpret_cast<unsigned int *>(&h));
}
} else if (attrName.compare("lineOrder") == 0) {
memcpy(&lineOrder, &data.at(0), sizeof(lineOrder));
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
// Read offset tables.
int numBlocks = dataHeight / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < dataHeight) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
for (int y = 0; y < numBlocks; y++) {
long long offset;
memcpy(&offset, marker, sizeof(long long));
if (IsBigEndian()) {
swap8(reinterpret_cast<unsigned long long *>(&offset));
}
marker += sizeof(long long); // = 8
offsets[y] = offset;
}
exrImage->images = reinterpret_cast<unsigned char **>(
(float **)malloc(sizeof(float *) * numChannels));
std::vector<size_t> channelOffsetList(numChannels);
int pixelDataSize = 0;
size_t channelOffset = 0;
for (int c = 0; c < numChannels; c++) {
channelOffsetList[c] = channelOffset;
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
pixelDataSize += sizeof(unsigned short);
channelOffset += sizeof(unsigned short);
// Alloc internal image for half type.
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
exrImage->images[c] =
reinterpret_cast<unsigned char *>((unsigned short *)malloc(
sizeof(unsigned short) * dataWidth * dataHeight));
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_FLOAT) {
exrImage->images[c] = reinterpret_cast<unsigned char *>(
(float *)malloc(sizeof(float) * dataWidth * dataHeight));
} else {
assert(0);
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
pixelDataSize += sizeof(float);
channelOffset += sizeof(float);
exrImage->images[c] = reinterpret_cast<unsigned char *>(
(float *)malloc(sizeof(float) * dataWidth * dataHeight));
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
pixelDataSize += sizeof(unsigned int);
channelOffset += sizeof(unsigned int);
exrImage->images[c] = reinterpret_cast<unsigned char *>((
unsigned int *)malloc(sizeof(unsigned int) * dataWidth * dataHeight));
} else {
assert(0);
}
}
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int y = 0; y < numBlocks; y++) {
const unsigned char *dataPtr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(uncompressed or compressed)
int lineNo;
memcpy(&lineNo, dataPtr, sizeof(int));
int dataLen;
memcpy(&dataLen, dataPtr + 4, sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&lineNo));
swap4(reinterpret_cast<unsigned int *>(&dataLen));
}
int endLineNo = (std::min)(lineNo + numScanlineBlocks, dataHeight);
int numLines = endLineNo - lineNo;
if (compressionType == 4) { // PIZ
// Allocate original data size.
std::vector<unsigned char> outBuf(dataWidth * numLines * pixelDataSize);
size_t tmpBufLen = dataWidth * numLines * pixelDataSize;
DecompressPiz(reinterpret_cast<unsigned char *>(&outBuf.at(0)),
dataPtr + 8, tmpBufLen, channels, dataWidth, numLines);
bool isBigEndian = IsBigEndian();
// For ZIP_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (int c = 0; c < numChannels; c++) {
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
for (int v = 0; v < numLines; v++) {
const unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = hf.u;
} else { // HALF -> FLOAT
FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = f32.f;
}
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (int v = 0; v < numLines; v++) {
const unsigned int *linePtr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
unsigned int val = linePtr[u];
if (isBigEndian) {
swap4(&val);
}
unsigned int *image =
reinterpret_cast<unsigned int **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (int v = 0; v < numLines; v++) {
const float *linePtr = reinterpret_cast<float *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
float val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else {
assert(0);
}
}
// mwkm, ZIPS or ZIP both good to go
} else if (compressionType == 2 || compressionType == 3) { // ZIP
// Allocate original data size.
std::vector<unsigned char> outBuf(dataWidth * numLines * pixelDataSize);
unsigned long dstLen = outBuf.size();
DecompressZip(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen,
dataPtr + 8, dataLen);
bool isBigEndian = IsBigEndian();
// For ZIP_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (int c = 0; c < numChannels; c++) {
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
for (int v = 0; v < numLines; v++) {
const unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = hf.u;
} else { // HALF -> FLOAT
FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = f32.f;
}
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (int v = 0; v < numLines; v++) {
const unsigned int *linePtr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
unsigned int val = linePtr[u];
if (isBigEndian) {
swap4(&val);
}
unsigned int *image =
reinterpret_cast<unsigned int **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (int v = 0; v < numLines; v++) {
const float *linePtr = reinterpret_cast<float *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
float val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else {
assert(0);
}
}
} else if (compressionType == 0) { // No compression
bool isBigEndian = IsBigEndian();
for (int c = 0; c < numChannels; c++) {
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
const unsigned short *linePtr =
reinterpret_cast<const unsigned short *>(
dataPtr + 8 + c * dataWidth * sizeof(unsigned short));
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
unsigned short *outLine =
reinterpret_cast<unsigned short *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
outLine[u] = hf.u;
}
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_FLOAT) {
float *outLine = reinterpret_cast<float *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
FP32 f32 = half_to_float(hf);
outLine[u] = f32.f;
}
} else {
assert(0);
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
const float *linePtr = reinterpret_cast<const float *>(
dataPtr + 8 + c * dataWidth * sizeof(float));
float *outLine = reinterpret_cast<float *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
float val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
outLine[u] = val;
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
const unsigned int *linePtr = reinterpret_cast<const unsigned int *>(
dataPtr + 8 + c * dataWidth * sizeof(unsigned int));
unsigned int *outLine =
reinterpret_cast<unsigned int *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
unsigned int val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
outLine[u] = val;
}
}
}
}
} // omp parallel
{
exrImage->channel_names =
(const char **)malloc(sizeof(const char *) * numChannels);
for (int c = 0; c < numChannels; c++) {
#ifdef _WIN32
exrImage->channel_names[c] = _strdup(channels[c].name.c_str());
#else
exrImage->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
exrImage->num_channels = numChannels;
exrImage->width = dataWidth;
exrImage->height = dataHeight;
// Fill with requested_pixel_types.
exrImage->pixel_types = (int *)malloc(sizeof(int *) * numChannels);
for (int c = 0; c < numChannels; c++) {
exrImage->pixel_types[c] = exrImage->requested_pixel_types[c];
}
}
return 0; // OK
}
// @deprecated
#if 0
int SaveEXR(const float *in_rgba, int width, int height, const char *filename,
const char **err) {
if (in_rgba == NULL || filename == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "wb");
if (!fp) {
if (err) {
(*err) = "Cannot write a file.";
}
return -1;
}
// Header
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
size_t n = fwrite(header, 1, 4, fp);
assert(n == 4);
}
// Version, scanline.
{
const char marker[] = {2, 0, 0, 0};
size_t n = fwrite(marker, 1, 4, fp);
assert(n == 4);
}
int numScanlineBlocks = 16; // 16 for ZIP compression.
// Write attributes.
{
unsigned char data[] = {
'A', 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'B',
0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'G', 0,
1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'R', 0, 1,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0}; // last 0 =
// terminator.
WriteAttribute(fp, "channels", "chlist", data, 18 * 4 + 1); // +1 = null
}
{
int compressionType = 3; // ZIP compression
WriteAttribute(fp, "compression", "compression",
reinterpret_cast<const unsigned char *>(&compressionType),
1);
}
{
int data[4] = {0, 0, width - 1, height - 1};
WriteAttribute(fp, "dataWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
WriteAttribute(fp, "displayWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
}
{
unsigned char lineOrder = 0; // increasingY
WriteAttribute(fp, "lineOrder", "lineOrder", &lineOrder, 1);
}
{
float aspectRatio = 1.0f;
WriteAttribute(fp, "pixelAspectRatio", "float",
reinterpret_cast<const unsigned char *>(&aspectRatio),
sizeof(float));
}
{
float center[2] = {0.0f, 0.0f};
WriteAttribute(fp, "screenWindowCenter", "v2f",
reinterpret_cast<const unsigned char *>(center),
2 * sizeof(float));
}
{
float w = (float)width;
WriteAttribute(fp, "screenWindowWidth", "float",
reinterpret_cast<const unsigned char *>(&w), sizeof(float));
}
{ // end of header
unsigned char e = 0;
fwrite(&e, 1, 1, fp);
}
int numBlocks = height / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < height) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
size_t headerSize = ftell(fp); // sizeof(header)
long long offset =
headerSize +
numBlocks * sizeof(long long); // sizeof(header) + sizeof(offsetTable)
std::vector<unsigned char> data;
for (int i = 0; i < numBlocks; i++) {
int startY = numScanlineBlocks * i;
int endY = (std::min)(numScanlineBlocks * (i + 1), height);
int h = endY - startY;
std::vector<unsigned short> buf(4 * width * h);
for (int y = 0; y < h; y++) {
for (int x = 0; x < width; x++) {
FP32 r, g, b, a;
r.f = in_rgba[4 * ((y + startY) * width + x) + 0];
g.f = in_rgba[4 * ((y + startY) * width + x) + 1];
b.f = in_rgba[4 * ((y + startY) * width + x) + 2];
a.f = in_rgba[4 * ((y + startY) * width + x) + 3];
FP16 hr, hg, hb, ha;
hr = float_to_half_full(r);
hg = float_to_half_full(g);
hb = float_to_half_full(b);
ha = float_to_half_full(a);
// Assume increasing Y
buf[4 * y * width + 3 * width + x] = hr.u;
buf[4 * y * width + 2 * width + x] = hg.u;
buf[4 * y * width + 1 * width + x] = hb.u;
buf[4 * y * width + 0 * width + x] = ha.u;
}
}
int bound = miniz::mz_compressBound(buf.size() * sizeof(unsigned short));
std::vector<unsigned char> block(
miniz::mz_compressBound(buf.size() * sizeof(unsigned short)));
unsigned long long outSize = block.size();
CompressZip(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
buf.size() * sizeof(unsigned short));
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = outSize; // truncate
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
data.insert(data.end(), header.begin(), header.end());
data.insert(data.end(), block.begin(), block.begin() + dataLen);
offsets[i] = offset;
offset += dataLen + 8; // 8 = sizeof(blockHeader)
}
fwrite(&offsets.at(0), 1, sizeof(unsigned long long) * numBlocks, fp);
fwrite(&data.at(0), 1, data.size(), fp);
fclose(fp);
return 0; // OK
}
#endif
size_t SaveMultiChannelEXRToMemory(const EXRImage *exrImage,
unsigned char **memory_out,
const char **err) {
if (exrImage == NULL || memory_out == NULL || exrImage->compression < 0 ||
exrImage->compression > TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Invalid argument.";
}
return 0;
}
std::vector<unsigned char> memory;
// Header
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
memory.insert(memory.end(), header, header + 4);
}
// Version, scanline.
{
const char marker[] = {2, 0, 0, 0};
memory.insert(memory.end(), marker, marker + 4);
}
int numScanlines = 1;
if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIP) {
numScanlines = 16;
} else if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_PIZ) {
numScanlines = 32;
}
// Write attributes.
std::vector<ChannelInfo> channels;
{
std::vector<unsigned char> data;
for (int c = 0; c < exrImage->num_channels; c++) {
ChannelInfo info;
info.pLinear = 0;
info.pixelType = exrImage->requested_pixel_types[c];
info.xSampling = 1;
info.ySampling = 1;
info.name = std::string(exrImage->channel_names[c]);
channels.push_back(info);
}
WriteChannelInfo(data, channels);
WriteAttributeToMemory(memory, "channels", "chlist", &data.at(0),
data.size()); // +1 = null
}
{
int comp = exrImage->compression;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&comp));
}
WriteAttributeToMemory(memory, "compression", "compression",
reinterpret_cast<const unsigned char *>(&comp), 1);
}
{
int data[4] = {0, 0, exrImage->width - 1, exrImage->height - 1};
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&data[0]));
swap4(reinterpret_cast<unsigned int *>(&data[1]));
swap4(reinterpret_cast<unsigned int *>(&data[2]));
swap4(reinterpret_cast<unsigned int *>(&data[3]));
}
WriteAttributeToMemory(memory, "dataWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
WriteAttributeToMemory(memory, "displayWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
}
{
unsigned char lineOrder = 0; // increasingY
WriteAttributeToMemory(memory, "lineOrder", "lineOrder", &lineOrder, 1);
}
{
float aspectRatio = 1.0f;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&aspectRatio));
}
WriteAttributeToMemory(
memory, "pixelAspectRatio", "float",
reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float));
}
{
float center[2] = {0.0f, 0.0f};
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(¢er[0]));
swap4(reinterpret_cast<unsigned int *>(¢er[1]));
}
WriteAttributeToMemory(memory, "screenWindowCenter", "v2f",
reinterpret_cast<const unsigned char *>(center),
2 * sizeof(float));
}
{
float w = (float)exrImage->width;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&w));
}
WriteAttributeToMemory(memory, "screenWindowWidth", "float",
reinterpret_cast<const unsigned char *>(&w),
sizeof(float));
}
// Custom attributes
if (exrImage->num_custom_attributes > 0) {
// @todo { endian }
for (int i = 0; i < exrImage->num_custom_attributes; i++) {
WriteAttributeToMemory(memory, exrImage->custom_attributes[i].name,
exrImage->custom_attributes[i].type,
reinterpret_cast<const unsigned char *>(
&exrImage->custom_attributes[i].value),
exrImage->custom_attributes[i].size);
}
}
{ // end of header
unsigned char e = 0;
memory.push_back(e);
}
int numBlocks = exrImage->height / numScanlines;
if (numBlocks * numScanlines < exrImage->height) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
size_t headerSize = memory.size();
long long offset =
headerSize +
numBlocks * sizeof(long long); // sizeof(header) + sizeof(offsetTable)
std::vector<unsigned char> data;
bool isBigEndian = IsBigEndian();
std::vector<std::vector<unsigned char> > dataList(numBlocks);
std::vector<size_t> channelOffsetList(exrImage->num_channels);
int pixelDataSize = 0;
size_t channelOffset = 0;
for (int c = 0; c < exrImage->num_channels; c++) {
channelOffsetList[c] = channelOffset;
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
pixelDataSize += sizeof(unsigned short);
channelOffset += sizeof(unsigned short);
} else if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
pixelDataSize += sizeof(float);
channelOffset += sizeof(float);
} else if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
pixelDataSize += sizeof(unsigned int);
channelOffset += sizeof(unsigned int);
} else {
assert(0);
}
}
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < numBlocks; i++) {
int startY = numScanlines * i;
int endY = (std::min)(numScanlines * (i + 1), exrImage->height);
int h = endY - startY;
std::vector<unsigned char> buf(exrImage->width * h * pixelDataSize);
for (int c = 0; c < exrImage->num_channels; c++) {
if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
FP16 h16;
h16.u = reinterpret_cast<unsigned short **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
FP32 f32 = half_to_float(h16);
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&f32.f));
}
// Assume increasing Y
float *linePtr = reinterpret_cast<float *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = f32.f;
}
}
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_HALF) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
unsigned short val = reinterpret_cast<unsigned short **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
if (isBigEndian) {
swap2(&val);
}
// Assume increasing Y
unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = val;
}
}
} else {
assert(0);
}
} else if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
FP32 f32;
f32.f = reinterpret_cast<float **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
FP16 h16;
h16 = float_to_half_full(f32);
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&h16.u));
}
// Assume increasing Y
unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = h16.u;
}
}
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_FLOAT) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
float val = reinterpret_cast<float **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
// Assume increasing Y
float *linePtr = reinterpret_cast<float *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = val;
}
}
} else {
assert(0);
}
} else if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
unsigned int val = reinterpret_cast<unsigned int **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
if (isBigEndian) {
swap4(&val);
}
// Assume increasing Y
unsigned int *linePtr = reinterpret_cast<unsigned int *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = val;
}
}
}
}
if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_NONE) {
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(uncompressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = (unsigned int)buf.size();
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
}
dataList[i].insert(dataList[i].end(), header.begin(), header.end());
dataList[i].insert(dataList[i].end(), buf.begin(), buf.begin() + dataLen);
} else if ((exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
(exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIP)) {
std::vector<unsigned char> block(miniz::mz_compressBound(buf.size()));
unsigned long long outSize = block.size();
CompressZip(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
buf.size());
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = outSize; // truncate
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
}
dataList[i].insert(dataList[i].end(), header.begin(), header.end());
dataList[i].insert(dataList[i].end(), block.begin(),
block.begin() + dataLen);
} else if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_PIZ) {
unsigned int bufLen =
1024 +
1.2 * (unsigned int)buf.size(); // @fixme { compute good bound. }
std::vector<unsigned char> block(bufLen);
unsigned int outSize = static_cast<unsigned int>(block.size());
CompressPiz(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
buf.size(), channels, exrImage->width, h);
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = outSize;
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
}
dataList[i].insert(dataList[i].end(), header.begin(), header.end());
dataList[i].insert(dataList[i].end(), block.begin(),
block.begin() + dataLen);
} else {
assert(0);
}
} // omp parallel
for (int i = 0; i < numBlocks; i++) {
data.insert(data.end(), dataList[i].begin(), dataList[i].end());
offsets[i] = offset;
if (IsBigEndian()) {
swap8(reinterpret_cast<unsigned long long *>(&offsets[i]));
}
offset += dataList[i].size();
}
{
memory.insert(memory.end(),
reinterpret_cast<unsigned char *>(&offsets.at(0)),
reinterpret_cast<unsigned char *>(&offsets.at(0)) +
sizeof(unsigned long long) * numBlocks);
}
{ memory.insert(memory.end(), data.begin(), data.end()); }
assert(memory.size() > 0);
(*memory_out) = (unsigned char *)malloc(memory.size());
memcpy((*memory_out), &memory.at(0), memory.size());
return memory.size(); // OK
}
int SaveMultiChannelEXRToFile(const EXRImage *exrImage, const char *filename,
const char **err) {
if (exrImage == NULL || filename == NULL || exrImage->compression < 0 ||
exrImage->compression > TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "wb");
if (!fp) {
if (err) {
(*err) = "Cannot write a file.";
}
return -1;
}
unsigned char *mem = NULL;
size_t mem_size = SaveMultiChannelEXRToMemory(exrImage, &mem, err);
if ((mem_size > 0) && mem) {
fwrite(mem, 1, mem_size, fp);
}
free(mem);
fclose(fp);
return 0; // OK
}
int LoadDeepEXR(DeepImage *deepImage, const char *filename, const char **err) {
if (deepImage == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot read file.";
}
return -1;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (filesize == 0) {
fclose(fp);
if (err) {
(*err) = "File size is zero.";
}
return -1;
}
std::vector<char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
(void)ret;
}
fclose(fp);
const char *head = &buf[0];
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
if (err) {
(*err) = "Header mismatch.";
}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// ver 2.0, scanline, deep bit on(0x800)
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
if (err) {
(*err) = "Unsupported version or scanline.";
}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int numScanlineBlocks = 1; // 16 for ZIP compression.
int compressionType = -1;
int numChannels = -1;
std::vector<ChannelInfo> channels;
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == 0) {
// must be 0:No compression, 1: RLE, 2: ZIPs or 3: ZIP
if (data[0] > 3) {
if (err) {
(*err) = "Unsupported compression type.";
}
return -5;
}
compressionType = data[0];
if (compressionType == 3) { // ZIP
numScanlineBlocks = 16;
}
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
if (err) {
(*err) = "Invalid channels format.";
}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
int x;
int y;
int w;
int h;
memcpy(&x, &data.at(0), sizeof(int));
memcpy(&y, &data.at(4), sizeof(int));
memcpy(&w, &data.at(8), sizeof(int));
memcpy(&h, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&x));
swap4(reinterpret_cast<unsigned int *>(&y));
swap4(reinterpret_cast<unsigned int *>(&w));
swap4(reinterpret_cast<unsigned int *>(&h));
}
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
std::vector<float> image(dataWidth * dataHeight * 4); // 4 = RGBA
// Read offset tables.
int numBlocks = dataHeight / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < dataHeight) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
for (int y = 0; y < numBlocks; y++) {
long long offset;
memcpy(&offset, marker, sizeof(long long));
if (IsBigEndian()) {
swap8(reinterpret_cast<unsigned long long *>(&offset));
}
marker += sizeof(long long); // = 8
offsets[y] = offset;
}
if (compressionType != 0 && compressionType != 2 && compressionType != 3) {
if (err) {
(*err) = "Unsupported format.";
}
return -10;
}
deepImage->image = (float ***)malloc(sizeof(float **) * numChannels);
for (int c = 0; c < numChannels; c++) {
deepImage->image[c] = (float **)malloc(sizeof(float *) * dataHeight);
for (int y = 0; y < dataHeight; y++) {
}
}
deepImage->offset_table = (int **)malloc(sizeof(int *) * dataHeight);
for (int y = 0; y < dataHeight; y++) {
deepImage->offset_table[y] = (int *)malloc(sizeof(int) * dataWidth);
}
for (int y = 0; y < numBlocks; y++) {
const unsigned char *dataPtr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// int: y coordinate
// int64: packed size of pixel offset table
// int64: packed size of sample data
// int64: unpacked size of sample data
// compressed pixel offset table
// compressed sample data
int lineNo;
long long packedOffsetTableSize;
long long packedSampleDataSize;
long long unpackedSampleDataSize;
memcpy(&lineNo, dataPtr, sizeof(int));
memcpy(&packedOffsetTableSize, dataPtr + 4, sizeof(long long));
memcpy(&packedSampleDataSize, dataPtr + 12, sizeof(long long));
memcpy(&unpackedSampleDataSize, dataPtr + 20, sizeof(long long));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&lineNo));
swap8(reinterpret_cast<unsigned long long *>(&packedOffsetTableSize));
swap8(reinterpret_cast<unsigned long long *>(&packedSampleDataSize));
swap8(reinterpret_cast<unsigned long long *>(&unpackedSampleDataSize));
}
std::vector<int> pixelOffsetTable(dataWidth);
// decode pixel offset table.
{
unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
DecompressZip(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
dstLen, dataPtr + 28, packedOffsetTableSize);
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
for (int i = 0; i < dataWidth; i++) {
deepImage->offset_table[y][i] = pixelOffsetTable[i];
}
}
std::vector<unsigned char> sampleData(unpackedSampleDataSize);
// decode sample data.
{
unsigned long dstLen = unpackedSampleDataSize;
DecompressZip(reinterpret_cast<unsigned char *>(&sampleData.at(0)),
dstLen, dataPtr + 28 + packedOffsetTableSize,
packedSampleDataSize);
assert(dstLen == (unsigned long)unpackedSampleDataSize);
}
// decode sample
int sampleSize = -1;
std::vector<int> channelOffsetList(numChannels);
{
int channelOffset = 0;
for (int i = 0; i < numChannels; i++) {
channelOffsetList[i] = channelOffset;
if (channels[i].pixelType == TINYEXR_PIXELTYPE_UINT) { // UINT
channelOffset += 4;
} else if (channels[i].pixelType == TINYEXR_PIXELTYPE_HALF) { // half
channelOffset += 2;
} else if (channels[i].pixelType == TINYEXR_PIXELTYPE_FLOAT) { // float
channelOffset += 4;
} else {
assert(0);
}
}
sampleSize = channelOffset;
}
assert(sampleSize >= 2);
assert((size_t)(pixelOffsetTable[dataWidth - 1] * sampleSize) ==
sampleData.size());
int samplesPerLine = sampleData.size() / sampleSize;
//
// Alloc memory
//
//
// pixel data is stored as image[channels][pixel_samples]
//
{
unsigned long long dataOffset = 0;
for (int c = 0; c < numChannels; c++) {
deepImage->image[c][y] =
(float *)malloc(sizeof(float) * samplesPerLine);
if (channels[c].pixelType == 0) { // UINT
for (int x = 0; x < samplesPerLine; x++) {
unsigned int ui = *reinterpret_cast<unsigned int *>(
&sampleData.at(dataOffset + x * sizeof(int)));
deepImage->image[c][y][x] = (float)ui; // @fixme
}
dataOffset += sizeof(unsigned int) * samplesPerLine;
} else if (channels[c].pixelType == 1) { // half
for (int x = 0; x < samplesPerLine; x++) {
FP16 f16;
f16.u = *reinterpret_cast<unsigned short *>(
&sampleData.at(dataOffset + x * sizeof(short)));
FP32 f32 = half_to_float(f16);
deepImage->image[c][y][x] = f32.f;
}
dataOffset += sizeof(short) * samplesPerLine;
} else { // float
for (int x = 0; x < samplesPerLine; x++) {
float f = *reinterpret_cast<float *>(
&sampleData.at(dataOffset + x * sizeof(float)));
deepImage->image[c][y][x] = f;
}
dataOffset += sizeof(float) * samplesPerLine;
}
}
}
} // y
deepImage->width = dataWidth;
deepImage->height = dataHeight;
deepImage->channel_names =
(const char **)malloc(sizeof(const char *) * numChannels);
for (int c = 0; c < numChannels; c++) {
#ifdef _WIN32
deepImage->channel_names[c] = _strdup(channels[c].name.c_str());
#else
deepImage->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
deepImage->num_channels = numChannels;
return 0; // OK
}
int SaveDeepEXR(const DeepImage *deepImage, const char *filename,
const char **err) {
if (deepImage == NULL || filename == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot write file.";
}
return -1;
}
// Write header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
size_t n = fwrite(header, 1, 4, fp);
if (n != 4) {
if (err) {
(*err) = "Header write failed.";
}
fclose(fp);
return -3;
}
}
// Version, scanline.
{
// ver 2.0, scanline, deep bit on(0x800)
const char data[] = {2, 8, 0, 0};
size_t n = fwrite(data, 1, 4, fp);
if (n != 4) {
if (err) {
(*err) = "Flag write failed.";
}
fclose(fp);
return -3;
}
}
// Write attributes.
{
int data = 2; // ZIPS
WriteAttribute(fp, "compression", "compression",
reinterpret_cast<const unsigned char *>(&data), sizeof(int));
}
{
int data[4] = {0, 0, deepImage->width - 1, deepImage->height - 1};
WriteAttribute(fp, "dataWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
WriteAttribute(fp, "displayWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
}
int numScanlineBlocks = 1;
// Write offset tables.
int numBlocks = deepImage->height / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < deepImage->height) {
numBlocks++;
}
#if 0 // @todo
std::vector<long long> offsets(numBlocks);
//std::vector<int> pixelOffsetTable(dataWidth);
// compress pixel offset table.
{
unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
Compresses(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
dstLen, dataPtr + 28, packedOffsetTableSize);
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
// int ret =
// miniz::mz_uncompress(reinterpret_cast<unsigned char
// *>(&pixelOffsetTable.at(0)), &dstLen, dataPtr + 28,
// packedOffsetTableSize);
// printf("ret = %d, dstLen = %d\n", ret, (int)dstLen);
//
for (int i = 0; i < dataWidth; i++) {
// printf("offt[%d] = %d\n", i, pixelOffsetTable[i]);
deepImage->offset_table[y][i] = pixelOffsetTable[i];
}
}
for (int y = 0; y < numBlocks; y++) {
//long long offset = *(reinterpret_cast<const long long *>(marker));
// printf("offset[%d] = %lld\n", y, offset);
//marker += sizeof(long long); // = 8
offsets[y] = offset;
}
// Write offset table.
fwrite(&offsets.at(0), sizeof(long long), numBlocks, fp);
for (int y = 0; y < numBlocks; y++) {
const unsigned char *dataPtr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// int: y coordinate
// int64: packed size of pixel offset table
// int64: packed size of sample data
// int64: unpacked size of sample data
// compressed pixel offset table
// compressed sample data
int lineNo = *reinterpret_cast<const int *>(dataPtr);
long long packedOffsetTableSize =
*reinterpret_cast<const long long *>(dataPtr + 4);
long long packedSampleDataSize =
*reinterpret_cast<const long long *>(dataPtr + 12);
long long unpackedSampleDataSize =
*reinterpret_cast<const long long *>(dataPtr + 20);
// printf("line: %d, %lld/%lld/%lld\n", lineNo, packedOffsetTableSize,
// packedSampleDataSize, unpackedSampleDataSize);
int endLineNo = (std::min)(lineNo + numScanlineBlocks, dataHeight);
int numLines = endLineNo - lineNo;
// printf("numLines: %d\n", numLines);
std::vector<int> pixelOffsetTable(dataWidth);
// decode pixel offset table.
{
unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
DecompressZip(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
dstLen, dataPtr + 28, packedOffsetTableSize);
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
// int ret =
// miniz::mz_uncompress(reinterpret_cast<unsigned char
// *>(&pixelOffsetTable.at(0)), &dstLen, dataPtr + 28,
// packedOffsetTableSize);
// printf("ret = %d, dstLen = %d\n", ret, (int)dstLen);
//
for (int i = 0; i < dataWidth; i++) {
// printf("offt[%d] = %d\n", i, pixelOffsetTable[i]);
deepImage->offset_table[y][i] = pixelOffsetTable[i];
}
}
std::vector<unsigned char> sampleData(unpackedSampleDataSize);
// decode sample data.
{
unsigned long dstLen = unpackedSampleDataSize;
// printf("dstLen = %d\n", dstLen);
// printf("srcLen = %d\n", packedSampleDataSize);
DecompressZip(reinterpret_cast<unsigned char *>(&sampleData.at(0)),
dstLen, dataPtr + 28 + packedOffsetTableSize,
packedSampleDataSize);
assert(dstLen == unpackedSampleDataSize);
}
// decode sample
int sampleSize = -1;
std::vector<int> channelOffsetList(numChannels);
{
int channelOffset = 0;
for (int i = 0; i < numChannels; i++) {
// printf("offt[%d] = %d\n", i, channelOffset);
channelOffsetList[i] = channelOffset;
if (channels[i].pixelType == 0) { // UINT
channelOffset += 4;
} else if (channels[i].pixelType == 1) { // half
channelOffset += 2;
} else if (channels[i].pixelType == 2) { // float
channelOffset += 4;
} else {
assert(0);
}
}
sampleSize = channelOffset;
}
assert(sampleSize >= 2);
assert(pixelOffsetTable[dataWidth - 1] * sampleSize == sampleData.size());
int samplesPerLine = sampleData.size() / sampleSize;
//
// Alloc memory
//
//
// pixel data is stored as image[channels][pixel_samples]
//
{
unsigned long long dataOffset = 0;
for (int c = 0; c < numChannels; c++) {
deepImage->image[c][y] =
(float *)malloc(sizeof(float) * samplesPerLine);
// unsigned int channelOffset = channelOffsetList[c];
// unsigned int i = channelOffset;
// printf("channel = %d. name = %s. ty = %d\n", c,
// channels[c].name.c_str(), channels[c].pixelType);
// printf("dataOffset = %d\n", (int)dataOffset);
if (channels[c].pixelType == 0) { // UINT
for (int x = 0; x < samplesPerLine; x++) {
unsigned int ui = *reinterpret_cast<unsigned int *>(
&sampleData.at(dataOffset + x * sizeof(int)));
deepImage->image[c][y][x] = (float)ui; // @fixme
}
dataOffset += sizeof(unsigned int) * samplesPerLine;
} else if (channels[c].pixelType == 1) { // half
for (int x = 0; x < samplesPerLine; x++) {
FP16 f16;
f16.u = *reinterpret_cast<unsigned short *>(
&sampleData.at(dataOffset + x * sizeof(short)));
FP32 f32 = half_to_float(f16);
deepImage->image[c][y][x] = f32.f;
// printf("c[%d] f(half) = %f (0x%08x)\n", c, f32.f, f16.u);
}
dataOffset += sizeof(short) * samplesPerLine;
} else { // float
for (int x = 0; x < samplesPerLine; x++) {
float f = *reinterpret_cast<float *>(
&sampleData.at(dataOffset + x * sizeof(float)));
// printf(" f = %f(0x%08x)\n", f, *((unsigned int *)&f));
deepImage->image[c][y][x] = f;
}
dataOffset += sizeof(float) * samplesPerLine;
}
}
// printf("total: %d\n", dataOffset);
}
} // y
#endif
fclose(fp);
return 0; // OK
}
void InitEXRImage(EXRImage *exrImage) {
if (exrImage == NULL) {
return;
}
exrImage->num_custom_attributes = 0;
exrImage->num_channels = 0;
exrImage->channel_names = NULL;
exrImage->images = NULL;
exrImage->pixel_types = NULL;
exrImage->requested_pixel_types = NULL;
exrImage->compression = TINYEXR_COMPRESSIONTYPE_ZIP;
}
int FreeEXRImage(EXRImage *exrImage) {
if (exrImage == NULL) {
return -1; // Err
}
for (int i = 0; i < exrImage->num_channels; i++) {
if (exrImage->channel_names && exrImage->channel_names[i]) {
free((char *)exrImage->channel_names[i]); // remove const
}
if (exrImage->images && exrImage->images[i]) {
free(exrImage->images[i]);
}
}
if (exrImage->channel_names) {
free(exrImage->channel_names);
}
if (exrImage->images) {
free(exrImage->images);
}
if (exrImage->pixel_types) {
free(exrImage->pixel_types);
}
if (exrImage->requested_pixel_types) {
free(exrImage->requested_pixel_types);
}
for (int i = 0; i < exrImage->num_custom_attributes; i++) {
if (exrImage->custom_attributes[i].name) {
free(exrImage->custom_attributes[i].name);
}
if (exrImage->custom_attributes[i].type) {
free(exrImage->custom_attributes[i].type);
}
if (exrImage->custom_attributes[i].value) {
free(exrImage->custom_attributes[i].value);
}
}
return 0;
}
int ParseMultiChannelEXRHeaderFromFile(EXRImage *exrImage, const char *filename,
const char **err) {
if (exrImage == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot read file.";
}
return -1;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
(void)ret;
}
return ParseMultiChannelEXRHeaderFromMemory(exrImage, &buf.at(0), err);
}
int ParseMultiChannelEXRHeaderFromMemory(EXRImage *exrImage,
const unsigned char *memory,
const char **err) {
if (exrImage == NULL || memory == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
const char *buf = reinterpret_cast<const char *>(memory);
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
if (err) {
(*err) = "Header mismatch.";
}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
if (err) {
(*err) = "Unsupported version or scanline.";
}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int numChannels = -1;
int displayWindow[4] = {-1, -1, -1, -1}; // @fixme.
float screenWindowCenter[2] = {0.0f, 0.0f}; // @fixme
float screenWindowWidth = 1.0f; // @fixme
float pixelAspectRatio = 1.0f;
unsigned char lineOrder = 0; // 0 -> increasing y; 1 -> decreasing
std::vector<ChannelInfo> channels;
int compressionType = 0; // @fixme
int numCustomAttributes = 0;
std::vector<EXRAttribute> customAttribs;
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == 0) {
// must be 0:No compression, 1: RLE, 2: ZIPs, 3: ZIP or 4: PIZ
if (data[0] > TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Unsupported compression type.";
}
return -5;
}
compressionType = data[0];
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
if (err) {
(*err) = "Invalid channels format.";
}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
memcpy(&displayWindow[0], &data.at(0), sizeof(int));
memcpy(&displayWindow[1], &data.at(4), sizeof(int));
memcpy(&displayWindow[2], &data.at(8), sizeof(int));
memcpy(&displayWindow[3], &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&displayWindow[0]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[1]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[2]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[3]));
}
} else if (attrName.compare("lineOrder") == 0) {
int order;
memcpy(&order, &data.at(0), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&order));
}
lineOrder = (unsigned char)order;
} else if (attrName.compare("pixelAspectRatio") == 0) {
memcpy(&pixelAspectRatio, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&pixelAspectRatio));
}
} else if (attrName.compare("screenWindowCenter") == 0) {
memcpy(&screenWindowCenter[0], &data.at(0), sizeof(float));
memcpy(&screenWindowCenter[1], &data.at(4), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[0]));
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[1]));
}
} else if (attrName.compare("screenWindowWidth") == 0) {
memcpy(&screenWindowWidth, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowWidth));
}
} else {
// Custom attribute(up to TINYEXR_MAX_ATTRIBUTES)
if (numCustomAttributes < TINYEXR_MAX_ATTRIBUTES) {
EXRAttribute attrib;
attrib.name = strdup(attrName.c_str());
attrib.type = strdup(attrType.c_str());
attrib.size = data.size();
attrib.value = (unsigned char *)malloc(data.size());
memcpy((char *)attrib.value, &data.at(0), data.size());
customAttribs.push_back(attrib);
}
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
{
exrImage->channel_names =
(const char **)malloc(sizeof(const char *) * numChannels);
for (int c = 0; c < numChannels; c++) {
#ifdef _WIN32
exrImage->channel_names[c] = _strdup(channels[c].name.c_str());
#else
exrImage->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
exrImage->num_channels = numChannels;
exrImage->width = dataWidth;
exrImage->height = dataHeight;
exrImage->pixel_aspect_ratio = pixelAspectRatio;
exrImage->screen_window_center[0] = screenWindowCenter[0];
exrImage->screen_window_center[1] = screenWindowCenter[1];
exrImage->screen_window_width = screenWindowWidth;
exrImage->display_window[0] = displayWindow[0];
exrImage->display_window[1] = displayWindow[1];
exrImage->display_window[2] = displayWindow[2];
exrImage->display_window[3] = displayWindow[3];
exrImage->data_window[0] = dx;
exrImage->data_window[1] = dy;
exrImage->data_window[2] = dw;
exrImage->data_window[3] = dh;
exrImage->line_order = lineOrder;
exrImage->compression = compressionType;
exrImage->pixel_types = (int *)malloc(sizeof(int) * numChannels);
for (int c = 0; c < numChannels; c++) {
exrImage->pixel_types[c] = channels[c].pixelType;
}
// Initially fill with values of `pixel-types`
exrImage->requested_pixel_types = (int *)malloc(sizeof(int) * numChannels);
for (int c = 0; c < numChannels; c++) {
exrImage->requested_pixel_types[c] = channels[c].pixelType;
}
}
if (numCustomAttributes > 0) {
assert(customAttribs.size() < TINYEXR_MAX_ATTRIBUTES);
exrImage->num_custom_attributes = numCustomAttributes;
for (int i = 0; i < (int)customAttribs.size(); i++) {
exrImage->custom_attributes[i] = customAttribs[i];
}
}
return 0; // OK
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
#endif // __TINYEXR_H__
|
3d25pt_var.c | /*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 16;
tile_size[1] = 16;
tile_size[2] = 8;
tile_size[3] = 256;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
common.h | // Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COMMON_H
#define COMMON_H
#include <atomic>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#define CHECK(x) \
do { \
if (!(x)) { \
fprintf(stderr, "Assertion failure at %s:%d: %s\n", __FILE__, __LINE__, \
#x); \
abort(); \
} \
} while (0);
#define CHECK_NE(a, b) CHECK(a != b)
#define CHECK_M(x, msg) \
do { \
if (!(x)) { \
fprintf(stderr, "Assertion failure at %s:%d: %s %s\n", __FILE__, \
__LINE__, #x, msg); \
abort(); \
} \
} while (0);
inline void FullFence() {
std::atomic_thread_fence(std::memory_order_seq_cst);
asm volatile("" : : : "memory");
#pragma omp barrier
}
template <typename T>
void ReadBinaryOrDie(FILE *f, T *out, size_t count = 1) {
fread(out, sizeof(T), count, f);
}
template <typename T>
T ReadBinaryOrDie(FILE *f) {
T ans;
ReadBinaryOrDie(f, &ans);
return ans;
}
template <typename T>
T ReadBase10Fast(FILE *f) {
T n = 0;
int ch = fgetc_unlocked(f);
while (ch != EOF && !('0' <= ch && ch <= '9')) ch = fgetc_unlocked(f);
if (ch == EOF) return EOF;
while ('0' <= ch && ch <= '9') {
n = 10 * n + ch - '0';
ch = fgetc_unlocked(f);
}
return n;
}
class FastWriter {
static constexpr size_t kBufSize = 1 << 16;
public:
FastWriter(const char *filename) { CHECK(out_ = fopen(filename, "w")); }
FastWriter(int fd) { CHECK(out_ = fdopen(fd, "w")); }
~FastWriter() {
Flush();
CHECK_M(fclose(out_) == 0, strerror(errno));
}
FastWriter(const FastWriter &) = delete;
FastWriter(FastWriter &&) = delete;
void Flush() {
if (buf_position_ > 0) {
CHECK_M(fwrite(buf_, 1, buf_position_, out_), strerror(errno));
}
buf_position_ = 0;
}
void AddToBuffer(char c) {
buf_[buf_position_++] = c;
if (buf_position_ >= kBufSize) {
Flush();
}
}
void AddToBuffer(const char *data, size_t len) {
for (size_t i = 0; i < len; i++) {
buf_[buf_position_++] = data[i];
if (buf_position_ >= kBufSize) {
Flush();
}
}
}
void AddToBuffer(const std::string &s) { AddToBuffer(s.c_str(), s.size()); }
template <typename T>
void Write(const T ¶m) {
AddToBuffer(std::to_string(param));
}
void Write(const char param) { AddToBuffer(param); }
private:
FILE *out_ = nullptr; // owned
char buf_[kBufSize] = {};
size_t buf_position_ = 0;
};
std::string FileFromStorageDir(const std::string &storage_dir,
const std::string &filename) {
if (storage_dir.empty()) return "";
return storage_dir + "/" + filename;
}
#endif
|
shared-clause.c | /*
* private-clause.c
*
* Created on: 02/04/2014
* Author: Carlos de la Torre
*/
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
int main() {
int i, n = 7;
int a[n];
for (i = 0; i < n; i++)
a[i] = i + 1;
#pragma omp parallel for shared(a)
for (i = 0; i < n; i++)
a[i] += i;
printf("Después de parallel for:\n");
for (i = 0; i < n; i++)
printf("a[%d] = %d\n", i, a[i]);
return 0;
}
|
ejercicio2-2.c | #include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
main(){
int i, n = 7;
int a[n], suma;
for (i=0; i<n; i++)
a[i] = i;
#pragma omp parallel private(suma)
{
suma=5;
#pragma omp for
for(i=0; i<n; i++){
suma = suma + a[i];
printf("thread %d suma a[%d]/", omp_get_thread_num(), i);
}
printf("\n* thread %d suma= %d", omp_get_thread_num(), suma);
}
printf("\n");
}
|
GB_dense_subassign_06d_template.c | //------------------------------------------------------------------------------
// GB_dense_subassign_06d_template: C<A> = A
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
{
//--------------------------------------------------------------------------
// get C and A
//--------------------------------------------------------------------------
ASSERT (!GB_ZOMBIES (A)) ;
ASSERT (GB_JUMBLED_OK (A)) ;
ASSERT (!GB_PENDING (A)) ;
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ah = A->h ;
const int64_t *restrict Ai = A->i ;
const int8_t *restrict Ab = A->b ;
const bool A_iso = A->iso ;
const int64_t avlen = A->vlen ;
const bool A_is_bitmap = GB_IS_BITMAP (A) ;
const bool A_is_dense = GB_as_if_full (A) ;
const int64_t anz = GB_nnz_held (A) ;
// since A is the mask, if A->iso is true, Mask_struct has been set true
ASSERT (GB_IMPLIES (A_iso, Mask_struct)) ;
int8_t *restrict Cb = C->b ;
const int64_t cvlen = C->vlen ;
const bool C_is_bitmap = GB_IS_BITMAP (C) ;
#ifdef GB_ISO_ASSIGN
ASSERT (C->iso) ;
ASSERT (A->iso) ;
ASSERT (Mask_struct) ;
#else
const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ;
GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ;
#endif
//--------------------------------------------------------------------------
// C<A> = A
//--------------------------------------------------------------------------
int64_t cnvals = C->nvals ; // for C bitmap
if (Mask_struct)
{
//----------------------------------------------------------------------
// C<A,struct> = A where A can be iso or non-iso; mask is structural
//----------------------------------------------------------------------
if (A_is_dense)
{
//------------------------------------------------------------------
// A is dense: all entries present
//------------------------------------------------------------------
#ifndef GB_ISO_ASSIGN
{
int64_t p ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static)
for (p = 0 ; p < anz ; p++)
{
// Cx [p] = Ax [p]
GB_COPY_A_TO_C (Cx, p, Ax, p, A_iso) ;
}
}
#endif
if (C_is_bitmap)
{
GB_memset (Cb, 1, anz, A_nthreads) ;
cnvals = anz ;
}
}
else if (A_is_bitmap)
{
//------------------------------------------------------------------
// A is bitmap
//------------------------------------------------------------------
if (C_is_bitmap)
{
//--------------------------------------------------------------
// C is bitmap, A is bitmap
//--------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static) reduction(+:cnvals)
for (tid = 0 ; tid < A_nthreads ; tid++)
{
int64_t pA_start, pA_end, task_cnvals = 0 ;
GB_PARTITION (pA_start, pA_end, anz, tid, A_nthreads) ;
for (int64_t p = pA_start ; p < pA_end ; p++)
{
if (Ab [p])
{
// Cx [p] = Ax [p]
#ifndef GB_ISO_ASSIGN
GB_COPY_A_TO_C (Cx, p, Ax, p, A_iso) ;
#endif
task_cnvals += (Cb [p] == 0) ;
Cb [p] = 1 ;
}
}
cnvals += task_cnvals ;
}
}
else
{
//--------------------------------------------------------------
// C is hypersparse, sparse, or full, with all entries present
//--------------------------------------------------------------
#ifndef GB_ISO_ASSIGN
{
// this method is used by LAGraph_bfs_parent when q is
// a bitmap and pi is full.
int64_t p ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static)
for (p = 0 ; p < anz ; p++)
{
// Cx [p] = Ax [p]
if (Ab [p])
{
GB_COPY_A_TO_C (Cx, p, Ax, p, A_iso) ;
}
}
}
#endif
}
}
else
{
//------------------------------------------------------------------
// A is hypersparse or sparse; C is dense or a bitmap
//------------------------------------------------------------------
const int64_t *restrict kfirst_Aslice = A_ek_slicing ;
const int64_t *restrict klast_Aslice = A_ek_slicing + A_ntasks ;
const int64_t *restrict pstart_Aslice = A_ek_slicing + A_ntasks * 2;
int taskid ;
if (C_is_bitmap)
{
//--------------------------------------------------------------
// C is bitmap, mask is structural
//--------------------------------------------------------------
#pragma omp parallel for num_threads(A_nthreads) \
schedule(dynamic,1) reduction(+:cnvals)
for (taskid = 0 ; taskid < A_ntasks ; taskid++)
{
// if kfirst > klast then taskid does no work at all
int64_t kfirst = kfirst_Aslice [taskid] ;
int64_t klast = klast_Aslice [taskid] ;
int64_t task_cnvals = 0 ;
// C<A(:,kfirst:klast)> = A(:,kfirst:klast)
for (int64_t k = kfirst ; k <= klast ; k++)
{
// get A(:,j), the kth vector of A
int64_t j = GBH (Ah, k) ;
int64_t pA_start, pA_end ;
GB_get_pA (&pA_start, &pA_end, taskid, k,
kfirst, klast, pstart_Aslice, Ap, avlen) ;
// pC is the start of C(:,j)
int64_t pC = j * cvlen ;
// C<A(:,j),struct>=A(:,j) with C bitmap, A sparse
GB_PRAGMA_SIMD_REDUCTION (+,task_cnvals)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
int64_t p = pC + Ai [pA] ;
// Cx [p] = Ax [pA]
#ifndef GB_ISO_ASSIGN
GB_COPY_A_TO_C (Cx, p, Ax, pA, A_iso) ;
#endif
task_cnvals += (Cb [p] == 0) ;
Cb [p] = 1 ;
}
}
cnvals += task_cnvals ;
}
}
else
{
//--------------------------------------------------------------
// C is full, mask is structural
//--------------------------------------------------------------
#ifndef GB_ISO_ASSIGN
{
#pragma omp parallel for num_threads(A_nthreads) \
schedule(dynamic,1)
for (taskid = 0 ; taskid < A_ntasks ; taskid++)
{
// if kfirst > klast then taskid does no work at all
int64_t kfirst = kfirst_Aslice [taskid] ;
int64_t klast = klast_Aslice [taskid] ;
// C<A(:,kfirst:klast)> = A(:,kfirst:klast)
for (int64_t k = kfirst ; k <= klast ; k++)
{
// get A(:,j), the kth vector of A
int64_t j = GBH (Ah, k) ;
int64_t pA_start, pA_end ;
GB_get_pA (&pA_start, &pA_end, taskid, k,
kfirst, klast, pstart_Aslice, Ap, avlen) ;
// pC is the start of C(:,j)
int64_t pC = j * cvlen ;
// C<A(:,j),struct>=A(:,j) with C full, A sparse
GB_PRAGMA_SIMD_VECTORIZE
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
int64_t p = pC + Ai [pA] ;
// Cx [p] = Ax [pA]
GB_COPY_A_TO_C (Cx, p, Ax, pA, A_iso) ;
}
}
}
}
#endif
}
}
}
#ifndef GB_ISO_ASSIGN
else
{
//----------------------------------------------------------------------
// C<A> = A where A must be non-iso, and the mask is valued
//----------------------------------------------------------------------
if (A_is_dense)
{
//------------------------------------------------------------------
// A is dense: all entries present
//------------------------------------------------------------------
if (C_is_bitmap)
{
//--------------------------------------------------------------
// C is bitmap, A is dense
//--------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static) reduction(+:cnvals)
for (tid = 0 ; tid < A_nthreads ; tid++)
{
int64_t pA_start, pA_end, task_cnvals = 0 ;
GB_PARTITION (pA_start, pA_end, anz, tid, A_nthreads) ;
for (int64_t p = pA_start ; p < pA_end ; p++)
{
if (GB_AX_MASK (Ax, p, asize))
{
// Cx [p] = Ax [p]
GB_COPY_A_TO_C (Cx, p, Ax, p, false) ;
task_cnvals += (Cb [p] == 0) ;
Cb [p] = 1 ;
}
}
cnvals += task_cnvals ;
}
}
else
{
//--------------------------------------------------------------
// C is hypersparse, sparse, or full, with all entries present
//--------------------------------------------------------------
int64_t p ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (GB_AX_MASK (Ax, p, asize))
{
// Cx [p] = Ax [p]
GB_COPY_A_TO_C (Cx, p, Ax, p, false) ;
}
}
}
}
else if (A_is_bitmap)
{
//------------------------------------------------------------------
// A is bitmap
//------------------------------------------------------------------
if (C_is_bitmap)
{
//-------------------------------------------------------------
// C is bitmap, A is bitmap
//--------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static) reduction(+:cnvals)
for (tid = 0 ; tid < A_nthreads ; tid++)
{
int64_t pA_start, pA_end, task_cnvals = 0 ;
GB_PARTITION (pA_start, pA_end, anz, tid, A_nthreads) ;
for (int64_t p = pA_start ; p < pA_end ; p++)
{
if (Ab [p] && GB_AX_MASK (Ax, p, asize))
{
// Cx [p] = Ax [p]
GB_COPY_A_TO_C (Cx, p, Ax, p, false) ;
task_cnvals += (Cb [p] == 0) ;
Cb [p] = 1 ;
}
}
cnvals += task_cnvals ;
}
}
else
{
//--------------------------------------------------------------
// C is hypersparse, sparse, or full, with all entries present
//--------------------------------------------------------------
int64_t p ;
#pragma omp parallel for num_threads(A_nthreads) \
schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (Ab [p] && GB_AX_MASK (Ax, p, asize))
{
// Cx [p] = Ax [p]
GB_COPY_A_TO_C (Cx, p, Ax, p, false) ;
}
}
}
}
else
{
//------------------------------------------------------------------
// A is hypersparse or sparse; C is dense or a bitmap
//------------------------------------------------------------------
const int64_t *restrict kfirst_Aslice = A_ek_slicing ;
const int64_t *restrict klast_Aslice = A_ek_slicing + A_ntasks ;
const int64_t *restrict pstart_Aslice = A_ek_slicing + A_ntasks * 2;
int taskid ;
if (C_is_bitmap)
{
//--------------------------------------------------------------
// C is bitmap
//--------------------------------------------------------------
#pragma omp parallel for num_threads(A_nthreads) \
schedule(dynamic,1) reduction(+:cnvals)
for (taskid = 0 ; taskid < A_ntasks ; taskid++)
{
// if kfirst > klast then taskid does no work at all
int64_t kfirst = kfirst_Aslice [taskid] ;
int64_t klast = klast_Aslice [taskid] ;
int64_t task_cnvals = 0 ;
// C<A(:,kfirst:klast)> = A(:,kfirst:klast)
for (int64_t k = kfirst ; k <= klast ; k++)
{
// get A(:,j), the kth vector of A
int64_t j = GBH (Ah, k) ;
int64_t pA_start, pA_end ;
GB_get_pA (&pA_start, &pA_end, taskid, k,
kfirst, klast, pstart_Aslice, Ap, avlen) ;
// pC is the start of C(:,j)
int64_t pC = j * cvlen ;
// C<A(:,j),struct>=A(:,j) with C bitmap, A sparse
GB_PRAGMA_SIMD_REDUCTION (+,task_cnvals)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
if (GB_AX_MASK (Ax, pA, asize))
{
int64_t p = pC + Ai [pA] ;
// Cx [p] = Ax [pA]
GB_COPY_A_TO_C (Cx, p, Ax, pA, A_iso) ;
task_cnvals += (Cb [p] == 0) ;
Cb [p] = 1 ;
}
}
}
cnvals += task_cnvals ;
}
}
else
{
//--------------------------------------------------------------
// C is full
//--------------------------------------------------------------
#pragma omp parallel for num_threads(A_nthreads) \
schedule(dynamic,1) reduction(+:cnvals)
for (taskid = 0 ; taskid < A_ntasks ; taskid++)
{
// if kfirst > klast then taskid does no work at all
int64_t kfirst = kfirst_Aslice [taskid] ;
int64_t klast = klast_Aslice [taskid] ;
// C<A(:,kfirst:klast)> = A(:,kfirst:klast)
for (int64_t k = kfirst ; k <= klast ; k++)
{
// get A(:,j), the kth vector of A
int64_t j = GBH (Ah, k) ;
int64_t pA_start, pA_end ;
GB_get_pA (&pA_start, &pA_end, taskid, k,
kfirst, klast, pstart_Aslice, Ap, avlen) ;
// pC is the start of C(:,j)
int64_t pC = j * cvlen ;
// C<A(:,j),struct>=A(:,j) with C dense, A sparse
GB_PRAGMA_SIMD_VECTORIZE
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
if (GB_AX_MASK (Ax, pA, asize))
{
int64_t p = pC + Ai [pA] ;
// Cx [p] = Ax [pA]
GB_COPY_A_TO_C (Cx, p, Ax, pA, A_iso) ;
}
}
}
}
}
}
}
#endif
//--------------------------------------------------------------------------
// log the number of entries in the C bitmap
//--------------------------------------------------------------------------
if (C_is_bitmap)
{
C->nvals = cnvals ;
}
}
#undef GB_ISO_ASSIGN
|
single_helper_thread.c | // RUN: %libomp-compile && env LIBOMP_NUM_HIDDEN_HELPER_THREADS=1 %libomp-run
// The test checks that "devide-by-0" bug fixed in runtime.
// The fix is to increment number of threads by 1 if positive,
// so that operation
// (gtid) % (__kmp_hidden_helper_threads_num - 1)
// does not cause crash.
#include <stdio.h>
#include <omp.h>
int main(){
#pragma omp target nowait
{
printf("----- in target region\n");
}
printf("------ before taskwait\n");
#pragma omp taskwait
printf("passed\n");
return 0;
}
|
pattern_matching.c | /*
* Lucas Bergmann e Ricardo Somariva
* Programação Paralela 2018/2
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <omp.h>
/**
* Disponível em: https://www.geeksforgeeks.org/wildcard-character-matching/
*/
// The main function that checks if two given strings
// match. The first string may contain wildcard characters
bool match(char *first, char * second) {
// If we reach at the end of both strings, we are done
if (*first == '\0' && *second == '\0')
return true;
// Make sure that the characters after '*' are present
// in second string. This function assumes that the first
// string will not contain two consecutive '*'
if (*first == '*' && *(first+1) != '\0' && *second == '\0')
return false;
// If the first string contains '?', or current characters
// of both strings match
if (*first == '?' || *first == *second)
return match(first+1, second+1);
// If there is *, then there are two possibilities
// a) We consider current character of second string
// b) We ignore current character of second string.
if (*first == '*')
return match(first+1, second) || match(first, second+1);
return false;
}
/**
* Disponível em: https://stackoverflow.com/questions/1841758/how-to-remove-punctuation-from-a-string-in-c?noredirect=1&lq=1
*/
void remove_punct_and_make_lower_case(char *p) {
char *src = p, *dst = p;
while (*src) {
if (ispunct((unsigned char)*src)) {
/* Skip this character */
src++;
} else if (isupper((unsigned char)*src)) {
/* Make it lowercase */
*dst++ = tolower((unsigned char)*src);
src++;
} else if (src == dst) {
/* Increment both pointers without copying */
src++;
dst++;
} else {
/* Copy character */
*dst++ = *src++;
}
}
*dst = 0;
}
int main(void) {
/* declare a file pointer */
FILE *infile;
char *buffer;
long numbytes;
char pattern[100];
char *array[400000];
/* open an existing file for reading */
infile = fopen("texto.txt", "r");
/* quit if the file does not exist */
if(infile == NULL)
return 1;
/* Get the number of bytes */
fseek(infile, 0L, SEEK_END);
numbytes = ftell(infile);
/* reset the file position indicator to
the beginning of the file */
fseek(infile, 0L, SEEK_SET);
/* grab sufficient memory for the
buffer to hold the text */
buffer = (char*)calloc(numbytes, sizeof(char));
/* memory error */
if(buffer == NULL)
return 1;
/* copy all the text into the buffer */
fread(buffer, sizeof(char), numbytes, infile);
fclose(infile);
printf("WILDCARD PATTERN MATCHING");
printf("\n\n\nDigite o padrão desejado: ");
scanf("%s", pattern);
printf("\n\n");
char * line = strtok(strdup(buffer), "\n");
int numLines = 0;
// Este loop serve p/ popular o array e contar o numero de linhas do texto p/ utilizar no for paralelizado
while(line != NULL) {
remove_punct_and_make_lower_case(line);
array[numLines] = line;
line = strtok(NULL, "\n");
numLines++;
}
// Início da execução
clock_t timeStart = clock();
// Pode-se utilizar este comando para setar o numero de threads
// ao invés de variáveis de ambiente
//omp_set_num_threads(4);
printf("LINHAS QUE OCORREU O PADRÃO\n");
int numPatternFound = 0;
char linhaChar[100];
int i = 0;
#pragma omp parallel
{
#pragma omp for reduction(+:numPatternFound)
for(int i = 0; i < numLines; i++) {
if(match(pattern, array[i])) {
printf("%d: %s\n", i, array[i]);
numPatternFound++;
}
}
}
// Fim da execução
clock_t timeFinish = clock();
// Calcula a diferença de tempo
double executionTime = (double)(timeFinish - timeStart) / CLOCKS_PER_SEC;
printf("\n\n");
printf("TEMPO DE EXECUÇÃO: %lf\n", executionTime);
printf("O PADRÃO OCORREU %d VEZES\n", numPatternFound);
printf("\nFIM DA EXECUÇÃO\n");
free(buffer);
return 0;
} |
3d25pt_var.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 32;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=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-254,256)),ceild(3*t1-510,512)),ceild(24*t2-Nz-2035,2048)),ceild(32*t3-Ny-2035,2048));t4<=min(min(min(min(floord(4*Nt+Nx-9,2048),floord(12*t1+Nx+15,2048)),floord(24*t2+Nx+11,2048)),floord(32*t3+Nx+19,2048)),floord(24*t1-24*t2+Nz+Nx+13,2048));t4++) {
for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(2048*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),512*t4+510);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(2048*t4,4*t5+4);
ubv=min(2048*t4+2047,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
3d25pt.c | /*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
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);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*(
coef0* A[t%2][i ][j ][k ] +
coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] +
A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] +
A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) +
coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] +
A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] +
A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) +
coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] +
A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] +
A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) +
coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] +
A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] +
A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) );
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
csr.c | /*!
* \file
*
* \brief Various routines with dealing with CSR matrices
*
* \author George Karypis
* \version\verbatim $Id: csr.c 15599 2013-10-19 18:17:33Z karypis $ \endverbatim
*/
#include <GKlib.h>
#define OMPMINOPS 50000
/*************************************************************************/
/*! Allocate memory for a CSR matrix and initializes it
\returns the allocated matrix. The various fields are set to NULL.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Create()
{
gk_csr_t *mat;
mat = (gk_csr_t *)gk_malloc(sizeof(gk_csr_t), "gk_csr_Create: mat");
gk_csr_Init(mat);
return mat;
}
/*************************************************************************/
/*! Initializes the matrix
\param mat is the matrix to be initialized.
*/
/*************************************************************************/
void gk_csr_Init(gk_csr_t *mat)
{
memset(mat, 0, sizeof(gk_csr_t));
mat->nrows = mat->ncols = -1;
}
/*************************************************************************/
/*! Frees all the memory allocated for matrix.
\param mat is the matrix to be freed.
*/
/*************************************************************************/
void gk_csr_Free(gk_csr_t **mat)
{
if (*mat == NULL)
return;
gk_csr_FreeContents(*mat);
gk_free((void **)mat, LTERM);
}
/*************************************************************************/
/*! Frees only the memory allocated for the matrix's different fields and
sets them to NULL.
\param mat is the matrix whose contents will be freed.
*/
/*************************************************************************/
void gk_csr_FreeContents(gk_csr_t *mat)
{
gk_free((void *)&mat->rowptr, &mat->rowind, &mat->rowval, &mat->rowids,
&mat->colptr, &mat->colind, &mat->colval, &mat->colids,
&mat->rnorms, &mat->cnorms, &mat->rsums, &mat->csums,
&mat->rsizes, &mat->csizes, &mat->rvols, &mat->cvols,
&mat->rwgts, &mat->cwgts,
LTERM);
}
/*************************************************************************/
/*! Returns a copy of a matrix.
\param mat is the matrix to be duplicated.
\returns the newly created copy of the matrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Dup(gk_csr_t *mat)
{
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = mat->nrows;
nmat->ncols = mat->ncols;
/* copy the row structure */
if (mat->rowptr)
nmat->rowptr = gk_zcopy(mat->nrows+1, mat->rowptr,
gk_zmalloc(mat->nrows+1, "gk_csr_Dup: rowptr"));
if (mat->rowids)
nmat->rowids = gk_icopy(mat->nrows, mat->rowids,
gk_imalloc(mat->nrows, "gk_csr_Dup: rowids"));
if (mat->rnorms)
nmat->rnorms = gk_fcopy(mat->nrows, mat->rnorms,
gk_fmalloc(mat->nrows, "gk_csr_Dup: rnorms"));
if (mat->rowind)
nmat->rowind = gk_icopy(mat->rowptr[mat->nrows], mat->rowind,
gk_imalloc(mat->rowptr[mat->nrows], "gk_csr_Dup: rowind"));
if (mat->rowval)
nmat->rowval = gk_fcopy(mat->rowptr[mat->nrows], mat->rowval,
gk_fmalloc(mat->rowptr[mat->nrows], "gk_csr_Dup: rowval"));
/* copy the col structure */
if (mat->colptr)
nmat->colptr = gk_zcopy(mat->ncols+1, mat->colptr,
gk_zmalloc(mat->ncols+1, "gk_csr_Dup: colptr"));
if (mat->colids)
nmat->colids = gk_icopy(mat->ncols, mat->colids,
gk_imalloc(mat->ncols, "gk_csr_Dup: colids"));
if (mat->cnorms)
nmat->cnorms = gk_fcopy(mat->ncols, mat->cnorms,
gk_fmalloc(mat->ncols, "gk_csr_Dup: cnorms"));
if (mat->colind)
nmat->colind = gk_icopy(mat->colptr[mat->ncols], mat->colind,
gk_imalloc(mat->colptr[mat->ncols], "gk_csr_Dup: colind"));
if (mat->colval)
nmat->colval = gk_fcopy(mat->colptr[mat->ncols], mat->colval,
gk_fmalloc(mat->colptr[mat->ncols], "gk_csr_Dup: colval"));
return nmat;
}
/*************************************************************************/
/*! Returns a submatrix containint a set of consecutive rows.
\param mat is the original matrix.
\param rstart is the starting row.
\param nrows is the number of rows from rstart to extract.
\returns the row structure of the newly created submatrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ExtractSubmatrix(gk_csr_t *mat, int rstart, int nrows)
{
ssize_t i;
gk_csr_t *nmat;
if (rstart+nrows > mat->nrows)
return NULL;
nmat = gk_csr_Create();
nmat->nrows = nrows;
nmat->ncols = mat->ncols;
/* copy the row structure */
if (mat->rowptr)
nmat->rowptr = gk_zcopy(nrows+1, mat->rowptr+rstart,
gk_zmalloc(nrows+1, "gk_csr_ExtractSubmatrix: rowptr"));
for (i=nrows; i>=0; i--)
nmat->rowptr[i] -= nmat->rowptr[0];
ASSERT(nmat->rowptr[0] == 0);
if (mat->rowids)
nmat->rowids = gk_icopy(nrows, mat->rowids+rstart,
gk_imalloc(nrows, "gk_csr_ExtractSubmatrix: rowids"));
if (mat->rnorms)
nmat->rnorms = gk_fcopy(nrows, mat->rnorms+rstart,
gk_fmalloc(nrows, "gk_csr_ExtractSubmatrix: rnorms"));
if (mat->rsums)
nmat->rsums = gk_fcopy(nrows, mat->rsums+rstart,
gk_fmalloc(nrows, "gk_csr_ExtractSubmatrix: rsums"));
ASSERT(nmat->rowptr[nrows] == mat->rowptr[rstart+nrows]-mat->rowptr[rstart]);
if (mat->rowind)
nmat->rowind = gk_icopy(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
mat->rowind+mat->rowptr[rstart],
gk_imalloc(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
"gk_csr_ExtractSubmatrix: rowind"));
if (mat->rowval)
nmat->rowval = gk_fcopy(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
mat->rowval+mat->rowptr[rstart],
gk_fmalloc(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
"gk_csr_ExtractSubmatrix: rowval"));
return nmat;
}
/*************************************************************************/
/*! Returns a submatrix containing a certain set of rows.
\param mat is the original matrix.
\param nrows is the number of rows to extract.
\param rind is the set of row numbers to extract.
\returns the row structure of the newly created submatrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ExtractRows(gk_csr_t *mat, int nrows, int *rind)
{
ssize_t i, ii, j, nnz;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = nrows;
nmat->ncols = mat->ncols;
for (nnz=0, i=0; i<nrows; i++)
nnz += mat->rowptr[rind[i]+1]-mat->rowptr[rind[i]];
nmat->rowptr = gk_zmalloc(nmat->nrows+1, "gk_csr_ExtractPartition: rowptr");
nmat->rowind = gk_imalloc(nnz, "gk_csr_ExtractPartition: rowind");
nmat->rowval = gk_fmalloc(nnz, "gk_csr_ExtractPartition: rowval");
nmat->rowptr[0] = 0;
for (nnz=0, j=0, ii=0; ii<nrows; ii++) {
i = rind[ii];
gk_icopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowind+mat->rowptr[i], nmat->rowind+nnz);
gk_fcopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowval+mat->rowptr[i], nmat->rowval+nnz);
nnz += mat->rowptr[i+1]-mat->rowptr[i];
nmat->rowptr[++j] = nnz;
}
ASSERT(j == nmat->nrows);
return nmat;
}
/*************************************************************************/
/*! Returns a submatrix corresponding to a specified partitioning of rows.
\param mat is the original matrix.
\param part is the partitioning vector of the rows.
\param pid is the partition ID that will be extracted.
\returns the row structure of the newly created submatrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ExtractPartition(gk_csr_t *mat, int *part, int pid)
{
ssize_t i, j, nnz;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = 0;
nmat->ncols = mat->ncols;
for (nnz=0, i=0; i<mat->nrows; i++) {
if (part[i] == pid) {
nmat->nrows++;
nnz += mat->rowptr[i+1]-mat->rowptr[i];
}
}
nmat->rowptr = gk_zmalloc(nmat->nrows+1, "gk_csr_ExtractPartition: rowptr");
nmat->rowind = gk_imalloc(nnz, "gk_csr_ExtractPartition: rowind");
nmat->rowval = gk_fmalloc(nnz, "gk_csr_ExtractPartition: rowval");
nmat->rowptr[0] = 0;
for (nnz=0, j=0, i=0; i<mat->nrows; i++) {
if (part[i] == pid) {
gk_icopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowind+mat->rowptr[i], nmat->rowind+nnz);
gk_fcopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowval+mat->rowptr[i], nmat->rowval+nnz);
nnz += mat->rowptr[i+1]-mat->rowptr[i];
nmat->rowptr[++j] = nnz;
}
}
ASSERT(j == nmat->nrows);
return nmat;
}
/*************************************************************************/
/*! Splits the matrix into multiple sub-matrices based on the provided
color array.
\param mat is the original matrix.
\param color is an array of size equal to the number of non-zeros
in the matrix (row-wise structure). The matrix is split into
as many parts as the number of colors. For meaningfull results,
the colors should be numbered consecutively starting from 0.
\returns an array of matrices for each supplied color number.
*/
/**************************************************************************/
gk_csr_t **gk_csr_Split(gk_csr_t *mat, int *color)
{
ssize_t i, j;
int nrows, ncolors;
ssize_t *rowptr;
int *rowind;
float *rowval;
gk_csr_t **smats;
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
ncolors = gk_imax(rowptr[nrows], color)+1;
smats = (gk_csr_t **)gk_malloc(sizeof(gk_csr_t *)*ncolors, "gk_csr_Split: smats");
for (i=0; i<ncolors; i++) {
smats[i] = gk_csr_Create();
smats[i]->nrows = mat->nrows;
smats[i]->ncols = mat->ncols;
smats[i]->rowptr = gk_zsmalloc(nrows+1, 0, "gk_csr_Split: smats[i]->rowptr");
}
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
smats[color[j]]->rowptr[i]++;
}
for (i=0; i<ncolors; i++)
MAKECSR(j, nrows, smats[i]->rowptr);
for (i=0; i<ncolors; i++) {
smats[i]->rowind = gk_imalloc(smats[i]->rowptr[nrows], "gk_csr_Split: smats[i]->rowind");
smats[i]->rowval = gk_fmalloc(smats[i]->rowptr[nrows], "gk_csr_Split: smats[i]->rowval");
}
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
smats[color[j]]->rowind[smats[color[j]]->rowptr[i]] = rowind[j];
smats[color[j]]->rowval[smats[color[j]]->rowptr[i]] = rowval[j];
smats[color[j]]->rowptr[i]++;
}
}
for (i=0; i<ncolors; i++)
SHIFTCSR(j, nrows, smats[i]->rowptr);
return smats;
}
/**************************************************************************/
/*! Reads a CSR matrix from the supplied file and stores it the matrix's
forward structure.
\param filename is the file that stores the data.
\param format is either GK_CSR_FMT_METIS, GK_CSR_FMT_CLUTO,
GK_CSR_FMT_CSR, GK_CSR_FMT_BINROW, GK_CSR_FMT_BINCOL
specifying the type of the input format.
The GK_CSR_FMT_CSR does not contain a header
line, whereas the GK_CSR_FMT_BINROW is a binary format written
by gk_csr_Write() using the same format specifier.
\param readvals is either 1 or 0, indicating if the CSR file contains
values or it does not. It only applies when GK_CSR_FMT_CSR is
used.
\param numbering is either 1 or 0, indicating if the numbering of the
indices start from 1 or 0, respectively. If they start from 1,
they are automatically decreamented during input so that they
will start from 0. It only applies when GK_CSR_FMT_CSR is
used.
\returns the matrix that was read.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Read(char *filename, int format, int readvals, int numbering)
{
ssize_t i, k, l;
size_t nfields, nrows, ncols, nnz, fmt, ncon;
size_t lnlen;
ssize_t *rowptr;
int *rowind, *iinds, *jinds, ival;
float *rowval=NULL, *vals, fval;
int readsizes, readwgts;
char *line=NULL, *head, *tail, fmtstr[256];
FILE *fpin;
gk_csr_t *mat=NULL;
if (!gk_fexists(filename))
gk_errexit(SIGERR, "File %s does not exist!\n", filename);
switch (format) {
case GK_CSR_FMT_BINROW:
mat = gk_csr_Create();
fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin");
if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename);
if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename);
mat->rowptr = gk_zmalloc(mat->nrows+1, "gk_csr_Read: rowptr");
if (fread(mat->rowptr, sizeof(ssize_t), mat->nrows+1, fpin) != mat->nrows+1)
gk_errexit(SIGERR, "Failed to read the rowptr from file %s!\n", filename);
mat->rowind = gk_imalloc(mat->rowptr[mat->nrows], "gk_csr_Read: rowind");
if (fread(mat->rowind, sizeof(int32_t), mat->rowptr[mat->nrows], fpin) != mat->rowptr[mat->nrows])
gk_errexit(SIGERR, "Failed to read the rowind from file %s!\n", filename);
if (readvals == 1) {
mat->rowval = gk_fmalloc(mat->rowptr[mat->nrows], "gk_csr_Read: rowval");
if (fread(mat->rowval, sizeof(float), mat->rowptr[mat->nrows], fpin) != mat->rowptr[mat->nrows])
gk_errexit(SIGERR, "Failed to read the rowval from file %s!\n", filename);
}
gk_fclose(fpin);
return mat;
break;
case GK_CSR_FMT_BINCOL:
mat = gk_csr_Create();
fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin");
if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename);
if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename);
mat->colptr = gk_zmalloc(mat->ncols+1, "gk_csr_Read: colptr");
if (fread(mat->colptr, sizeof(ssize_t), mat->ncols+1, fpin) != mat->ncols+1)
gk_errexit(SIGERR, "Failed to read the colptr from file %s!\n", filename);
mat->colind = gk_imalloc(mat->colptr[mat->ncols], "gk_csr_Read: colind");
if (fread(mat->colind, sizeof(int32_t), mat->colptr[mat->ncols], fpin) != mat->colptr[mat->ncols])
gk_errexit(SIGERR, "Failed to read the colind from file %s!\n", filename);
if (readvals) {
mat->colval = gk_fmalloc(mat->colptr[mat->ncols], "gk_csr_Read: colval");
if (fread(mat->colval, sizeof(float), mat->colptr[mat->ncols], fpin) != mat->colptr[mat->ncols])
gk_errexit(SIGERR, "Failed to read the colval from file %s!\n", filename);
}
gk_fclose(fpin);
return mat;
break;
case GK_CSR_FMT_IJV:
gk_getfilestats(filename, &nrows, &nnz, NULL, NULL);
if (readvals == 1 && 3*nrows != nnz)
gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not a multiple of 3.\n", nnz, readvals);
if (readvals == 0 && 2*nrows != nnz)
gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not a multiple of 2.\n", nnz, readvals);
nnz = nrows;
numbering = (numbering ? - 1 : 0);
/* read the data into three arrays */
iinds = gk_i32malloc(nnz, "iinds");
jinds = gk_i32malloc(nnz, "jinds");
vals = (readvals ? gk_fmalloc(nnz, "vals") : NULL);
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
for (nrows=0, ncols=0, i=0; i<nnz; i++) {
if (readvals) {
if (fscanf(fpin, "%d %d %f", &iinds[i], &jinds[i], &vals[i]) != 3)
gk_errexit(SIGERR, "Error: Failed to read (i, j, val) for nnz: %zd.\n", i);
}
else {
if (fscanf(fpin, "%d %d", &iinds[i], &jinds[i]) != 2)
gk_errexit(SIGERR, "Error: Failed to read (i, j) value for nnz: %zd.\n", i);
}
iinds[i] += numbering;
jinds[i] += numbering;
if (nrows < iinds[i])
nrows = iinds[i];
if (ncols < jinds[i])
ncols = jinds[i];
}
nrows++;
ncols++;
gk_fclose(fpin);
/* convert (i, j, v) into a CSR matrix */
mat = gk_csr_Create();
mat->nrows = nrows;
mat->ncols = ncols;
rowptr = mat->rowptr = gk_zsmalloc(nrows+1, 0, "rowptr");
rowind = mat->rowind = gk_i32malloc(nnz, "rowind");
if (readvals)
rowval = mat->rowval = gk_fmalloc(nnz, "rowval");
for (i=0; i<nnz; i++)
rowptr[iinds[i]]++;
MAKECSR(i, nrows, rowptr);
for (i=0; i<nnz; i++) {
rowind[rowptr[iinds[i]]] = jinds[i];
if (readvals)
rowval[rowptr[iinds[i]]] = vals[i];
rowptr[iinds[i]]++;
}
SHIFTCSR(i, nrows, rowptr);
gk_free((void **)&iinds, &jinds, &vals, LTERM);
return mat;
break;
case GK_CSR_FMT_BIJV:
mat = gk_csr_Create();
fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin");
if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename);
if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename);
if (fread(&nnz, sizeof(size_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the nnz from file %s!\n", filename);
if (fread(&readvals, sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the readvals from file %s!\n", filename);
/* read the data into three arrays */
iinds = gk_i32malloc(nnz, "iinds");
jinds = gk_i32malloc(nnz, "jinds");
vals = (readvals ? gk_fmalloc(nnz, "vals") : NULL);
for (i=0; i<nnz; i++) {
if (fread(&(iinds[i]), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read iinds[i] from file %s!\n", filename);
if (fread(&(jinds[i]), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read jinds[i] from file %s!\n", filename);
if (readvals) {
if (fread(&(vals[i]), sizeof(float), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read vals[i] from file %s!\n", filename);
}
//printf("%d %d\n", iinds[i], jinds[i]);
}
gk_fclose(fpin);
/* convert (i, j, v) into a CSR matrix */
rowptr = mat->rowptr = gk_zsmalloc(mat->nrows+1, 0, "rowptr");
rowind = mat->rowind = gk_i32malloc(nnz, "rowind");
if (readvals)
rowval = mat->rowval = gk_fmalloc(nnz, "rowval");
for (i=0; i<nnz; i++)
rowptr[iinds[i]]++;
MAKECSR(i, mat->nrows, rowptr);
for (i=0; i<nnz; i++) {
rowind[rowptr[iinds[i]]] = jinds[i];
if (readvals)
rowval[rowptr[iinds[i]]] = vals[i];
rowptr[iinds[i]]++;
}
SHIFTCSR(i, mat->nrows, rowptr);
gk_free((void **)&iinds, &jinds, &vals, LTERM);
return mat;
break;
/* the following are handled by a common input code, that comes after the switch */
case GK_CSR_FMT_CLUTO:
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
do {
if (gk_getline(&line, &lnlen, fpin) <= 0)
gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename);
} while (line[0] == '%');
if (sscanf(line, "%zu %zu %zu", &nrows, &ncols, &nnz) != 3)
gk_errexit(SIGERR, "Header line must contain 3 integers.\n");
readsizes = 0;
readwgts = 0;
readvals = 1;
numbering = 1;
break;
case GK_CSR_FMT_METIS:
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
do {
if (gk_getline(&line, &lnlen, fpin) <= 0)
gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename);
} while (line[0] == '%');
fmt = ncon = 0;
nfields = sscanf(line, "%zu %zu %zu %zu", &nrows, &nnz, &fmt, &ncon);
if (nfields < 2)
gk_errexit(SIGERR, "Header line must contain at least 2 integers (#vtxs and #edges).\n");
ncols = nrows;
nnz *= 2;
if (fmt > 111)
gk_errexit(SIGERR, "Cannot read this type of file format [fmt=%zu]!\n", fmt);
sprintf(fmtstr, "%03zu", fmt%1000);
readsizes = (fmtstr[0] == '1');
readwgts = (fmtstr[1] == '1');
readvals = (fmtstr[2] == '1');
numbering = 1;
ncon = (ncon == 0 ? 1 : ncon);
break;
case GK_CSR_FMT_CSR:
readsizes = 0;
readwgts = 0;
gk_getfilestats(filename, &nrows, &nnz, NULL, NULL);
if (readvals == 1 && nnz%2 == 1)
gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not even.\n", nnz, readvals);
if (readvals == 1)
nnz = nnz/2;
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
break;
default:
gk_errexit(SIGERR, "Unknown csr format.\n");
return NULL;
}
mat = gk_csr_Create();
mat->nrows = nrows;
rowptr = mat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Read: rowptr");
rowind = mat->rowind = gk_imalloc(nnz, "gk_csr_Read: rowind");
if (readvals != 2)
rowval = mat->rowval = gk_fsmalloc(nnz, 1.0, "gk_csr_Read: rowval");
if (readsizes)
mat->rsizes = gk_fsmalloc(nrows, 0.0, "gk_csr_Read: rsizes");
if (readwgts)
mat->rwgts = gk_fsmalloc(nrows*ncon, 0.0, "gk_csr_Read: rwgts");
/*----------------------------------------------------------------------
* Read the sparse matrix file
*---------------------------------------------------------------------*/
numbering = (numbering ? -1 : 0);
for (ncols=0, rowptr[0]=0, k=0, i=0; i<nrows; i++) {
do {
if (gk_getline(&line, &lnlen, fpin) == -1)
gk_errexit(SIGERR, "Premature end of input file: file while reading row %d\n", i);
} while (line[0] == '%');
head = line;
tail = NULL;
/* Read vertex sizes */
if (readsizes) {
#ifdef __MSC__
mat->rsizes[i] = (float)strtod(head, &tail);
#else
mat->rsizes[i] = strtof(head, &tail);
#endif
if (tail == head)
gk_errexit(SIGERR, "The line for vertex %zd does not have size information\n", i+1);
if (mat->rsizes[i] < 0)
errexit("The size for vertex %zd must be >= 0\n", i+1);
head = tail;
}
/* Read vertex weights */
if (readwgts) {
for (l=0; l<ncon; l++) {
#ifdef __MSC__
mat->rwgts[i*ncon+l] = (float)strtod(head, &tail);
#else
mat->rwgts[i*ncon+l] = strtof(head, &tail);
#endif
if (tail == head)
errexit("The line for vertex %zd does not have enough weights "
"for the %d constraints.\n", i+1, ncon);
if (mat->rwgts[i*ncon+l] < 0)
errexit("The weight vertex %zd and constraint %zd must be >= 0\n", i+1, l);
head = tail;
}
}
/* Read the rest of the row */
while (1) {
ival = (int)strtol(head, &tail, 0);
if (tail == head)
break;
head = tail;
if ((rowind[k] = ival + numbering) < 0)
gk_errexit(SIGERR, "Error: Invalid column number %d at row %zd.\n", ival, i);
ncols = gk_max(rowind[k], ncols);
if (readvals == 1) {
#ifdef __MSC__
fval = (float)strtod(head, &tail);
#else
fval = strtof(head, &tail);
#endif
if (tail == head)
gk_errexit(SIGERR, "Value could not be found for column! Row:%zd, NNZ:%zd\n", i, k);
head = tail;
rowval[k] = fval;
}
k++;
}
rowptr[i+1] = k;
}
if (format == GK_CSR_FMT_METIS) {
ASSERT(ncols+1 == mat->nrows);
mat->ncols = mat->nrows;
}
else {
mat->ncols = ncols+1;
}
if (k != nnz)
gk_errexit(SIGERR, "gk_csr_Read: Something wrong with the number of nonzeros in "
"the input file. NNZ=%zd, ActualNNZ=%zd.\n", nnz, k);
gk_fclose(fpin);
gk_free((void **)&line, LTERM);
return mat;
}
/**************************************************************************/
/*! Writes the row-based structure of a matrix into a file.
\param mat is the matrix to be written,
\param filename is the name of the output file.
\param format is one of: GK_CSR_FMT_CLUTO, GK_CSR_FMT_CSR,
GK_CSR_FMT_BINROW, GK_CSR_FMT_BINCOL, GK_CSR_FMT_BIJV.
\param writevals is either 1 or 0 indicating if the values will be
written or not. This is only applicable when GK_CSR_FMT_CSR
is used.
\param numbering is either 1 or 0 indicating if the internal 0-based
numbering will be shifted by one or not during output. This
is only applicable when GK_CSR_FMT_CSR is used.
*/
/**************************************************************************/
void gk_csr_Write(gk_csr_t *mat, char *filename, int format, int writevals, int numbering)
{
ssize_t i, j;
int32_t edge[2];
FILE *fpout;
switch (format) {
case GK_CSR_FMT_METIS:
if (mat->nrows != mat->ncols || mat->rowptr[mat->nrows]%2 == 1)
gk_errexit(SIGERR, "METIS output format requires a square symmetric matrix.\n");
if (filename)
fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout");
else
fpout = stdout;
fprintf(fpout, "%d %zd\n", mat->nrows, mat->rowptr[mat->nrows]/2);
for (i=0; i<mat->nrows; i++) {
for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++)
fprintf(fpout, " %d", mat->rowind[j]+1);
fprintf(fpout, "\n");
}
if (filename)
gk_fclose(fpout);
break;
case GK_CSR_FMT_BINROW:
if (filename == NULL)
gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n");
fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout");
fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout);
fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout);
fwrite(mat->rowptr, sizeof(ssize_t), mat->nrows+1, fpout);
fwrite(mat->rowind, sizeof(int32_t), mat->rowptr[mat->nrows], fpout);
if (writevals)
fwrite(mat->rowval, sizeof(float), mat->rowptr[mat->nrows], fpout);
gk_fclose(fpout);
return;
break;
case GK_CSR_FMT_BINCOL:
if (filename == NULL)
gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n");
fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout");
fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout);
fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout);
fwrite(mat->colptr, sizeof(ssize_t), mat->ncols+1, fpout);
fwrite(mat->colind, sizeof(int32_t), mat->colptr[mat->ncols], fpout);
if (writevals)
fwrite(mat->colval, sizeof(float), mat->colptr[mat->ncols], fpout);
gk_fclose(fpout);
return;
break;
case GK_CSR_FMT_IJV:
if (filename == NULL)
gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n");
fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout");
numbering = (numbering ? 1 : 0);
for (i=0; i<mat->nrows; i++) {
for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) {
if (writevals)
fprintf(fpout, "%zd %d %.8f\n", i+numbering, mat->rowind[j]+numbering, mat->rowval[j]);
else
fprintf(fpout, "%zd %d\n", i+numbering, mat->rowind[j]+numbering);
}
}
gk_fclose(fpout);
return;
break;
case GK_CSR_FMT_BIJV:
if (filename == NULL)
gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n");
fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout");
fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout);
fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout);
fwrite(&(mat->rowptr[mat->nrows]), sizeof(size_t), 1, fpout);
fwrite(&writevals, sizeof(int32_t), 1, fpout);
for (i=0; i<mat->nrows; i++) {
edge[0] = i;
for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) {
edge[1] = mat->rowind[j];
fwrite(edge, sizeof(int32_t), 2, fpout);
if (writevals)
fwrite(&(mat->rowval[j]), sizeof(float), 1, fpout);
}
}
gk_fclose(fpout);
return;
break;
default:
if (filename)
fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout");
else
fpout = stdout;
if (format == GK_CSR_FMT_CLUTO) {
fprintf(fpout, "%d %d %zd\n", mat->nrows, mat->ncols, mat->rowptr[mat->nrows]);
writevals = 1;
numbering = 1;
}
for (i=0; i<mat->nrows; i++) {
for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) {
fprintf(fpout, " %d", mat->rowind[j]+(numbering ? 1 : 0));
if (writevals)
fprintf(fpout, " %f", mat->rowval[j]);
}
fprintf(fpout, "\n");
}
if (filename)
gk_fclose(fpout);
}
}
/*************************************************************************/
/*! Prunes certain rows/columns of the matrix. The prunning takes place
by analyzing the row structure of the matrix. The prunning takes place
by removing rows/columns but it does not affect the numbering of the
remaining rows/columns.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param minf is the minimum number of rows (columns) that a column (row) must
be present in order to be kept,
\param maxf is the maximum number of rows (columns) that a column (row) must
be present at in order to be kept.
\returns the prunned matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Prune(gk_csr_t *mat, int what, int minf, int maxf)
{
ssize_t i, j, nnz;
int nrows, ncols;
ssize_t *rowptr, *nrowptr;
int *rowind, *nrowind, *collen;
float *rowval, *nrowval;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nrows = nmat->nrows = mat->nrows;
ncols = nmat->ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Prune: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_Prune: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_Prune: nrowval");
switch (what) {
case GK_CSR_COL:
collen = gk_ismalloc(ncols, 0, "gk_csr_Prune: collen");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
ASSERT(rowind[j] < ncols);
collen[rowind[j]]++;
}
}
for (i=0; i<ncols; i++)
collen[i] = (collen[i] >= minf && collen[i] <= maxf ? 1 : 0);
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (collen[rowind[j]]) {
nrowind[nnz] = rowind[j];
nrowval[nnz] = rowval[j];
nnz++;
}
}
nrowptr[i+1] = nnz;
}
gk_free((void **)&collen, LTERM);
break;
case GK_CSR_ROW:
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
if (rowptr[i+1]-rowptr[i] >= minf && rowptr[i+1]-rowptr[i] <= maxf) {
for (j=rowptr[i]; j<rowptr[i+1]; j++, nnz++) {
nrowind[nnz] = rowind[j];
nrowval[nnz] = rowval[j];
}
}
nrowptr[i+1] = nnz;
}
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Eliminates certain entries from the rows/columns of the matrix. The
filtering takes place by keeping only the highest weight entries whose
sum accounts for a certain fraction of the overall weight of the
row/column.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param norm indicates the norm that will be used to aggregate the weights
and possible values are 1 or 2,
\param fraction is the fraction of the overall norm that will be retained
by the kept entries.
\returns the filtered matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_LowFilter(gk_csr_t *mat, int what, int norm, float fraction)
{
ssize_t i, j, nnz;
int nrows, ncols, ncand, maxlen=0;
ssize_t *rowptr, *colptr, *nrowptr;
int *rowind, *colind, *nrowind;
float *rowval, *colval, *nrowval, rsum, tsum;
gk_csr_t *nmat;
gk_fkv_t *cand;
nmat = gk_csr_Create();
nrows = nmat->nrows = mat->nrows;
ncols = nmat->ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
colptr = mat->colptr;
colind = mat->colind;
colval = mat->colval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_LowFilter: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_LowFilter: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_LowFilter: nrowval");
switch (what) {
case GK_CSR_COL:
if (mat->colptr == NULL)
gk_errexit(SIGERR, "Cannot filter columns when column-based structure has not been created.\n");
gk_zcopy(nrows+1, rowptr, nrowptr);
for (i=0; i<ncols; i++)
maxlen = gk_max(maxlen, colptr[i+1]-colptr[i]);
#pragma omp parallel private(i, j, ncand, rsum, tsum, cand)
{
cand = gk_fkvmalloc(maxlen, "gk_csr_LowFilter: cand");
#pragma omp for schedule(static)
for (i=0; i<ncols; i++) {
for (tsum=0.0, ncand=0, j=colptr[i]; j<colptr[i+1]; j++, ncand++) {
cand[ncand].val = colind[j];
cand[ncand].key = colval[j];
tsum += (norm == 1 ? colval[j] : colval[j]*colval[j]);
}
gk_fkvsortd(ncand, cand);
for (rsum=0.0, j=0; j<ncand && rsum<=fraction*tsum; j++) {
rsum += (norm == 1 ? cand[j].key : cand[j].key*cand[j].key);
nrowind[nrowptr[cand[j].val]] = i;
nrowval[nrowptr[cand[j].val]] = cand[j].key;
nrowptr[cand[j].val]++;
}
}
gk_free((void **)&cand, LTERM);
}
/* compact the nrowind/nrowval */
for (nnz=0, i=0; i<nrows; i++) {
for (j=rowptr[i]; j<nrowptr[i]; j++, nnz++) {
nrowind[nnz] = nrowind[j];
nrowval[nnz] = nrowval[j];
}
nrowptr[i] = nnz;
}
SHIFTCSR(i, nrows, nrowptr);
break;
case GK_CSR_ROW:
if (mat->rowptr == NULL)
gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n");
for (i=0; i<nrows; i++)
maxlen = gk_max(maxlen, rowptr[i+1]-rowptr[i]);
#pragma omp parallel private(i, j, ncand, rsum, tsum, cand)
{
cand = gk_fkvmalloc(maxlen, "gk_csr_LowFilter: cand");
#pragma omp for schedule(static)
for (i=0; i<nrows; i++) {
for (tsum=0.0, ncand=0, j=rowptr[i]; j<rowptr[i+1]; j++, ncand++) {
cand[ncand].val = rowind[j];
cand[ncand].key = rowval[j];
tsum += (norm == 1 ? rowval[j] : rowval[j]*rowval[j]);
}
gk_fkvsortd(ncand, cand);
for (rsum=0.0, j=0; j<ncand && rsum<=fraction*tsum; j++) {
rsum += (norm == 1 ? cand[j].key : cand[j].key*cand[j].key);
nrowind[rowptr[i]+j] = cand[j].val;
nrowval[rowptr[i]+j] = cand[j].key;
}
nrowptr[i+1] = rowptr[i]+j;
}
gk_free((void **)&cand, LTERM);
}
/* compact nrowind/nrowval */
nrowptr[0] = nnz = 0;
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<nrowptr[i+1]; j++, nnz++) {
nrowind[nnz] = nrowind[j];
nrowval[nnz] = nrowval[j];
}
nrowptr[i+1] = nnz;
}
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Eliminates certain entries from the rows/columns of the matrix. The
filtering takes place by keeping only the highest weight top-K entries
along each row/column and those entries whose weight is greater than
a specified value.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param topk is the number of the highest weight entries to keep.
\param keepval is the weight of a term above which will be kept. This
is used to select additional terms past the first topk.
\returns the filtered matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_TopKPlusFilter(gk_csr_t *mat, int what, int topk, float keepval)
{
ssize_t i, j, k, nnz;
int nrows, ncols, ncand;
ssize_t *rowptr, *colptr, *nrowptr;
int *rowind, *colind, *nrowind;
float *rowval, *colval, *nrowval;
gk_csr_t *nmat;
gk_fkv_t *cand;
nmat = gk_csr_Create();
nrows = nmat->nrows = mat->nrows;
ncols = nmat->ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
colptr = mat->colptr;
colind = mat->colind;
colval = mat->colval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_LowFilter: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_LowFilter: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_LowFilter: nrowval");
switch (what) {
case GK_CSR_COL:
if (mat->colptr == NULL)
gk_errexit(SIGERR, "Cannot filter columns when column-based structure has not been created.\n");
cand = gk_fkvmalloc(nrows, "gk_csr_LowFilter: cand");
gk_zcopy(nrows+1, rowptr, nrowptr);
for (i=0; i<ncols; i++) {
for (ncand=0, j=colptr[i]; j<colptr[i+1]; j++, ncand++) {
cand[ncand].val = colind[j];
cand[ncand].key = colval[j];
}
gk_fkvsortd(ncand, cand);
k = gk_min(topk, ncand);
for (j=0; j<k; j++) {
nrowind[nrowptr[cand[j].val]] = i;
nrowval[nrowptr[cand[j].val]] = cand[j].key;
nrowptr[cand[j].val]++;
}
for (; j<ncand; j++) {
if (cand[j].key < keepval)
break;
nrowind[nrowptr[cand[j].val]] = i;
nrowval[nrowptr[cand[j].val]] = cand[j].key;
nrowptr[cand[j].val]++;
}
}
/* compact the nrowind/nrowval */
for (nnz=0, i=0; i<nrows; i++) {
for (j=rowptr[i]; j<nrowptr[i]; j++, nnz++) {
nrowind[nnz] = nrowind[j];
nrowval[nnz] = nrowval[j];
}
nrowptr[i] = nnz;
}
SHIFTCSR(i, nrows, nrowptr);
gk_free((void **)&cand, LTERM);
break;
case GK_CSR_ROW:
if (mat->rowptr == NULL)
gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n");
cand = gk_fkvmalloc(ncols, "gk_csr_LowFilter: cand");
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
for (ncand=0, j=rowptr[i]; j<rowptr[i+1]; j++, ncand++) {
cand[ncand].val = rowind[j];
cand[ncand].key = rowval[j];
}
gk_fkvsortd(ncand, cand);
k = gk_min(topk, ncand);
for (j=0; j<k; j++, nnz++) {
nrowind[nnz] = cand[j].val;
nrowval[nnz] = cand[j].key;
}
for (; j<ncand; j++, nnz++) {
if (cand[j].key < keepval)
break;
nrowind[nnz] = cand[j].val;
nrowval[nnz] = cand[j].key;
}
nrowptr[i+1] = nnz;
}
gk_free((void **)&cand, LTERM);
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Eliminates certain entries from the rows/columns of the matrix. The
filtering takes place by keeping only the terms whose contribution to
the total length of the document is greater than a user-splied multiple
over the average.
This routine assumes that the vectors are normalized to be unit length.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param zscore is the multiplicative factor over the average contribution
to the length of the document.
\returns the filtered matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ZScoreFilter(gk_csr_t *mat, int what, float zscore)
{
ssize_t i, j, nnz;
int nrows;
ssize_t *rowptr, *nrowptr;
int *rowind, *nrowind;
float *rowval, *nrowval, avgwgt;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = mat->nrows;
nmat->ncols = mat->ncols;
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_ZScoreFilter: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_ZScoreFilter: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_ZScoreFilter: nrowval");
switch (what) {
case GK_CSR_COL:
gk_errexit(SIGERR, "This has not been implemented yet.\n");
break;
case GK_CSR_ROW:
if (mat->rowptr == NULL)
gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n");
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
avgwgt = zscore/(rowptr[i+1]-rowptr[i]);
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] > avgwgt) {
nrowind[nnz] = rowind[j];
nrowval[nnz] = rowval[j];
nnz++;
}
}
nrowptr[i+1] = nnz;
}
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Compacts the column-space of the matrix by removing empty columns.
As a result of the compaction, the column numbers are renumbered.
The compaction operation is done in place and only affects the row-based
representation of the matrix.
The new columns are ordered in decreasing frequency.
\param mat the matrix whose empty columns will be removed.
*/
/**************************************************************************/
void gk_csr_CompactColumns(gk_csr_t *mat)
{
ssize_t i;
int nrows, ncols, nncols;
ssize_t *rowptr;
int *rowind, *colmap;
gk_ikv_t *clens;
nrows = mat->nrows;
ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
colmap = gk_imalloc(ncols, "gk_csr_CompactColumns: colmap");
clens = gk_ikvmalloc(ncols, "gk_csr_CompactColumns: clens");
for (i=0; i<ncols; i++) {
clens[i].key = 0;
clens[i].val = i;
}
for (i=0; i<rowptr[nrows]; i++)
clens[rowind[i]].key++;
gk_ikvsortd(ncols, clens);
for (nncols=0, i=0; i<ncols; i++) {
if (clens[i].key > 0)
colmap[clens[i].val] = nncols++;
else
break;
}
for (i=0; i<rowptr[nrows]; i++)
rowind[i] = colmap[rowind[i]];
mat->ncols = nncols;
gk_free((void **)&colmap, &clens, LTERM);
}
/*************************************************************************/
/*! Sorts the indices in increasing order
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which set of
indices to sort.
*/
/**************************************************************************/
void gk_csr_SortIndices(gk_csr_t *mat, int what)
{
int n, nn=0;
ssize_t *ptr;
int *ind;
float *val;
switch (what) {
case GK_CSR_ROW:
if (!mat->rowptr)
gk_errexit(SIGERR, "Row-based view of the matrix does not exists.\n");
n = mat->nrows;
ptr = mat->rowptr;
ind = mat->rowind;
val = mat->rowval;
break;
case GK_CSR_COL:
if (!mat->colptr)
gk_errexit(SIGERR, "Column-based view of the matrix does not exists.\n");
n = mat->ncols;
ptr = mat->colptr;
ind = mat->colind;
val = mat->colval;
break;
default:
gk_errexit(SIGERR, "Invalid index type of %d.\n", what);
return;
}
#pragma omp parallel if (n > 100)
{
ssize_t i, j, k;
gk_ikv_t *cand;
float *tval;
#pragma omp single
for (i=0; i<n; i++)
nn = gk_max(nn, ptr[i+1]-ptr[i]);
cand = gk_ikvmalloc(nn, "gk_csr_SortIndices: cand");
tval = gk_fmalloc(nn, "gk_csr_SortIndices: tval");
#pragma omp for schedule(static)
for (i=0; i<n; i++) {
for (k=0, j=ptr[i]; j<ptr[i+1]; j++) {
if (j > ptr[i] && ind[j] < ind[j-1])
k = 1; /* an inversion */
cand[j-ptr[i]].val = j-ptr[i];
cand[j-ptr[i]].key = ind[j];
tval[j-ptr[i]] = val[j];
}
if (k) {
gk_ikvsorti(ptr[i+1]-ptr[i], cand);
for (j=ptr[i]; j<ptr[i+1]; j++) {
ind[j] = cand[j-ptr[i]].key;
val[j] = tval[cand[j-ptr[i]].val];
}
}
}
gk_free((void **)&cand, &tval, LTERM);
}
}
/*************************************************************************/
/*! Creates a row/column index from the column/row data.
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which index
will be created.
*/
/**************************************************************************/
void gk_csr_CreateIndex(gk_csr_t *mat, int what)
{
/* 'f' stands for forward, 'r' stands for reverse */
ssize_t i, j, k, nf, nr;
ssize_t *fptr, *rptr;
int *find, *rind;
float *fval, *rval;
switch (what) {
case GK_CSR_COL:
nf = mat->nrows;
fptr = mat->rowptr;
find = mat->rowind;
fval = mat->rowval;
if (mat->colptr) gk_free((void **)&mat->colptr, LTERM);
if (mat->colind) gk_free((void **)&mat->colind, LTERM);
if (mat->colval) gk_free((void **)&mat->colval, LTERM);
nr = mat->ncols;
rptr = mat->colptr = gk_zsmalloc(nr+1, 0, "gk_csr_CreateIndex: rptr");
rind = mat->colind = gk_imalloc(fptr[nf], "gk_csr_CreateIndex: rind");
rval = mat->colval = (fval ? gk_fmalloc(fptr[nf], "gk_csr_CreateIndex: rval") : NULL);
break;
case GK_CSR_ROW:
nf = mat->ncols;
fptr = mat->colptr;
find = mat->colind;
fval = mat->colval;
if (mat->rowptr) gk_free((void **)&mat->rowptr, LTERM);
if (mat->rowind) gk_free((void **)&mat->rowind, LTERM);
if (mat->rowval) gk_free((void **)&mat->rowval, LTERM);
nr = mat->nrows;
rptr = mat->rowptr = gk_zsmalloc(nr+1, 0, "gk_csr_CreateIndex: rptr");
rind = mat->rowind = gk_imalloc(fptr[nf], "gk_csr_CreateIndex: rind");
rval = mat->rowval = (fval ? gk_fmalloc(fptr[nf], "gk_csr_CreateIndex: rval") : NULL);
break;
default:
gk_errexit(SIGERR, "Invalid index type of %d.\n", what);
return;
}
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rptr[find[j]]++;
}
MAKECSR(i, nr, rptr);
if (rptr[nr] > 6*nr) {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rind[rptr[find[j]]++] = i;
}
SHIFTCSR(i, nr, rptr);
if (fval) {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rval[rptr[find[j]]++] = fval[j];
}
SHIFTCSR(i, nr, rptr);
}
}
else {
if (fval) {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++) {
k = find[j];
rind[rptr[k]] = i;
rval[rptr[k]++] = fval[j];
}
}
}
else {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rind[rptr[find[j]]++] = i;
}
}
SHIFTCSR(i, nr, rptr);
}
}
/*************************************************************************/
/*! Normalizes the rows/columns of the matrix to be unit
length.
\param mat the matrix itself,
\param what indicates what will be normalized and is obtained by
specifying GK_CSR_ROW, GK_CSR_COL, GK_CSR_ROW|GK_CSR_COL.
\param norm indicates what norm is to normalize to, 1: 1-norm, 2: 2-norm
*/
/**************************************************************************/
void gk_csr_Normalize(gk_csr_t *mat, int what, int norm)
{
ssize_t i, j;
int n;
ssize_t *ptr;
float *val, sum;
if (what&GK_CSR_ROW && mat->rowval) {
n = mat->nrows;
ptr = mat->rowptr;
val = mat->rowval;
#pragma omp parallel if (ptr[n] > OMPMINOPS)
{
#pragma omp for private(j,sum) schedule(static)
for (i=0; i<n; i++) {
for (sum=0.0, j=ptr[i]; j<ptr[i+1]; j++){
if (norm == 2)
sum += val[j]*val[j];
else if (norm == 1)
sum += val[j]; /* assume val[j] > 0 */
}
if (sum > 0) {
if (norm == 2)
sum=1.0/sqrt(sum);
else if (norm == 1)
sum=1.0/sum;
for (j=ptr[i]; j<ptr[i+1]; j++)
val[j] *= sum;
}
}
}
}
if (what&GK_CSR_COL && mat->colval) {
n = mat->ncols;
ptr = mat->colptr;
val = mat->colval;
#pragma omp parallel if (ptr[n] > OMPMINOPS)
{
#pragma omp for private(j,sum) schedule(static)
for (i=0; i<n; i++) {
for (sum=0.0, j=ptr[i]; j<ptr[i+1]; j++)
if (norm == 2)
sum += val[j]*val[j];
else if (norm == 1)
sum += val[j];
if (sum > 0) {
if (norm == 2)
sum=1.0/sqrt(sum);
else if (norm == 1)
sum=1.0/sum;
for (j=ptr[i]; j<ptr[i+1]; j++)
val[j] *= sum;
}
}
}
}
}
/*************************************************************************/
/*! Applies different row scaling methods.
\param mat the matrix itself,
\param type indicates the type of row scaling. Possible values are:
GK_CSR_MAXTF, GK_CSR_SQRT, GK_CSR_LOG, GK_CSR_IDF, GK_CSR_MAXTF2.
*/
/**************************************************************************/
void gk_csr_Scale(gk_csr_t *mat, int type)
{
ssize_t i, j;
int nrows, ncols, nnzcols, bgfreq;
ssize_t *rowptr;
int *rowind, *collen;
float *rowval, *cscale, maxtf;
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
switch (type) {
case GK_CSR_MAXTF: /* TF' = .5 + .5*TF/MAX(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j, maxtf) schedule(static)
for (i=0; i<nrows; i++) {
maxtf = fabs(rowval[rowptr[i]]);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
maxtf = (maxtf < fabs(rowval[j]) ? fabs(rowval[j]) : maxtf);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] = .5 + .5*rowval[j]/maxtf;
}
}
break;
case GK_CSR_MAXTF2: /* TF' = .1 + .9*TF/MAX(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j, maxtf) schedule(static)
for (i=0; i<nrows; i++) {
maxtf = fabs(rowval[rowptr[i]]);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
maxtf = (maxtf < fabs(rowval[j]) ? fabs(rowval[j]) : maxtf);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] = .1 + .9*rowval[j]/maxtf;
}
}
break;
case GK_CSR_SQRT: /* TF' = .1+SQRT(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], sqrt(fabs(rowval[j])));
}
}
}
break;
case GK_CSR_POW25: /* TF' = .1+POW(TF,.25) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], sqrt(sqrt(fabs(rowval[j]))));
}
}
}
break;
case GK_CSR_POW65: /* TF' = .1+POW(TF,.65) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .65));
}
}
}
break;
case GK_CSR_POW75: /* TF' = .1+POW(TF,.75) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .75));
}
}
}
break;
case GK_CSR_POW85: /* TF' = .1+POW(TF,.85) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .85));
}
}
}
break;
case GK_CSR_LOG: /* TF' = 1+log_2(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
double logscale = 1.0/log(2.0);
#pragma omp for schedule(static,32)
for (i=0; i<rowptr[nrows]; i++) {
if (rowval[i] != 0.0)
rowval[i] = 1+(rowval[i]>0.0 ? log(rowval[i]) : -log(-rowval[i]))*logscale;
}
#ifdef XXX
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = 1+(rowval[j]>0.0 ? log(rowval[j]) : -log(-rowval[j]))*logscale;
//rowval[j] = 1+sign(rowval[j], log(fabs(rowval[j]))*logscale);
}
}
#endif
}
break;
case GK_CSR_IDF: /* TF' = TF*IDF */
ncols = mat->ncols;
cscale = gk_fmalloc(ncols, "gk_csr_Scale: cscale");
collen = gk_ismalloc(ncols, 0, "gk_csr_Scale: collen");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
collen[rowind[j]]++;
}
#pragma omp parallel if (ncols > OMPMINOPS)
{
#pragma omp for schedule(static)
for (i=0; i<ncols; i++)
cscale[i] = (collen[i] > 0 ? log(1.0*nrows/collen[i]) : 0.0);
}
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] *= cscale[rowind[j]];
}
}
gk_free((void **)&cscale, &collen, LTERM);
break;
case GK_CSR_IDF2: /* TF' = TF*IDF */
ncols = mat->ncols;
cscale = gk_fmalloc(ncols, "gk_csr_Scale: cscale");
collen = gk_ismalloc(ncols, 0, "gk_csr_Scale: collen");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
collen[rowind[j]]++;
}
nnzcols = 0;
#pragma omp parallel if (ncols > OMPMINOPS)
{
#pragma omp for schedule(static) reduction(+:nnzcols)
for (i=0; i<ncols; i++)
nnzcols += (collen[i] > 0 ? 1 : 0);
bgfreq = gk_max(10, (ssize_t)(.5*rowptr[nrows]/nnzcols));
#pragma omp master
{
printf("nnz: %zd, nnzcols: %d, bgfreq: %d\n", rowptr[nrows], nnzcols, bgfreq);
}
#pragma omp for schedule(static)
for (i=0; i<ncols; i++)
cscale[i] = (collen[i] > 0 ? log(1.0*(nrows+2*bgfreq)/(bgfreq+collen[i])) : 0.0);
}
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] *= cscale[rowind[j]];
}
}
gk_free((void **)&cscale, &collen, LTERM);
break;
default:
gk_errexit(SIGERR, "Unknown scaling type of %d\n", type);
}
}
/*************************************************************************/
/*! Computes the sums of the rows/columns
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which
sums to compute.
*/
/**************************************************************************/
void gk_csr_ComputeSums(gk_csr_t *mat, int what)
{
ssize_t i;
int n;
ssize_t *ptr;
float *val, *sums;
switch (what) {
case GK_CSR_ROW:
n = mat->nrows;
ptr = mat->rowptr;
val = mat->rowval;
if (mat->rsums)
gk_free((void **)&mat->rsums, LTERM);
sums = mat->rsums = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: sums");
break;
case GK_CSR_COL:
n = mat->ncols;
ptr = mat->colptr;
val = mat->colval;
if (mat->csums)
gk_free((void **)&mat->csums, LTERM);
sums = mat->csums = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: sums");
break;
default:
gk_errexit(SIGERR, "Invalid sum type of %d.\n", what);
return;
}
#pragma omp parallel for if (ptr[n] > OMPMINOPS) schedule(static)
for (i=0; i<n; i++)
sums[i] = gk_fsum(ptr[i+1]-ptr[i], val+ptr[i], 1);
}
/*************************************************************************/
/*! Computes the squared of the norms of the rows/columns
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which
squared norms to compute.
*/
/**************************************************************************/
void gk_csr_ComputeSquaredNorms(gk_csr_t *mat, int what)
{
ssize_t i;
int n;
ssize_t *ptr;
float *val, *norms;
switch (what) {
case GK_CSR_ROW:
n = mat->nrows;
ptr = mat->rowptr;
val = mat->rowval;
if (mat->rnorms) gk_free((void **)&mat->rnorms, LTERM);
norms = mat->rnorms = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: norms");
break;
case GK_CSR_COL:
n = mat->ncols;
ptr = mat->colptr;
val = mat->colval;
if (mat->cnorms) gk_free((void **)&mat->cnorms, LTERM);
norms = mat->cnorms = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: norms");
break;
default:
gk_errexit(SIGERR, "Invalid norm type of %d.\n", what);
return;
}
#pragma omp parallel for if (ptr[n] > OMPMINOPS) schedule(static)
for (i=0; i<n; i++)
norms[i] = gk_fdot(ptr[i+1]-ptr[i], val+ptr[i], 1, val+ptr[i], 1);
}
/*************************************************************************/
/*! Returns a new matrix whose rows/columns are shuffled.
\param mat the matrix to be shuffled,
\param what indicates if the rows (GK_CSR_ROW), columns (GK_CSR_COL),
or both (GK_CSR_ROWCOL) will be shuffled,
\param symmetric indicates if the same shuffling will be applied to
both rows and columns. This is valid with nrows==ncols and
GK_CSR_ROWCOL was specified.
\returns the shuffled matrix.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Shuffle(gk_csr_t *mat, int what, int symmetric)
{
ssize_t i, j;
int nrows, ncols;
ssize_t *rowptr, *nrowptr;
int *rowind, *nrowind;
int *rperm, *cperm;
float *rowval, *nrowval;
gk_csr_t *nmat;
if (what == GK_CSR_ROWCOL && symmetric && mat->nrows != mat->ncols)
gk_errexit(SIGERR, "The matrix is not square for a symmetric rowcol shuffling.\n");
nrows = mat->nrows;
ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
rperm = gk_imalloc(nrows, "gk_csr_Shuffle: rperm");
cperm = gk_imalloc(ncols, "gk_csr_Shuffle: cperm");
switch (what) {
case GK_CSR_ROW:
gk_RandomPermute(nrows, rperm, 1);
for (i=0; i<20; i++)
gk_RandomPermute(nrows, rperm, 0);
for (i=0; i<ncols; i++)
cperm[i] = i;
break;
case GK_CSR_COL:
gk_RandomPermute(ncols, cperm, 1);
for (i=0; i<20; i++)
gk_RandomPermute(ncols, cperm, 0);
for (i=0; i<nrows; i++)
rperm[i] = i;
break;
case GK_CSR_ROWCOL:
gk_RandomPermute(nrows, rperm, 1);
for (i=0; i<20; i++)
gk_RandomPermute(nrows, rperm, 0);
if (symmetric)
gk_icopy(nrows, rperm, cperm);
else {
gk_RandomPermute(ncols, cperm, 1);
for (i=0; i<20; i++)
gk_RandomPermute(ncols, cperm, 0);
}
break;
default:
gk_free((void **)&rperm, &cperm, LTERM);
gk_errexit(SIGERR, "Unknown shuffling type of %d\n", what);
return NULL;
}
nmat = gk_csr_Create();
nmat->nrows = nrows;
nmat->ncols = ncols;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Shuffle: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_Shuffle: nrowind");
nrowval = nmat->rowval = (rowval ? gk_fmalloc(rowptr[nrows], "gk_csr_Shuffle: nrowval") : NULL) ;
for (i=0; i<nrows; i++)
nrowptr[rperm[i]] = rowptr[i+1]-rowptr[i];
MAKECSR(i, nrows, nrowptr);
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
nrowind[nrowptr[rperm[i]]] = cperm[rowind[j]];
if (nrowval)
nrowval[nrowptr[rperm[i]]] = rowval[j];
nrowptr[rperm[i]]++;
}
}
SHIFTCSR(i, nrows, nrowptr);
gk_free((void **)&rperm, &cperm, LTERM);
return nmat;
}
/*************************************************************************/
/*! Computes the similarity between two rows/columns
\param mat the matrix itself. The routine assumes that the indices
are sorted in increasing order.
\param i1 is the first row/column,
\param i2 is the second row/column,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating the type of
objects between the similarity will be computed,
\param simtype is the type of similarity and is one of GK_CSR_COS,
GK_CSR_JAC, GK_CSR_MIN, GK_CSR_AMIN
\returns the similarity between the two rows/columns.
*/
/**************************************************************************/
float gk_csr_ComputeSimilarity(gk_csr_t *mat, int i1, int i2, int what, int simtype)
{
int nind1, nind2;
int *ind1, *ind2;
float *val1, *val2, stat1, stat2, sim;
switch (what) {
case GK_CSR_ROW:
if (!mat->rowptr)
gk_errexit(SIGERR, "Row-based view of the matrix does not exists.\n");
nind1 = mat->rowptr[i1+1]-mat->rowptr[i1];
nind2 = mat->rowptr[i2+1]-mat->rowptr[i2];
ind1 = mat->rowind + mat->rowptr[i1];
ind2 = mat->rowind + mat->rowptr[i2];
val1 = mat->rowval + mat->rowptr[i1];
val2 = mat->rowval + mat->rowptr[i2];
break;
case GK_CSR_COL:
if (!mat->colptr)
gk_errexit(SIGERR, "Column-based view of the matrix does not exists.\n");
nind1 = mat->colptr[i1+1]-mat->colptr[i1];
nind2 = mat->colptr[i2+1]-mat->colptr[i2];
ind1 = mat->colind + mat->colptr[i1];
ind2 = mat->colind + mat->colptr[i2];
val1 = mat->colval + mat->colptr[i1];
val2 = mat->colval + mat->colptr[i2];
break;
default:
gk_errexit(SIGERR, "Invalid index type of %d.\n", what);
return 0.0;
}
switch (simtype) {
case GK_CSR_COS:
case GK_CSR_JAC:
sim = stat1 = stat2 = 0.0;
i1 = i2 = 0;
while (i1<nind1 && i2<nind2) {
if (i1 == nind1) {
stat2 += val2[i2]*val2[i2];
i2++;
}
else if (i2 == nind2) {
stat1 += val1[i1]*val1[i1];
i1++;
}
else if (ind1[i1] < ind2[i2]) {
stat1 += val1[i1]*val1[i1];
i1++;
}
else if (ind1[i1] > ind2[i2]) {
stat2 += val2[i2]*val2[i2];
i2++;
}
else {
sim += val1[i1]*val2[i2];
stat1 += val1[i1]*val1[i1];
stat2 += val2[i2]*val2[i2];
i1++;
i2++;
}
}
if (simtype == GK_CSR_COS)
sim = (stat1*stat2 > 0.0 ? sim/sqrt(stat1*stat2) : 0.0);
else
sim = (stat1+stat2-sim > 0.0 ? sim/(stat1+stat2-sim) : 0.0);
break;
case GK_CSR_MIN:
sim = stat1 = stat2 = 0.0;
i1 = i2 = 0;
while (i1<nind1 && i2<nind2) {
if (i1 == nind1) {
stat2 += val2[i2];
i2++;
}
else if (i2 == nind2) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] < ind2[i2]) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] > ind2[i2]) {
stat2 += val2[i2];
i2++;
}
else {
sim += gk_min(val1[i1],val2[i2]);
stat1 += val1[i1];
stat2 += val2[i2];
i1++;
i2++;
}
}
sim = (stat1+stat2-sim > 0.0 ? sim/(stat1+stat2-sim) : 0.0);
break;
case GK_CSR_AMIN:
sim = stat1 = stat2 = 0.0;
i1 = i2 = 0;
while (i1<nind1 && i2<nind2) {
if (i1 == nind1) {
stat2 += val2[i2];
i2++;
}
else if (i2 == nind2) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] < ind2[i2]) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] > ind2[i2]) {
stat2 += val2[i2];
i2++;
}
else {
sim += gk_min(val1[i1],val2[i2]);
stat1 += val1[i1];
stat2 += val2[i2];
i1++;
i2++;
}
}
sim = (stat1 > 0.0 ? sim/stat1 : 0.0);
break;
default:
gk_errexit(SIGERR, "Unknown similarity measure %d\n", simtype);
return -1;
}
return sim;
}
/*************************************************************************/
/*! Finds the n most similar rows (neighbors) to the query using cosine
similarity.
\param mat the matrix itself
\param nqterms is the number of columns in the query
\param qind is the list of query columns
\param qval is the list of correspodning query weights
\param simtype is the type of similarity and is one of GK_CSR_COS,
GK_CSR_JAC, GK_CSR_MIN, GK_CSR_AMIN
\param nsim is the maximum number of requested most similar rows.
If -1 is provided, then everything is returned unsorted.
\param minsim is the minimum similarity of the requested most
similar rows
\param hits is the result set. This array should be at least
of length nsim.
\param i_marker is an array of size equal to the number of rows
whose values are initialized to -1. If NULL is provided
then this array is allocated and freed internally.
\param i_cand is an array of size equal to the number of rows.
If NULL is provided then this array is allocated and freed
internally.
\returns the number of identified most similar rows, which can be
smaller than the requested number of nnbrs in those cases
in which there are no sufficiently many neighbors.
*/
/**************************************************************************/
int gk_csr_GetSimilarRows(gk_csr_t *mat, int nqterms, int *qind,
float *qval, int simtype, int nsim, float minsim, gk_fkv_t *hits,
int *i_marker, gk_fkv_t *i_cand)
{
ssize_t i, ii, j, k;
int nrows, ncols, ncand;
ssize_t *colptr;
int *colind, *marker;
float *colval, *rnorms, mynorm, *rsums, mysum;
gk_fkv_t *cand;
if (nqterms == 0)
return 0;
nrows = mat->nrows;
ncols = mat->ncols;
colptr = mat->colptr;
colind = mat->colind;
colval = mat->colval;
marker = (i_marker ? i_marker : gk_ismalloc(nrows, -1, "gk_csr_SimilarRows: marker"));
cand = (i_cand ? i_cand : gk_fkvmalloc(nrows, "gk_csr_SimilarRows: cand"));
switch (simtype) {
case GK_CSR_COS:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += colval[j]*qval[ii];
}
}
}
break;
case GK_CSR_JAC:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += colval[j]*qval[ii];
}
}
}
rnorms = mat->rnorms;
mynorm = gk_fdot(nqterms, qval, 1, qval, 1);
for (i=0; i<ncand; i++)
cand[i].key = cand[i].key/(rnorms[cand[i].val]+mynorm-cand[i].key);
break;
case GK_CSR_MIN:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += gk_min(colval[j], qval[ii]);
}
}
}
rsums = mat->rsums;
mysum = gk_fsum(nqterms, qval, 1);
for (i=0; i<ncand; i++)
cand[i].key = cand[i].key/(rsums[cand[i].val]+mysum-cand[i].key);
break;
/* Assymetric MIN similarity */
case GK_CSR_AMIN:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += gk_min(colval[j], qval[ii]);
}
}
}
mysum = gk_fsum(nqterms, qval, 1);
for (i=0; i<ncand; i++)
cand[i].key = cand[i].key/mysum;
break;
default:
gk_errexit(SIGERR, "Unknown similarity measure %d\n", simtype);
return -1;
}
/* go and prune the hits that are bellow minsim */
for (j=0, i=0; i<ncand; i++) {
marker[cand[i].val] = -1;
if (cand[i].key >= minsim)
cand[j++] = cand[i];
}
ncand = j;
if (nsim == -1 || nsim >= ncand) {
nsim = ncand;
}
else {
nsim = gk_min(nsim, ncand);
gk_dfkvkselect(ncand, nsim, cand);
gk_fkvsortd(nsim, cand);
}
gk_fkvcopy(nsim, cand, hits);
if (i_marker == NULL)
gk_free((void **)&marker, LTERM);
if (i_cand == NULL)
gk_free((void **)&cand, LTERM);
return nsim;
}
/*************************************************************************/
/*! This function finds the connected components in a graph.
\param mat is the graph structure in CSR format
\param cptr is the ptr structure of the CSR representation of the
components. The length of this vector must be mat->nrows+1.
\param cind is the indices structure of the CSR representation of
the components. The length of this vector must be mat->nrows.
\param cids is an array that stores the component # of each vertex
of the graph. The length of this vector must be mat->nrows.
\returns the number of components that it found.
\note The cptr, cind, and cids parameters can be NULL, in which case
only the number of connected components is returned.
*/
/*************************************************************************/
int gk_csr_FindConnectedComponents(gk_csr_t *mat, int32_t *cptr, int32_t *cind,
int32_t *cids)
{
ssize_t i, ii, j, jj, k, nvtxs, first, last, ntodo, ncmps;
ssize_t *xadj;
int32_t *adjncy, *pos, *todo;
int32_t mustfree_ccsr=0, mustfree_where=0;
if (mat->nrows != mat->ncols) {
fprintf(stderr, "gk_csr_FindComponents: The matrix needs to be square.\n");
return -1;
}
nvtxs = mat->nrows;
xadj = mat->rowptr;
adjncy = mat->rowind;
/* Deal with NULL supplied cptr/cind vectors */
if (cptr == NULL) {
cptr = gk_i32malloc(nvtxs+1, "gk_csr_FindComponents: cptr");
cind = gk_i32malloc(nvtxs, "gk_csr_FindComponents: cind");
mustfree_ccsr = 1;
}
/* The list of vertices that have not been touched yet.
The valid entries are from [0..ntodo). */
todo = gk_i32incset(nvtxs, 0, gk_i32malloc(nvtxs, "gk_csr_FindComponents: todo"));
/* For a vertex that has not been visited, pos[i] is the position in the
todo list that this vertex is stored.
If a vertex has been visited, pos[i] = -1. */
pos = gk_i32incset(nvtxs, 0, gk_i32malloc(nvtxs, "gk_csr_FindComponents: pos"));
/* Find the connected componends */
ncmps = -1;
ntodo = nvtxs; /* All vertices have not been visited */
first = last = 0; /* Point to the first and last vertices that have been touched
but not explored.
These vertices are stored in cind[first]...cind[last-1]. */
while (first < last || ntodo > 0) {
if (first == last) { /* Find another starting vertex */
cptr[++ncmps] = first; /* Mark the end of the current CC */
/* put the first vertex in the todo list as the start of the new CC */
ASSERT(pos[todo[0]] != -1);
cind[last++] = todo[0];
pos[todo[0]] = -1;
todo[0] = todo[--ntodo];
pos[todo[0]] = 0;
}
i = cind[first++]; /* Get the first visited but unexplored vertex */
for (j=xadj[i]; j<xadj[i+1]; j++) {
k = adjncy[j];
if (pos[k] != -1) {
cind[last++] = k;
/* Remove k from the todo list and put the last item in the todo
list at the position that k was so that the todo list will be
consequtive. The pos[] array is updated accordingly to keep track
the location of the vertices in the todo[] list. */
todo[pos[k]] = todo[--ntodo];
pos[todo[pos[k]]] = pos[k];
pos[k] = -1;
}
}
}
cptr[++ncmps] = first;
/* see if we need to return cids */
if (cids != NULL) {
for (i=0; i<ncmps; i++) {
for (j=cptr[i]; j<cptr[i+1]; j++)
cids[cind[j]] = i;
}
}
if (mustfree_ccsr)
gk_free((void **)&cptr, &cind, LTERM);
gk_free((void **)&pos, &todo, LTERM);
return (int) ncmps;
}
/*************************************************************************/
/*! Returns a symmetric version of a square matrix. The symmetric version
is constructed by applying an A op A^T operation, where op is one of
GK_CSR_SYM_SUM, GK_CSR_SYM_MIN, GK_CSR_SYM_MAX, GK_CSR_SYM_AVG.
\param mat the matrix to be symmetrized,
\param op indicates the operation to be performed. The possible values are
GK_CSR_SYM_SUM, GK_CSR_SYM_MIN, GK_CSR_SYM_MAX, and GK_CSR_SYM_AVG.
\returns the symmetrized matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_MakeSymmetric(gk_csr_t *mat, int op)
{
ssize_t i, j, k, nnz;
int nrows, nadj, hasvals;
ssize_t *rowptr, *colptr, *nrowptr;
int *rowind, *colind, *nrowind, *marker, *ids;
float *rowval=NULL, *colval=NULL, *nrowval=NULL, *wgts=NULL;
gk_csr_t *nmat;
if (mat->nrows != mat->ncols) {
fprintf(stderr, "gk_csr_MakeSymmetric: The matrix needs to be square.\n");
return NULL;
}
hasvals = (mat->rowval != NULL);
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
if (hasvals)
rowval = mat->rowval;
/* create the column view for efficient processing */
colptr = gk_zsmalloc(nrows+1, 0, "colptr");
colind = gk_i32malloc(rowptr[nrows], "colind");
if (hasvals)
colval = gk_fmalloc(rowptr[nrows], "colval");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
colptr[rowind[j]]++;
}
MAKECSR(i, nrows, colptr);
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
colind[colptr[rowind[j]]] = i;
if (hasvals)
colval[colptr[rowind[j]]] = rowval[j];
colptr[rowind[j]]++;
}
}
SHIFTCSR(i, nrows, colptr);
nmat = gk_csr_Create();
nmat->nrows = mat->nrows;
nmat->ncols = mat->ncols;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_MakeSymmetric: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_MakeSymmetric: nrowind");
if (hasvals)
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_MakeSymmetric: nrowval");
marker = gk_ismalloc(nrows, -1, "marker");
ids = gk_imalloc(nrows, "ids");
if (hasvals)
wgts = gk_fmalloc(nrows, "wgts");
nrowptr[0] = nnz = 0;
for (i=0; i<nrows; i++) {
nadj = 0;
/* out-edges */
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
ids[nadj] = rowind[j];
if (hasvals)
wgts[nadj] = (op == GK_CSR_SYM_AVG ? 0.5*rowval[j] : rowval[j]);
marker[rowind[j]] = nadj++;
}
/* in-edges */
for (j=colptr[i]; j<colptr[i+1]; j++) {
if (marker[colind[j]] == -1) {
if (op != GK_CSR_SYM_MIN) {
ids[nadj] = colind[j];
if (hasvals)
wgts[nadj] = (op == GK_CSR_SYM_AVG ? 0.5*colval[j] : colval[j]);
nadj++;
}
}
else {
if (hasvals) {
switch (op) {
case GK_CSR_SYM_MAX:
wgts[marker[colind[j]]] = gk_max(colval[j], wgts[marker[colind[j]]]);
break;
case GK_CSR_SYM_MIN:
wgts[marker[colind[j]]] = gk_min(colval[j], wgts[marker[colind[j]]]);
break;
case GK_CSR_SYM_SUM:
wgts[marker[colind[j]]] += colval[j];
break;
case GK_CSR_SYM_AVG:
wgts[marker[colind[j]]] = 0.5*(wgts[marker[colind[j]]] + colval[j]);
break;
default:
errexit("Unsupported op for MakeSymmetric!\n");
}
}
marker[colind[j]] = -1;
}
}
/* go over out edges again to resolve any edges that were not found in the in
* edges */
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (marker[rowind[j]] != -1) {
if (op == GK_CSR_SYM_MIN)
ids[marker[rowind[j]]] = -1;
marker[rowind[j]] = -1;
}
}
/* put the non '-1' entries in ids[] into i's row */
for (j=0; j<nadj; j++) {
if (ids[j] != -1) {
nrowind[nnz] = ids[j];
if (hasvals)
nrowval[nnz] = wgts[j];
nnz++;
}
}
nrowptr[i+1] = nnz;
}
gk_free((void **)&colptr, &colind, &colval, &marker, &ids, &wgts, LTERM);
return nmat;
}
|
grid_ao_drv.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include "config.h"
#include "grid_ao_drv.h"
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
double exp_cephes(double x);
double CINTcommon_fac_sp(int l);
void GTOnabla1(double *fx1, double *fy1, double *fz1,
double *fx0, double *fy0, double *fz0, int l, double a)
{
int i, n;
double a2 = -2 * a;
for (n = 0; n < SIMDD; n++) {
fx1[n] = a2*fx0[SIMDD+n];
fy1[n] = a2*fy0[SIMDD+n];
fz1[n] = a2*fz0[SIMDD+n];
}
for (i = 1; i <= l; i++) {
for (n = 0; n < SIMDD; n++) {
fx1[i*SIMDD+n] = i*fx0[(i-1)*SIMDD+n] + a2*fx0[(i+1)*SIMDD+n];
fy1[i*SIMDD+n] = i*fy0[(i-1)*SIMDD+n] + a2*fy0[(i+1)*SIMDD+n];
fz1[i*SIMDD+n] = i*fz0[(i-1)*SIMDD+n] + a2*fz0[(i+1)*SIMDD+n];
} }
}
/*
* r - R_O = (r-R_i) + ri, ri = (x,y,z) = R_i - R_O
*/
void GTOx1(double *fx1, double *fy1, double *fz1,
double *fx0, double *fy0, double *fz0, int l, double *ri)
{
int i, n;
for (i = 0; i <= l; i++) {
for (n = 0; n < SIMDD; n++) {
fx1[i*SIMDD+n] = ri[0] * fx0[i*SIMDD+n] + fx0[(i+1)*SIMDD+n];
fy1[i*SIMDD+n] = ri[1] * fy0[i*SIMDD+n] + fy0[(i+1)*SIMDD+n];
fz1[i*SIMDD+n] = ri[2] * fz0[i*SIMDD+n] + fz0[(i+1)*SIMDD+n];
} }
}
int GTOprim_exp(double *eprim, double *coord, double *alpha, double *coeff,
int l, int nprim, int nctr, size_t ngrids, double fac)
{
int i, j;
double arr, maxc;
double logcoeff[nprim];
double rr[ngrids];
double *gridx = coord;
double *gridy = coord+BLKSIZE;
double *gridz = coord+BLKSIZE*2;
int not0 = 0;
// the maximum value of the coefficients for each pGTO
for (j = 0; j < nprim; j++) {
maxc = 0;
for (i = 0; i < nctr; i++) {
maxc = MAX(maxc, fabs(coeff[i*nprim+j]));
}
logcoeff[j] = log(maxc);
}
for (i = 0; i < ngrids; i++) {
rr[i] = gridx[i]*gridx[i] + gridy[i]*gridy[i] + gridz[i]*gridz[i];
}
for (j = 0; j < nprim; j++) {
for (i = 0; i < ngrids; i++) {
arr = alpha[j] * rr[i];
if (arr-logcoeff[j] < EXPCUTOFF) {
eprim[j*BLKSIZE+i] = exp_cephes(-arr) * fac;
not0 = 1;
} else {
eprim[j*BLKSIZE+i] = 0;
}
}
}
return not0;
}
// grid2atm[atm_id,xyz,grid_id]
static void _fill_grid2atm(double *grid2atm, double *coord, size_t bgrids, size_t ngrids,
int *atm, int natm, int *bas, int nbas, double *env)
{
int atm_id;
size_t ig;
double *r_atm;
for (atm_id = 0; atm_id < natm; atm_id++) {
r_atm = env + atm[PTR_COORD+atm_id*ATM_SLOTS];
for (ig = 0; ig < bgrids; ig++) {
grid2atm[0*BLKSIZE+ig] = coord[0*ngrids+ig] - r_atm[0];
grid2atm[1*BLKSIZE+ig] = coord[1*ngrids+ig] - r_atm[1];
grid2atm[2*BLKSIZE+ig] = coord[2*ngrids+ig] - r_atm[2];
}
grid2atm += 3*BLKSIZE;
}
}
static void _dset0(double *out, size_t odim, size_t bgrids, int counts)
{
size_t i, j;
for (i = 0; i < counts; i++) {
for (j = 0; j < bgrids; j++) {
out[i*odim+j] = 0;
}
}
}
static void _zset0(double complex *out, size_t odim, size_t bgrids, int counts)
{
size_t i, j;
for (i = 0; i < counts; i++) {
for (j = 0; j < bgrids; j++) {
out[i*odim+j] = 0;
}
}
}
void GTOeval_sph_iter(FPtr_eval feval, FPtr_exp fexp, double fac,
size_t nao, size_t ngrids, size_t bgrids,
int param[], int *shls_slice, int *ao_loc, double *buf,
double *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ncomp = param[TENSOR];
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const int atmstart = bas[sh0*BAS_SLOTS+ATOM_OF];
const int atmend = bas[(sh1-1)*BAS_SLOTS+ATOM_OF]+1;
const int atmcount = atmend - atmstart;
int i, k, l, np, nc, atm_id, bas_id, deg, dcart, ao_id;
size_t di;
double fac1;
double *p_exp, *pcoeff, *pcoord, *pcart, *ri, *pao;
double *grid2atm = buf; // [atm_id,xyz,grid]
double *eprim = grid2atm + atmcount*3*BLKSIZE;
double *cart_gto = eprim + NPRIMAX*BLKSIZE*2;
_fill_grid2atm(grid2atm, coord, bgrids, ngrids,
atm+atmstart*ATM_SLOTS, atmcount, bas, nbas, env);
for (bas_id = sh0; bas_id < sh1; bas_id++) {
np = bas[bas_id*BAS_SLOTS+NPRIM_OF];
nc = bas[bas_id*BAS_SLOTS+NCTR_OF ];
l = bas[bas_id*BAS_SLOTS+ANG_OF ];
deg = l * 2 + 1;
fac1 = fac * CINTcommon_fac_sp(l);
p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP];
pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF];
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
pcoord = grid2atm + (atm_id - atmstart) * 3*BLKSIZE;
ao_id = ao_loc[bas_id] - ao_loc[sh0];
if (non0table[bas_id] &&
(*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac1)) {
dcart = (l+1)*(l+2)/2;
di = nc * dcart;
ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS];
if (l <= 1) { // s, p functions
(*feval)(ao+ao_id*ngrids, ri, eprim, pcoord, p_exp, pcoeff,
env, l, np, nc, nao, ngrids, bgrids);
} else {
(*feval)(cart_gto, ri, eprim, pcoord, p_exp, pcoeff,
env, l, np, nc, di, bgrids, bgrids);
pcart = cart_gto;
for (i = 0; i < ncomp; i++) {
pao = ao + (i*nao+ao_id)*ngrids;
for (k = 0; k < nc; k++) {
CINTc2s_ket_sph1(pao, pcart,
ngrids, bgrids, l);
pao += deg * ngrids;
pcart += dcart * bgrids;
}
}
}
} else {
for (i = 0; i < ncomp; i++) {
_dset0(ao+(i*nao+ao_id)*ngrids, ngrids, bgrids, nc*deg);
}
}
}
}
void GTOeval_cart_iter(FPtr_eval feval, FPtr_exp fexp, double fac,
size_t nao, size_t ngrids, size_t bgrids,
int param[], int *shls_slice, int *ao_loc, double *buf,
double *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ncomp = param[TENSOR];
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const int atmstart = bas[sh0*BAS_SLOTS+ATOM_OF];
const int atmend = bas[(sh1-1)*BAS_SLOTS+ATOM_OF]+1;
const int atmcount = atmend - atmstart;
int i, l, np, nc, atm_id, bas_id, deg, ao_id;
double fac1;
double *p_exp, *pcoeff, *pcoord, *ri;
double *grid2atm = buf; // [atm_id,xyz,grid]
double *eprim = grid2atm + atmcount*3*BLKSIZE;
_fill_grid2atm(grid2atm, coord, bgrids, ngrids,
atm+atmstart*ATM_SLOTS, atmcount, bas, nbas, env);
for (bas_id = sh0; bas_id < sh1; bas_id++) {
np = bas[bas_id*BAS_SLOTS+NPRIM_OF];
nc = bas[bas_id*BAS_SLOTS+NCTR_OF ];
l = bas[bas_id*BAS_SLOTS+ANG_OF ];
deg = (l+1)*(l+2)/2;
fac1 = fac * CINTcommon_fac_sp(l);
p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP];
pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF];
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
pcoord = grid2atm + (atm_id - atmstart) * 3*BLKSIZE;
ao_id = ao_loc[bas_id] - ao_loc[sh0];
if (non0table[bas_id] &&
(*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac1)) {
ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS];
(*feval)(ao+ao_id*ngrids, ri, eprim, pcoord, p_exp, pcoeff,
env, l, np, nc, nao, ngrids, bgrids);
} else {
for (i = 0; i < ncomp; i++) {
_dset0(ao+(i*nao+ao_id)*ngrids, ngrids, bgrids, nc*deg);
}
}
}
}
void GTOeval_spinor_iter(FPtr_eval feval, FPtr_exp fexp, void (*c2s)(), double fac,
size_t nao, size_t ngrids, size_t bgrids,
int param[], int *shls_slice, int *ao_loc, double *buf,
double complex *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ncomp_e1 = param[POS_E1];
const int ncomp = param[TENSOR];
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const int atmstart = bas[sh0*BAS_SLOTS+ATOM_OF];
const int atmend = bas[(sh1-1)*BAS_SLOTS+ATOM_OF]+1;
const int atmcount = atmend - atmstart;
int i, l, np, nc, atm_id, bas_id, deg, kappa, dcart, ao_id;
size_t off, di;
double fac1;
double *p_exp, *pcoeff, *pcoord, *pcart, *ri;
double complex *aoa = ao;
double complex *aob = ao + ncomp*nao*ngrids;
double *grid2atm = buf; // [atm_id,xyz,grid]
double *eprim = grid2atm + atmcount*3*BLKSIZE;
double *cart_gto = eprim + NPRIMAX*BLKSIZE*2;
_fill_grid2atm(grid2atm, coord, bgrids, ngrids,
atm+atmstart*ATM_SLOTS, atmcount, bas, nbas, env);
for (bas_id = sh0; bas_id < sh1; bas_id++) {
np = bas[bas_id*BAS_SLOTS+NPRIM_OF];
nc = bas[bas_id*BAS_SLOTS+NCTR_OF ];
l = bas[bas_id*BAS_SLOTS+ANG_OF ];
deg = CINTlen_spinor(bas_id, bas);
fac1 = fac * CINTcommon_fac_sp(l);
p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP];
pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF];
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
pcoord = grid2atm + (atm_id - atmstart) * 3*BLKSIZE;
ao_id = ao_loc[bas_id] - ao_loc[sh0];
if (non0table[bas_id] &&
(*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac1)) {
kappa = bas[bas_id*BAS_SLOTS+KAPPA_OF];
dcart = (l+1)*(l+2)/2;
di = nc * dcart;
ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS];
(*feval)(cart_gto, ri, eprim, pcoord, p_exp, pcoeff,
env, l, np, nc, di, bgrids, bgrids);
for (i = 0; i < ncomp; i++) {
pcart = cart_gto + i * di*bgrids*ncomp_e1;
off = (i*nao+ao_id)*ngrids;
(*c2s)(aoa+off, aob+off, pcart,
ngrids, bgrids, nc, kappa, l);
}
} else {
for (i = 0; i < ncomp; i++) {
off = (i*nao+ao_id)*ngrids;
_zset0(aoa+off, ngrids, bgrids, nc*deg);
_zset0(aob+off, ngrids, bgrids, nc*deg);
}
}
}
}
int GTOshloc_by_atom(int *shloc, int *shls_slice, int *ao_loc, int *atm, int *bas)
{
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
int ish, nshblk, lastatm;
shloc[0] = sh0;
nshblk = 1;
lastatm = bas[BAS_SLOTS*sh0+ATOM_OF];
for (ish = sh0; ish < sh1; ish++) {
if (lastatm != bas[BAS_SLOTS*ish+ATOM_OF]) {
lastatm = bas[BAS_SLOTS*ish+ATOM_OF];
shloc[nshblk] = ish;
nshblk++;
}
}
shloc[nshblk] = sh1;
return nshblk;
}
/*
* non0table[ngrids/blksize,natm] is the T/F table for ao values to
* screen the ao evaluation for each shell
*/
void GTOeval_loop(void (*fiter)(), FPtr_eval feval, FPtr_exp fexp, double fac,
int ngrids, int param[], int *shls_slice, int *ao_loc,
double *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int shloc[shls_slice[1]-shls_slice[0]+1];
const int nshblk = GTOshloc_by_atom(shloc, shls_slice, ao_loc, atm, bas);
const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE;
const size_t Ngrids = ngrids;
#pragma omp parallel
{
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const size_t nao = ao_loc[sh1] - ao_loc[sh0];
int ip, ib, k, iloc, ish;
size_t aoff, bgrids;
int ncart = NCTR_CART * param[TENSOR] * param[POS_E1];
double *buf = malloc(sizeof(double) * BLKSIZE*(NPRIMAX*2+ncart));
#pragma omp for schedule(dynamic, 4)
for (k = 0; k < nblk*nshblk; k++) {
iloc = k / nblk;
ish = shloc[iloc];
aoff = ao_loc[ish] - ao_loc[sh0];
ib = k - iloc * nblk;
ip = ib * BLKSIZE;
bgrids = MIN(ngrids-ip, BLKSIZE);
(*fiter)(feval, fexp, fac, nao, Ngrids, bgrids,
param, shloc+iloc, ao_loc, buf, ao+aoff*Ngrids+ip,
coord+ip, non0table+ib*nbas,
atm, natm, bas, nbas, env);
}
free(buf);
}
}
void GTOeval_sph_drv(FPtr_eval feval, FPtr_exp fexp, double fac, int ngrids,
int param[], int *shls_slice, int *ao_loc,
double *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
GTOeval_loop(GTOeval_sph_iter, feval, fexp, fac, ngrids,
param, shls_slice, ao_loc,
ao, coord, non0table, atm, natm, bas, nbas, env);
}
void GTOeval_cart_drv(FPtr_eval feval, FPtr_exp fexp, double fac, int ngrids,
int param[], int *shls_slice, int *ao_loc,
double *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
GTOeval_loop(GTOeval_cart_iter, feval, fexp, fac, ngrids,
param, shls_slice, ao_loc,
ao, coord, non0table, atm, natm, bas, nbas, env);
}
void GTOeval_spinor_drv(FPtr_eval feval, FPtr_exp fexp, void (*c2s)(), double fac,
int ngrids, int param[], int *shls_slice, int *ao_loc,
double complex *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int shloc[shls_slice[1]-shls_slice[0]+1];
const int nshblk = GTOshloc_by_atom(shloc, shls_slice, ao_loc, atm, bas);
const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE;
const size_t Ngrids = ngrids;
#pragma omp parallel
{
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const size_t nao = ao_loc[sh1] - ao_loc[sh0];
int ip, ib, k, iloc, ish;
size_t aoff, bgrids;
int ncart = NCTR_CART * param[TENSOR] * param[POS_E1];
double *buf = malloc(sizeof(double) * BLKSIZE*(NPRIMAX*2+ncart));
#pragma omp for schedule(dynamic, 4)
for (k = 0; k < nblk*nshblk; k++) {
iloc = k / nblk;
ish = shloc[iloc];
aoff = ao_loc[ish] - ao_loc[sh0];
ib = k - iloc * nblk;
ip = ib * BLKSIZE;
bgrids = MIN(ngrids-ip, BLKSIZE);
GTOeval_spinor_iter(feval, fexp, c2s, fac,
nao, Ngrids, bgrids,
param, shloc+iloc, ao_loc, buf, ao+aoff*Ngrids+ip,
coord+ip, non0table+ib*nbas,
atm, natm, bas, nbas, env);
}
free(buf);
}
}
|
p_kernel.c |
#include <petscmat.h>
#include <petscsnes.h>
#include <petscvec.h>
#include <omp.h>
#include <geometry.h>
#include <ktime.h>
#ifdef __USE_HW_COUNTER
#include <perf.h>
#include <kperf.h>
#endif
#include <kernel.h>
#include <phy.h>
/*
Evaluate Function F(x): Functional form used to convey the
nonlinear function to be solved by PETSc SNES
*/
int
ffunc(SNES snes, Vec x, Vec f, void *restrict ctx)
{
struct ctx *restrict c = (struct ctx *) ctx;
const size_t nnodes = c->g->n->sz;
const size_t bsz = c->g->c->bsz;
int ierr;
const double *restrict q;
ierr = VecGetArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
struct grad grad;
{
grad.bsz = c->g->c->bsz;
grad.dofs = c->g->c->sz;
grad.ie = c->g->s->ie;
grad.part = c->g->s->part;
grad.n0 = c->g->e->eptr->n0;
grad.n1 = c->g->e->eptr->n1;
grad.w0termsx = c->g->e->w->w0->x0;
grad.w0termsy = c->g->e->w->w0->x1;
grad.w0termsz = c->g->e->w->w0->x2;
grad.w1termsx = c->g->e->w->w1->x0;
grad.w1termsy = c->g->e->w->w1->x1;
grad.w1termsz = c->g->e->w->w1->x2;
grad.q = q;
grad.gradx0 = c->grad->x0;
grad.gradx1 = c->grad->x1;
grad.gradx2 = c->grad->x2;
grad.t = &c->t->grad;
#ifdef __USE_HW_COUNTER
grad.perf_counters = c->perf_counters;
#endif
}
compute_grad(&grad);
double *restrict r;
ierr = VecGetArray(f, (PetscScalar **) &r);
CHKERRQ(ierr);
struct flux flux;
{
flux.bsz = c->g->c->bsz;
flux.nfnodes = c->g->b->f->n->sz;
flux.dofs = c->g->c->sz;
flux.snfc = c->g->s->snfc;
flux.pressure = c->iv->p;
flux.velocity_u = c->iv->u;
flux.velocity_v = c->iv->v;
flux.velocity_w = c->iv->w;
flux.f_xyz0 = c->g->b->f->n->xyz->x0;
flux.f_xyz1 = c->g->b->f->n->xyz->x1;
flux.f_xyz2 = c->g->b->f->n->xyz->x2;
flux.xyz0 = c->g->n->xyz->x0;
flux.xyz1 = c->g->n->xyz->x1;
flux.xyz2 = c->g->n->xyz->x2;
flux.ie = c->g->s->ie;
flux.part = c->g->s->part;
flux.snfic = c->g->s->snfic;
flux.n0 = c->g->e->eptr->n0;
flux.n1 = c->g->e->eptr->n1;
flux.nfptr = c->g->b->f->n->nptr;
flux.sn0 = c->g->b->snfptr->n0;
flux.sn1 = c->g->b->snfptr->n1;
flux.sn2 = c->g->b->snfptr->n2;
flux.x0 = c->g->e->xyzn->x0;
flux.x1 = c->g->e->xyzn->x1;
flux.x2 = c->g->e->xyzn->x2;
flux.x3 = c->g->e->xyzn->x3;
flux.q = q;
flux.gradx0 = c->grad->x0;
flux.gradx1 = c->grad->x1;
flux.gradx2 = c->grad->x2;
flux.r = r;
flux.t = &c->t->flux;
#ifdef __USE_HW_COUNTER
flux.perf_counters = c->perf_counters;
#endif
}
compute_flux(&flux);
#ifdef __USE_HW_COUNTER
const struct fd fd = c->perf_counters->fd;
struct counters start;
perf_read(fd, &start);
const uint64_t icycle = __rdtsc();
#endif
struct ktime ktime;
setktime(&ktime);
const double *restrict q_;
ierr = VecGetArrayRead(c->ts->q, (const PetscScalar **) &q_);
CHKERRQ(ierr);
const double *restrict area = c->g->n->area;
double *restrict cdt = c->ts->cdt;
const double cfl = c->ts->cfl;
uint32_t i;
#pragma omp parallel for
for(i = 0; i < nnodes; i++)
{
const double t = area[i] / (cfl * cdt[i]);
const uint32_t idx = bsz * i;
r[idx + 0] += t * (q[idx + 0] - q_[idx + 0]);
r[idx + 1] += t * (q[idx + 1] - q_[idx + 1]);
r[idx + 2] += t * (q[idx + 2] - q_[idx + 2]);
r[idx + 3] += t * (q[idx + 3] - q_[idx + 3]);
}
ierr = VecRestoreArrayRead(c->ts->q, (const PetscScalar **) &q_);
CHKERRQ(ierr);
compute_time(&ktime, &c->t->tstep_contr);
ierr = VecRestoreArray(f, (PetscScalar **) &r);
CHKERRQ(ierr);
ierr = VecRestoreArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
#ifdef __USE_HW_COUNTER
const uint64_t cycle = __rdtsc() - icycle;
struct counters end;
perf_read(fd, &end);
struct tot tot;
perf_calc(start, end, &tot);
c->perf_counters->ctrs->timestep.cycles += cycle;
c->perf_counters->ctrs->timestep.tot.imcR += tot.imcR;
c->perf_counters->ctrs->timestep.tot.imcW += tot.imcW;
c->perf_counters->ctrs->timestep.tot.edcR += tot.edcR;
c->perf_counters->ctrs->timestep.tot.edcW += tot.edcW;
#endif
return 0;
}
/*
Function used to convey the nonlinear Jacobian of the
function to be solved by SNES
Evaluate Jacobian F'(x)
Input vector; matrix that defines the approximate Jacobian;
matrix to be used to construct the preconditioner;
flag indicating information about the preconditioner matrix structure
user-defined context
*/
int
jfunc(SNES snes, Vec x, Mat Amat, Mat Pmat, void *restrict ctx)
{
struct ctx *restrict c = (struct ctx *) ctx;
/*
Resets a factored matrix to be treated as unfactored
*/
int ierr;
ierr = MatSetUnfactored(Pmat);
CHKERRQ(ierr);
const double *restrict q;
ierr = VecGetArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
/*
Fill the nonzero term of the A matrix
*/
struct fill fill;
{
fill.q = q;
fill.g = c->g;
fill.ts = c->ts;
fill.iv = c->iv;
fill.A = Pmat;
fill.t = c->t;
#ifdef __USE_HW_COUNTER
fill.perf_counters = c->perf_counters;
#endif
}
ierr = fill_mat(&fill);
CHKERRQ(ierr);
ierr = VecRestoreArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
ierr = MatAssemblyBegin(Amat, MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
ierr = MatAssemblyEnd(Amat, MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
return 0;
}
|
GB_unop__identity_fp32_int64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fp32_int64)
// op(A') function: GB (_unop_tran__identity_fp32_int64)
// C type: float
// A type: int64_t
// cast: float cij = (float) aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
float z = (float) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = (float) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fp32_int64)
(
float *Cx, // Cx and Ax may be aliased
const int64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
float z = (float) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int64_t aij = Ax [p] ;
float z = (float) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fp32_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__minv_uint64_uint64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__minv_uint64_uint64)
// op(A') function: GB (_unop_tran__minv_uint64_uint64)
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 64)
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_UNSIGNED (x, 64) ;
// casting
#define GB_CAST(z, aij) \
uint64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint64_t z = aij ; \
Cx [pC] = GB_IMINV_UNSIGNED (z, 64) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__minv_uint64_uint64)
(
uint64_t *Cx, // Cx and Ax may be aliased
const uint64_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++)
{
uint64_t aij = Ax [p] ;
uint64_t z = aij ;
Cx [p] = GB_IMINV_UNSIGNED (z, 64) ;
}
}
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 ;
uint64_t aij = Ax [p] ;
uint64_t z = aij ;
Cx [p] = GB_IMINV_UNSIGNED (z, 64) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__minv_uint64_uint64)
(
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
|
parser.c | /* C++ Parser.
Copyright (C) 2000, 2001, 2002, 2003, 2004,
2005 Free Software Foundation, Inc.
Written by Mark Mitchell <mark@codesourcery.com>.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "dyn-string.h"
#include "varray.h"
#include "cpplib.h"
#include "tree.h"
#include "cp-tree.h"
#include "c-pragma.h"
#include "decl.h"
#include "flags.h"
#include "diagnostic.h"
#include "toplev.h"
#include "output.h"
#include "target.h"
/* APPLE LOCAL 4133801 */
#include "debug.h"
#include "cgraph.h"
#include "c-common.h"
/* APPLE LOCAL pascal strings */
#include "../../libcpp/internal.h"
/* APPLE LOCAL C* language */
#include "tree-iterator.h"
/* The lexer. */
/* The cp_lexer_* routines mediate between the lexer proper (in libcpp
and c-lex.c) and the C++ parser. */
/* A token's value and its associated deferred access checks and
qualifying scope. */
struct tree_check GTY(())
{
/* The value associated with the token. */
tree value;
/* The checks that have been associated with value. */
VEC (deferred_access_check, gc)* checks;
/* The token's qualifying scope (used when it is a
CPP_NESTED_NAME_SPECIFIER). */
tree qualifying_scope;
};
/* A C++ token. */
typedef struct cp_token GTY (())
{
/* The kind of token. */
ENUM_BITFIELD (cpp_ttype) type : 8;
/* If this token is a keyword, this value indicates which keyword.
Otherwise, this value is RID_MAX. */
ENUM_BITFIELD (rid) keyword : 8;
/* Token flags. */
unsigned char flags;
/* Identifier for the pragma. */
ENUM_BITFIELD (pragma_kind) pragma_kind : 6;
/* True if this token is from a system header. */
BOOL_BITFIELD in_system_header : 1;
/* True if this token is from a context where it is implicitly extern "C" */
BOOL_BITFIELD implicit_extern_c : 1;
/* True for a CPP_NAME token that is not a keyword (i.e., for which
KEYWORD is RID_MAX) iff this name was looked up and found to be
ambiguous. An error has already been reported. */
BOOL_BITFIELD ambiguous_p : 1;
/* The input file stack index at which this token was found. */
unsigned input_file_stack_index : INPUT_FILE_STACK_BITS;
/* The value associated with this token, if any. */
union cp_token_value {
/* Used for CPP_NESTED_NAME_SPECIFIER and CPP_TEMPLATE_ID. */
struct tree_check* GTY((tag ("1"))) tree_check_value;
/* Use for all other tokens. */
tree GTY((tag ("0"))) value;
} GTY((desc ("(%1.type == CPP_TEMPLATE_ID) || (%1.type == CPP_NESTED_NAME_SPECIFIER)"))) u;
/* The location at which this token was found. */
location_t location;
} cp_token;
/* We use a stack of token pointer for saving token sets. */
typedef struct cp_token *cp_token_position;
DEF_VEC_P (cp_token_position);
DEF_VEC_ALLOC_P (cp_token_position,heap);
static const cp_token eof_token =
{
CPP_EOF, RID_MAX, 0, PRAGMA_NONE, 0, 0, false, 0, { NULL },
#if USE_MAPPED_LOCATION
0
#else
{0, 0}
#endif
};
/* The cp_lexer structure represents the C++ lexer. It is responsible
for managing the token stream from the preprocessor and supplying
it to the parser. Tokens are never added to the cp_lexer after
it is created. */
typedef struct cp_lexer GTY (())
{
/* The memory allocated for the buffer. NULL if this lexer does not
own the token buffer. */
cp_token * GTY ((length ("%h.buffer_length"))) buffer;
/* If the lexer owns the buffer, this is the number of tokens in the
buffer. */
size_t buffer_length;
/* A pointer just past the last available token. The tokens
in this lexer are [buffer, last_token). */
cp_token_position GTY ((skip)) last_token;
/* The next available token. If NEXT_TOKEN is &eof_token, then there are
no more available tokens. */
cp_token_position GTY ((skip)) next_token;
/* A stack indicating positions at which cp_lexer_save_tokens was
called. The top entry is the most recent position at which we
began saving tokens. If the stack is non-empty, we are saving
tokens. */
VEC(cp_token_position,heap) *GTY ((skip)) saved_tokens;
/* The next lexer in a linked list of lexers. */
struct cp_lexer *next;
/* True if we should output debugging information. */
bool debugging_p;
/* True if we're in the context of parsing a pragma, and should not
increment past the end-of-line marker. */
bool in_pragma;
} cp_lexer;
/* cp_token_cache is a range of tokens. There is no need to represent
allocate heap memory for it, since tokens are never removed from the
lexer's array. There is also no need for the GC to walk through
a cp_token_cache, since everything in here is referenced through
a lexer. */
typedef struct cp_token_cache GTY(())
{
/* The beginning of the token range. */
cp_token * GTY((skip)) first;
/* Points immediately after the last token in the range. */
cp_token * GTY ((skip)) last;
} cp_token_cache;
/* APPLE LOCAL begin C* language */
/* APPLE LOCAL radar 5130983 */
int lvalue_or_else (tree*, enum lvalue_use);
static void objc_finish_foreach_stmt (tree);
/* APPLE LOCAL end C* language */
/* Prototypes. */
static cp_lexer *cp_lexer_new_main
(void);
static cp_lexer *cp_lexer_new_from_tokens
(cp_token_cache *tokens);
static void cp_lexer_destroy
(cp_lexer *);
static int cp_lexer_saving_tokens
(const cp_lexer *);
static cp_token_position cp_lexer_token_position
(cp_lexer *, bool);
static cp_token *cp_lexer_token_at
(cp_lexer *, cp_token_position);
static void cp_lexer_get_preprocessor_token
(cp_lexer *, cp_token *);
static inline cp_token *cp_lexer_peek_token
(cp_lexer *);
static cp_token *cp_lexer_peek_nth_token
(cp_lexer *, size_t);
static inline bool cp_lexer_next_token_is
(cp_lexer *, enum cpp_ttype);
static bool cp_lexer_next_token_is_not
(cp_lexer *, enum cpp_ttype);
static bool cp_lexer_next_token_is_keyword
(cp_lexer *, enum rid);
static cp_token *cp_lexer_consume_token
(cp_lexer *);
static void cp_lexer_purge_token
(cp_lexer *);
static void cp_lexer_purge_tokens_after
(cp_lexer *, cp_token_position);
static void cp_lexer_save_tokens
(cp_lexer *);
static void cp_lexer_commit_tokens
(cp_lexer *);
static void cp_lexer_rollback_tokens
(cp_lexer *);
#ifdef ENABLE_CHECKING
static void cp_lexer_print_token
(FILE *, cp_token *);
static inline bool cp_lexer_debugging_p
(cp_lexer *);
static void cp_lexer_start_debugging
(cp_lexer *) ATTRIBUTE_UNUSED;
static void cp_lexer_stop_debugging
(cp_lexer *) ATTRIBUTE_UNUSED;
#else
/* If we define cp_lexer_debug_stream to NULL it will provoke warnings
about passing NULL to functions that require non-NULL arguments
(fputs, fprintf). It will never be used, so all we need is a value
of the right type that's guaranteed not to be NULL. */
#define cp_lexer_debug_stream stdout
#define cp_lexer_print_token(str, tok) (void) 0
#define cp_lexer_debugging_p(lexer) 0
#endif /* ENABLE_CHECKING */
static cp_token_cache *cp_token_cache_new
(cp_token *, cp_token *);
static void cp_parser_initial_pragma
(cp_token *);
/* Manifest constants. */
#define CP_LEXER_BUFFER_SIZE ((256 * 1024) / sizeof (cp_token))
#define CP_SAVED_TOKEN_STACK 5
/* A token type for keywords, as opposed to ordinary identifiers. */
#define CPP_KEYWORD ((enum cpp_ttype) (N_TTYPES + 1))
/* A token type for template-ids. If a template-id is processed while
parsing tentatively, it is replaced with a CPP_TEMPLATE_ID token;
the value of the CPP_TEMPLATE_ID is whatever was returned by
cp_parser_template_id. */
#define CPP_TEMPLATE_ID ((enum cpp_ttype) (CPP_KEYWORD + 1))
/* A token type for nested-name-specifiers. If a
nested-name-specifier is processed while parsing tentatively, it is
replaced with a CPP_NESTED_NAME_SPECIFIER token; the value of the
CPP_NESTED_NAME_SPECIFIER is whatever was returned by
cp_parser_nested_name_specifier_opt. */
#define CPP_NESTED_NAME_SPECIFIER ((enum cpp_ttype) (CPP_TEMPLATE_ID + 1))
/* A token type for tokens that are not tokens at all; these are used
to represent slots in the array where there used to be a token
that has now been deleted. */
#define CPP_PURGED ((enum cpp_ttype) (CPP_NESTED_NAME_SPECIFIER + 1))
/* The number of token types, including C++-specific ones. */
#define N_CP_TTYPES ((int) (CPP_PURGED + 1))
/* Variables. */
#ifdef ENABLE_CHECKING
/* The stream to which debugging output should be written. */
static FILE *cp_lexer_debug_stream;
#endif /* ENABLE_CHECKING */
/* Create a new main C++ lexer, the lexer that gets tokens from the
preprocessor. */
static cp_lexer *
cp_lexer_new_main (void)
{
cp_token first_token;
cp_lexer *lexer;
cp_token *pos;
size_t alloc;
size_t space;
cp_token *buffer;
/* APPLE LOCAL begin 4137741 */
/* Tell cpplib we want CPP_BINCL and CPP_EINCL tokens. */
cpp_get_options (parse_in)->defer_file_change_debug_hooks = true;
/* APPLE LOCAL end 4137741 */
/* It's possible that parsing the first pragma will load a PCH file,
which is a GC collection point. So we have to do that before
allocating any memory. */
cp_parser_initial_pragma (&first_token);
/* APPLE LOCAL begin 4137741 */
while (first_token.type == CPP_BINCL
|| first_token.type == CPP_EINCL)
{
if (first_token.type == CPP_BINCL)
(*debug_hooks->start_source_file) (TREE_INT_CST_LOW (first_token.u.value),
first_token.location.file);
else
(*debug_hooks->end_source_file) (TREE_INT_CST_LOW (first_token.u.value));
cp_lexer_get_preprocessor_token (NULL, &first_token);
}
/* APPLE LOCAL end 4137741 */
/* Tell c_lex_with_flags not to merge string constants. */
c_lex_return_raw_strings = true;
c_common_no_more_pch ();
/* Allocate the memory. */
lexer = GGC_CNEW (cp_lexer);
#ifdef ENABLE_CHECKING
/* Initially we are not debugging. */
lexer->debugging_p = false;
#endif /* ENABLE_CHECKING */
lexer->saved_tokens = VEC_alloc (cp_token_position, heap,
CP_SAVED_TOKEN_STACK);
/* Create the buffer. */
alloc = CP_LEXER_BUFFER_SIZE;
buffer = GGC_NEWVEC (cp_token, alloc);
/* Put the first token in the buffer. */
space = alloc;
pos = buffer;
*pos = first_token;
/* Get the remaining tokens from the preprocessor. */
while (pos->type != CPP_EOF)
{
pos++;
if (!--space)
{
space = alloc;
alloc *= 2;
buffer = GGC_RESIZEVEC (cp_token, buffer, alloc);
pos = buffer + space;
}
cp_lexer_get_preprocessor_token (lexer, pos);
}
lexer->buffer = buffer;
lexer->buffer_length = alloc - space;
lexer->last_token = pos;
lexer->next_token = lexer->buffer_length ? buffer : (cp_token *)&eof_token;
/* Subsequent preprocessor diagnostics should use compiler
diagnostic functions to get the compiler source location. */
cpp_get_options (parse_in)->client_diagnostic = true;
cpp_get_callbacks (parse_in)->error = cp_cpp_error;
gcc_assert (lexer->next_token->type != CPP_PURGED);
return lexer;
}
/* Create a new lexer whose token stream is primed with the tokens in
CACHE. When these tokens are exhausted, no new tokens will be read. */
static cp_lexer *
cp_lexer_new_from_tokens (cp_token_cache *cache)
{
cp_token *first = cache->first;
cp_token *last = cache->last;
cp_lexer *lexer = GGC_CNEW (cp_lexer);
/* We do not own the buffer. */
lexer->buffer = NULL;
lexer->buffer_length = 0;
lexer->next_token = first == last ? (cp_token *)&eof_token : first;
lexer->last_token = last;
lexer->saved_tokens = VEC_alloc (cp_token_position, heap,
CP_SAVED_TOKEN_STACK);
#ifdef ENABLE_CHECKING
/* Initially we are not debugging. */
lexer->debugging_p = false;
#endif
gcc_assert (lexer->next_token->type != CPP_PURGED);
return lexer;
}
/* Frees all resources associated with LEXER. */
static void
cp_lexer_destroy (cp_lexer *lexer)
{
if (lexer->buffer)
ggc_free (lexer->buffer);
VEC_free (cp_token_position, heap, lexer->saved_tokens);
ggc_free (lexer);
}
/* Returns nonzero if debugging information should be output. */
#ifdef ENABLE_CHECKING
static inline bool
cp_lexer_debugging_p (cp_lexer *lexer)
{
return lexer->debugging_p;
}
#endif /* ENABLE_CHECKING */
static inline cp_token_position
cp_lexer_token_position (cp_lexer *lexer, bool previous_p)
{
gcc_assert (!previous_p || lexer->next_token != &eof_token);
return lexer->next_token - previous_p;
}
static inline cp_token *
cp_lexer_token_at (cp_lexer *lexer ATTRIBUTE_UNUSED, cp_token_position pos)
{
return pos;
}
/* nonzero if we are presently saving tokens. */
static inline int
cp_lexer_saving_tokens (const cp_lexer* lexer)
{
return VEC_length (cp_token_position, lexer->saved_tokens) != 0;
}
/* Store the next token from the preprocessor in *TOKEN. Return true
if we reach EOF. */
static void
cp_lexer_get_preprocessor_token (cp_lexer *lexer ATTRIBUTE_UNUSED ,
cp_token *token)
{
static int is_extern_c = 0;
/* Get a new token from the preprocessor. */
token->type
/* APPLE LOCAL CW asm blocks C++ comments 6338079 */
= c_lex_with_flags (&token->u.value, &token->location, &token->flags, 1);
token->input_file_stack_index = input_file_stack_tick;
token->keyword = RID_MAX;
token->pragma_kind = PRAGMA_NONE;
token->in_system_header = in_system_header;
/* On some systems, some header files are surrounded by an
implicit extern "C" block. Set a flag in the token if it
comes from such a header. */
is_extern_c += pending_lang_change;
pending_lang_change = 0;
token->implicit_extern_c = is_extern_c > 0;
/* Check to see if this token is a keyword. */
if (token->type == CPP_NAME)
{
if (C_IS_RESERVED_WORD (token->u.value))
{
/* Mark this token as a keyword. */
token->type = CPP_KEYWORD;
/* Record which keyword. */
token->keyword = C_RID_CODE (token->u.value);
/* Update the value. Some keywords are mapped to particular
entities, rather than simply having the value of the
corresponding IDENTIFIER_NODE. For example, `__const' is
mapped to `const'. */
token->u.value = ridpointers[token->keyword];
}
else
{
token->ambiguous_p = false;
token->keyword = RID_MAX;
}
}
/* Handle Objective-C++ keywords. */
else if (token->type == CPP_AT_NAME)
{
token->type = CPP_KEYWORD;
switch (C_RID_CODE (token->u.value))
{
/* Map 'class' to '@class', 'private' to '@private', etc. */
case RID_CLASS: token->keyword = RID_AT_CLASS; break;
/* APPLE LOCAL radar 4564694 */
case RID_AT_PACKAGE: token->keyword = RID_AT_PACKAGE; break;
case RID_PRIVATE: token->keyword = RID_AT_PRIVATE; break;
case RID_PROTECTED: token->keyword = RID_AT_PROTECTED; break;
case RID_PUBLIC: token->keyword = RID_AT_PUBLIC; break;
case RID_THROW: token->keyword = RID_AT_THROW; break;
case RID_TRY: token->keyword = RID_AT_TRY; break;
case RID_CATCH: token->keyword = RID_AT_CATCH; break;
default: token->keyword = C_RID_CODE (token->u.value);
}
}
else if (token->type == CPP_PRAGMA)
{
/* We smuggled the cpp_token->u.pragma value in an INTEGER_CST. */
token->pragma_kind = TREE_INT_CST_LOW (token->u.value);
token->u.value = NULL_TREE;
}
}
/* Update the globals input_location and in_system_header and the
input file stack from TOKEN. */
static inline void
cp_lexer_set_source_position_from_token (cp_token *token)
{
if (token->type != CPP_EOF)
{
input_location = token->location;
in_system_header = token->in_system_header;
restore_input_file_stack (token->input_file_stack_index);
}
}
/* APPLE LOCAL begin 4137741 */
/* Consume begin and end file marker tokens. */
static inline void
cp_lexer_consume_bincl_eincl_token (cp_lexer *lexer)
{
while (lexer->next_token->type == CPP_BINCL
|| lexer->next_token->type == CPP_EINCL)
{
if (lexer->next_token->type == CPP_BINCL)
(*debug_hooks->start_source_file) (TREE_INT_CST_LOW (lexer->next_token->u.value),
lexer->next_token->location.file);
else if (lexer->next_token->type == CPP_EINCL)
(*debug_hooks->end_source_file) (TREE_INT_CST_LOW (lexer->next_token->u.value));
cp_lexer_purge_token (lexer);
}
}
/* APPLE LOCAL end 4137741 */
/* Return a pointer to the next token in the token stream, but do not
consume it. */
static inline cp_token *
cp_lexer_peek_token (cp_lexer *lexer)
{
/* APPLE LOCAL begin CW asm blocks */
top:
if (flag_ms_asms)
if (lexer->next_token->type == CPP_NUMBER
&& lexer->next_token->u.value == error_mark_node
&& (lexer->next_token->flags & ERROR_DEFERRED))
{
cp_lexer_set_source_position_from_token (lexer->next_token);
/* This was previously deferred. */
lexer->next_token->flags ^= ERROR_DEFERRED;
error ("invalid suffix on integer constant");
}
if (!inside_iasm_block)
{
if (lexer->next_token->type == CPP_HASH)
{
cp_lexer_consume_token (lexer);
error ("stray %qs in program", "#");
goto top;
}
else if (lexer->next_token->type == CPP_PASTE)
{
cp_lexer_consume_token (lexer);
error ("stray %qs in program", "##");
goto top;
}
else if (lexer->next_token->type == CPP_OTHER)
{
tree value = lexer->next_token->u.value;
int c;
c = TREE_INT_CST_LOW (value);
cp_lexer_consume_token (lexer);
if (c == '"' || c == '\'')
error ("missing terminating %c character", (int) c);
else if (ISGRAPH (c))
error ("stray %qc in program", (int) c);
else
error ("stray %<\\%o%> in program", (int) c);
goto top;
}
}
/* APPLE LOCAL end CW asm blocks */
/* APPLE LOCAL 4137741 */
cp_lexer_consume_bincl_eincl_token (lexer);
if (cp_lexer_debugging_p (lexer))
{
fputs ("cp_lexer: peeking at token: ", cp_lexer_debug_stream);
cp_lexer_print_token (cp_lexer_debug_stream, lexer->next_token);
putc ('\n', cp_lexer_debug_stream);
}
return lexer->next_token;
}
/* Return true if the next token has the indicated TYPE. */
static inline bool
cp_lexer_next_token_is (cp_lexer* lexer, enum cpp_ttype type)
{
return cp_lexer_peek_token (lexer)->type == type;
}
/* Return true if the next token does not have the indicated TYPE. */
static inline bool
cp_lexer_next_token_is_not (cp_lexer* lexer, enum cpp_ttype type)
{
return !cp_lexer_next_token_is (lexer, type);
}
/* Return true if the next token is the indicated KEYWORD. */
static inline bool
cp_lexer_next_token_is_keyword (cp_lexer* lexer, enum rid keyword)
{
return cp_lexer_peek_token (lexer)->keyword == keyword;
}
/* Return true if the next token is a keyword for a decl-specifier. */
static bool
cp_lexer_next_token_is_decl_specifier_keyword (cp_lexer *lexer)
{
cp_token *token;
token = cp_lexer_peek_token (lexer);
switch (token->keyword)
{
/* Storage classes. */
case RID_AUTO:
case RID_REGISTER:
case RID_STATIC:
case RID_EXTERN:
case RID_MUTABLE:
case RID_THREAD:
/* Elaborated type specifiers. */
case RID_ENUM:
case RID_CLASS:
case RID_STRUCT:
case RID_UNION:
case RID_TYPENAME:
/* Simple type specifiers. */
case RID_CHAR:
case RID_WCHAR:
case RID_BOOL:
case RID_SHORT:
case RID_INT:
case RID_LONG:
case RID_SIGNED:
case RID_UNSIGNED:
case RID_FLOAT:
case RID_DOUBLE:
case RID_VOID:
/* GNU extensions. */
case RID_ATTRIBUTE:
case RID_TYPEOF:
return true;
default:
return false;
}
}
/* Return a pointer to the Nth token in the token stream. If N is 1,
then this is precisely equivalent to cp_lexer_peek_token (except
that it is not inline). One would like to disallow that case, but
there is one case (cp_parser_nth_token_starts_template_id) where
the caller passes a variable for N and it might be 1. */
static cp_token *
cp_lexer_peek_nth_token (cp_lexer* lexer, size_t n)
{
cp_token *token;
/* N is 1-based, not zero-based. */
gcc_assert (n > 0);
if (cp_lexer_debugging_p (lexer))
fprintf (cp_lexer_debug_stream,
"cp_lexer: peeking ahead %ld at token: ", (long)n);
--n;
token = lexer->next_token;
gcc_assert (!n || token != &eof_token);
while (n != 0)
{
++token;
if (token == lexer->last_token)
{
token = (cp_token *)&eof_token;
break;
}
/* APPLE LOCAL begin 4137741 */
if (token->type != CPP_PURGED
&& token->type != CPP_BINCL
&& token->type != CPP_EINCL)
/* APPLE LOCAL end 4137741 */
--n;
}
if (cp_lexer_debugging_p (lexer))
{
cp_lexer_print_token (cp_lexer_debug_stream, token);
putc ('\n', cp_lexer_debug_stream);
}
return token;
}
/* Return the next token, and advance the lexer's next_token pointer
to point to the next non-purged token. */
static cp_token *
cp_lexer_consume_token (cp_lexer* lexer)
{
cp_token *token = lexer->next_token;
gcc_assert (token != &eof_token);
gcc_assert (!lexer->in_pragma || token->type != CPP_PRAGMA_EOL);
do
{
lexer->next_token++;
/* APPLE LOCAL 4137741 */
cp_lexer_consume_bincl_eincl_token (lexer);
if (lexer->next_token == lexer->last_token)
{
lexer->next_token = (cp_token *)&eof_token;
break;
}
}
while (lexer->next_token->type == CPP_PURGED);
cp_lexer_set_source_position_from_token (token);
/* Provide debugging output. */
if (cp_lexer_debugging_p (lexer))
{
fputs ("cp_lexer: consuming token: ", cp_lexer_debug_stream);
cp_lexer_print_token (cp_lexer_debug_stream, token);
putc ('\n', cp_lexer_debug_stream);
}
return token;
}
/* Permanently remove the next token from the token stream, and
advance the next_token pointer to refer to the next non-purged
token. */
static void
cp_lexer_purge_token (cp_lexer *lexer)
{
cp_token *tok = lexer->next_token;
gcc_assert (tok != &eof_token);
tok->type = CPP_PURGED;
tok->location = UNKNOWN_LOCATION;
tok->u.value = NULL_TREE;
tok->keyword = RID_MAX;
do
{
tok++;
if (tok == lexer->last_token)
{
tok = (cp_token *)&eof_token;
break;
}
}
while (tok->type == CPP_PURGED);
lexer->next_token = tok;
}
/* Permanently remove all tokens after TOK, up to, but not
including, the token that will be returned next by
cp_lexer_peek_token. */
static void
cp_lexer_purge_tokens_after (cp_lexer *lexer, cp_token *tok)
{
cp_token *peek = lexer->next_token;
if (peek == &eof_token)
peek = lexer->last_token;
gcc_assert (tok < peek);
for ( tok += 1; tok != peek; tok += 1)
{
tok->type = CPP_PURGED;
tok->location = UNKNOWN_LOCATION;
tok->u.value = NULL_TREE;
tok->keyword = RID_MAX;
}
}
/* Begin saving tokens. All tokens consumed after this point will be
preserved. */
static void
cp_lexer_save_tokens (cp_lexer* lexer)
{
/* Provide debugging output. */
if (cp_lexer_debugging_p (lexer))
fprintf (cp_lexer_debug_stream, "cp_lexer: saving tokens\n");
VEC_safe_push (cp_token_position, heap,
lexer->saved_tokens, lexer->next_token);
}
/* Commit to the portion of the token stream most recently saved. */
static void
cp_lexer_commit_tokens (cp_lexer* lexer)
{
/* Provide debugging output. */
if (cp_lexer_debugging_p (lexer))
fprintf (cp_lexer_debug_stream, "cp_lexer: committing tokens\n");
VEC_pop (cp_token_position, lexer->saved_tokens);
}
/* Return all tokens saved since the last call to cp_lexer_save_tokens
to the token stream. Stop saving tokens. */
static void
cp_lexer_rollback_tokens (cp_lexer* lexer)
{
/* Provide debugging output. */
if (cp_lexer_debugging_p (lexer))
fprintf (cp_lexer_debug_stream, "cp_lexer: restoring tokens\n");
lexer->next_token = VEC_pop (cp_token_position, lexer->saved_tokens);
}
/* Print a representation of the TOKEN on the STREAM. */
#ifdef ENABLE_CHECKING
static void
cp_lexer_print_token (FILE * stream, cp_token *token)
{
/* We don't use cpp_type2name here because the parser defines
a few tokens of its own. */
static const char *const token_names[] = {
/* cpplib-defined token types */
#define OP(e, s) #e,
#define TK(e, s) #e,
TTYPE_TABLE
#undef OP
#undef TK
/* C++ parser token types - see "Manifest constants", above. */
"KEYWORD",
"TEMPLATE_ID",
"NESTED_NAME_SPECIFIER",
"PURGED"
};
/* If we have a name for the token, print it out. Otherwise, we
simply give the numeric code. */
gcc_assert (token->type < ARRAY_SIZE(token_names));
fputs (token_names[token->type], stream);
/* For some tokens, print the associated data. */
switch (token->type)
{
case CPP_KEYWORD:
/* Some keywords have a value that is not an IDENTIFIER_NODE.
For example, `struct' is mapped to an INTEGER_CST. */
if (TREE_CODE (token->u.value) != IDENTIFIER_NODE)
break;
/* else fall through */
case CPP_NAME:
fputs (IDENTIFIER_POINTER (token->u.value), stream);
break;
case CPP_STRING:
case CPP_WSTRING:
fprintf (stream, " \"%s\"", TREE_STRING_POINTER (token->u.value));
break;
default:
break;
}
}
/* Start emitting debugging information. */
static void
cp_lexer_start_debugging (cp_lexer* lexer)
{
lexer->debugging_p = true;
}
/* Stop emitting debugging information. */
static void
cp_lexer_stop_debugging (cp_lexer* lexer)
{
lexer->debugging_p = false;
}
#endif /* ENABLE_CHECKING */
/* Create a new cp_token_cache, representing a range of tokens. */
static cp_token_cache *
cp_token_cache_new (cp_token *first, cp_token *last)
{
cp_token_cache *cache = GGC_NEW (cp_token_cache);
cache->first = first;
cache->last = last;
return cache;
}
/* Decl-specifiers. */
/* Set *DECL_SPECS to represent an empty decl-specifier-seq. */
static void
clear_decl_specs (cp_decl_specifier_seq *decl_specs)
{
memset (decl_specs, 0, sizeof (cp_decl_specifier_seq));
}
/* Declarators. */
/* Nothing other than the parser should be creating declarators;
declarators are a semi-syntactic representation of C++ entities.
Other parts of the front end that need to create entities (like
VAR_DECLs or FUNCTION_DECLs) should do that directly. */
static cp_declarator *make_call_declarator
(cp_declarator *, cp_parameter_declarator *, cp_cv_quals, tree);
static cp_declarator *make_array_declarator
(cp_declarator *, tree);
static cp_declarator *make_pointer_declarator
(cp_cv_quals, cp_declarator *);
static cp_declarator *make_reference_declarator
(cp_cv_quals, cp_declarator *);
static cp_parameter_declarator *make_parameter_declarator
(cp_decl_specifier_seq *, cp_declarator *, tree);
static cp_declarator *make_ptrmem_declarator
(cp_cv_quals, tree, cp_declarator *);
/* An erroneous declarator. */
static cp_declarator *cp_error_declarator;
/* The obstack on which declarators and related data structures are
allocated. */
static struct obstack declarator_obstack;
/* Alloc BYTES from the declarator memory pool. */
static inline void *
alloc_declarator (size_t bytes)
{
return obstack_alloc (&declarator_obstack, bytes);
}
/* Allocate a declarator of the indicated KIND. Clear fields that are
common to all declarators. */
static cp_declarator *
make_declarator (cp_declarator_kind kind)
{
cp_declarator *declarator;
declarator = (cp_declarator *) alloc_declarator (sizeof (cp_declarator));
declarator->kind = kind;
declarator->attributes = NULL_TREE;
declarator->declarator = NULL;
return declarator;
}
/* Make a declarator for a generalized identifier. If
QUALIFYING_SCOPE is non-NULL, the identifier is
QUALIFYING_SCOPE::UNQUALIFIED_NAME; otherwise, it is just
UNQUALIFIED_NAME. SFK indicates the kind of special function this
is, if any. */
static cp_declarator *
make_id_declarator (tree qualifying_scope, tree unqualified_name,
special_function_kind sfk)
{
cp_declarator *declarator;
/* It is valid to write:
class C { void f(); };
typedef C D;
void D::f();
The standard is not clear about whether `typedef const C D' is
legal; as of 2002-09-15 the committee is considering that
question. EDG 3.0 allows that syntax. Therefore, we do as
well. */
if (qualifying_scope && TYPE_P (qualifying_scope))
qualifying_scope = TYPE_MAIN_VARIANT (qualifying_scope);
gcc_assert (TREE_CODE (unqualified_name) == IDENTIFIER_NODE
|| TREE_CODE (unqualified_name) == BIT_NOT_EXPR
|| TREE_CODE (unqualified_name) == TEMPLATE_ID_EXPR);
declarator = make_declarator (cdk_id);
declarator->u.id.qualifying_scope = qualifying_scope;
declarator->u.id.unqualified_name = unqualified_name;
declarator->u.id.sfk = sfk;
return declarator;
}
/* Make a declarator for a pointer to TARGET. CV_QUALIFIERS is a list
of modifiers such as const or volatile to apply to the pointer
type, represented as identifiers. */
cp_declarator *
make_pointer_declarator (cp_cv_quals cv_qualifiers, cp_declarator *target)
{
cp_declarator *declarator;
declarator = make_declarator (cdk_pointer);
declarator->declarator = target;
declarator->u.pointer.qualifiers = cv_qualifiers;
declarator->u.pointer.class_type = NULL_TREE;
return declarator;
}
/* Like make_pointer_declarator -- but for references. */
cp_declarator *
make_reference_declarator (cp_cv_quals cv_qualifiers, cp_declarator *target)
{
cp_declarator *declarator;
declarator = make_declarator (cdk_reference);
declarator->declarator = target;
declarator->u.pointer.qualifiers = cv_qualifiers;
declarator->u.pointer.class_type = NULL_TREE;
return declarator;
}
/* Like make_pointer_declarator -- but for a pointer to a non-static
member of CLASS_TYPE. */
cp_declarator *
make_ptrmem_declarator (cp_cv_quals cv_qualifiers, tree class_type,
cp_declarator *pointee)
{
cp_declarator *declarator;
declarator = make_declarator (cdk_ptrmem);
declarator->declarator = pointee;
declarator->u.pointer.qualifiers = cv_qualifiers;
declarator->u.pointer.class_type = class_type;
return declarator;
}
/* Make a declarator for the function given by TARGET, with the
indicated PARMS. The CV_QUALIFIERS aply to the function, as in
"const"-qualified member function. The EXCEPTION_SPECIFICATION
indicates what exceptions can be thrown. */
cp_declarator *
make_call_declarator (cp_declarator *target,
cp_parameter_declarator *parms,
cp_cv_quals cv_qualifiers,
tree exception_specification)
{
cp_declarator *declarator;
declarator = make_declarator (cdk_function);
declarator->declarator = target;
declarator->u.function.parameters = parms;
declarator->u.function.qualifiers = cv_qualifiers;
declarator->u.function.exception_specification = exception_specification;
return declarator;
}
/* Make a declarator for an array of BOUNDS elements, each of which is
defined by ELEMENT. */
cp_declarator *
make_array_declarator (cp_declarator *element, tree bounds)
{
cp_declarator *declarator;
declarator = make_declarator (cdk_array);
declarator->declarator = element;
declarator->u.array.bounds = bounds;
return declarator;
}
cp_parameter_declarator *no_parameters;
/* Create a parameter declarator with the indicated DECL_SPECIFIERS,
DECLARATOR and DEFAULT_ARGUMENT. */
cp_parameter_declarator *
make_parameter_declarator (cp_decl_specifier_seq *decl_specifiers,
cp_declarator *declarator,
tree default_argument)
{
cp_parameter_declarator *parameter;
parameter = ((cp_parameter_declarator *)
alloc_declarator (sizeof (cp_parameter_declarator)));
parameter->next = NULL;
if (decl_specifiers)
parameter->decl_specifiers = *decl_specifiers;
else
clear_decl_specs (¶meter->decl_specifiers);
parameter->declarator = declarator;
parameter->default_argument = default_argument;
parameter->ellipsis_p = false;
return parameter;
}
/* Returns true iff DECLARATOR is a declaration for a function. */
static bool
function_declarator_p (const cp_declarator *declarator)
{
while (declarator)
{
if (declarator->kind == cdk_function
&& declarator->declarator->kind == cdk_id)
return true;
if (declarator->kind == cdk_id
|| declarator->kind == cdk_error)
return false;
declarator = declarator->declarator;
}
return false;
}
/* The parser. */
/* Overview
--------
A cp_parser parses the token stream as specified by the C++
grammar. Its job is purely parsing, not semantic analysis. For
example, the parser breaks the token stream into declarators,
expressions, statements, and other similar syntactic constructs.
It does not check that the types of the expressions on either side
of an assignment-statement are compatible, or that a function is
not declared with a parameter of type `void'.
The parser invokes routines elsewhere in the compiler to perform
semantic analysis and to build up the abstract syntax tree for the
code processed.
The parser (and the template instantiation code, which is, in a
way, a close relative of parsing) are the only parts of the
compiler that should be calling push_scope and pop_scope, or
related functions. The parser (and template instantiation code)
keeps track of what scope is presently active; everything else
should simply honor that. (The code that generates static
initializers may also need to set the scope, in order to check
access control correctly when emitting the initializers.)
Methodology
-----------
The parser is of the standard recursive-descent variety. Upcoming
tokens in the token stream are examined in order to determine which
production to use when parsing a non-terminal. Some C++ constructs
require arbitrary look ahead to disambiguate. For example, it is
impossible, in the general case, to tell whether a statement is an
expression or declaration without scanning the entire statement.
Therefore, the parser is capable of "parsing tentatively." When the
parser is not sure what construct comes next, it enters this mode.
Then, while we attempt to parse the construct, the parser queues up
error messages, rather than issuing them immediately, and saves the
tokens it consumes. If the construct is parsed successfully, the
parser "commits", i.e., it issues any queued error messages and
the tokens that were being preserved are permanently discarded.
If, however, the construct is not parsed successfully, the parser
rolls back its state completely so that it can resume parsing using
a different alternative.
Future Improvements
-------------------
The performance of the parser could probably be improved substantially.
We could often eliminate the need to parse tentatively by looking ahead
a little bit. In some places, this approach might not entirely eliminate
the need to parse tentatively, but it might still speed up the average
case. */
/* Flags that are passed to some parsing functions. These values can
be bitwise-ored together. */
typedef enum cp_parser_flags
{
/* No flags. */
CP_PARSER_FLAGS_NONE = 0x0,
/* The construct is optional. If it is not present, then no error
should be issued. */
CP_PARSER_FLAGS_OPTIONAL = 0x1,
/* When parsing a type-specifier, do not allow user-defined types. */
CP_PARSER_FLAGS_NO_USER_DEFINED_TYPES = 0x2
} cp_parser_flags;
/* The different kinds of declarators we want to parse. */
typedef enum cp_parser_declarator_kind
{
/* APPLE LOCAL begin blocks 6339747 */
/* We want a block declarator. */
CP_PARSER_DECLARATOR_BLOCK,
/* APPLE LOCAL end blocks 6339747 */
/* We want an abstract declarator. */
CP_PARSER_DECLARATOR_ABSTRACT,
/* We want a named declarator. */
CP_PARSER_DECLARATOR_NAMED,
/* We don't mind, but the name must be an unqualified-id. */
CP_PARSER_DECLARATOR_EITHER
} cp_parser_declarator_kind;
/* The precedence values used to parse binary expressions. The minimum value
of PREC must be 1, because zero is reserved to quickly discriminate
binary operators from other tokens. */
enum cp_parser_prec
{
PREC_NOT_OPERATOR,
PREC_LOGICAL_OR_EXPRESSION,
PREC_LOGICAL_AND_EXPRESSION,
PREC_INCLUSIVE_OR_EXPRESSION,
PREC_EXCLUSIVE_OR_EXPRESSION,
PREC_AND_EXPRESSION,
PREC_EQUALITY_EXPRESSION,
PREC_RELATIONAL_EXPRESSION,
PREC_SHIFT_EXPRESSION,
PREC_ADDITIVE_EXPRESSION,
PREC_MULTIPLICATIVE_EXPRESSION,
PREC_PM_EXPRESSION,
NUM_PREC_VALUES = PREC_PM_EXPRESSION
};
/* A mapping from a token type to a corresponding tree node type, with a
precedence value. */
typedef struct cp_parser_binary_operations_map_node
{
/* The token type. */
enum cpp_ttype token_type;
/* The corresponding tree code. */
enum tree_code tree_type;
/* The precedence of this operator. */
enum cp_parser_prec prec;
} cp_parser_binary_operations_map_node;
/* The status of a tentative parse. */
typedef enum cp_parser_status_kind
{
/* No errors have occurred. */
CP_PARSER_STATUS_KIND_NO_ERROR,
/* An error has occurred. */
CP_PARSER_STATUS_KIND_ERROR,
/* We are committed to this tentative parse, whether or not an error
has occurred. */
CP_PARSER_STATUS_KIND_COMMITTED
} cp_parser_status_kind;
typedef struct cp_parser_expression_stack_entry
{
tree lhs;
enum tree_code tree_type;
int prec;
} cp_parser_expression_stack_entry;
/* The stack for storing partial expressions. We only need NUM_PREC_VALUES
entries because precedence levels on the stack are monotonically
increasing. */
typedef struct cp_parser_expression_stack_entry
cp_parser_expression_stack[NUM_PREC_VALUES];
/* Context that is saved and restored when parsing tentatively. */
typedef struct cp_parser_context GTY (())
{
/* If this is a tentative parsing context, the status of the
tentative parse. */
enum cp_parser_status_kind status;
/* If non-NULL, we have just seen a `x->' or `x.' expression. Names
that are looked up in this context must be looked up both in the
scope given by OBJECT_TYPE (the type of `x' or `*x') and also in
the context of the containing expression. */
tree object_type;
/* The next parsing context in the stack. */
struct cp_parser_context *next;
} cp_parser_context;
/* Prototypes. */
/* Constructors and destructors. */
static cp_parser_context *cp_parser_context_new
(cp_parser_context *);
/* Class variables. */
static GTY((deletable)) cp_parser_context* cp_parser_context_free_list;
/* The operator-precedence table used by cp_parser_binary_expression.
Transformed into an associative array (binops_by_token) by
cp_parser_new. */
static const cp_parser_binary_operations_map_node binops[] = {
{ CPP_DEREF_STAR, MEMBER_REF, PREC_PM_EXPRESSION },
{ CPP_DOT_STAR, DOTSTAR_EXPR, PREC_PM_EXPRESSION },
{ CPP_MULT, MULT_EXPR, PREC_MULTIPLICATIVE_EXPRESSION },
{ CPP_DIV, TRUNC_DIV_EXPR, PREC_MULTIPLICATIVE_EXPRESSION },
{ CPP_MOD, TRUNC_MOD_EXPR, PREC_MULTIPLICATIVE_EXPRESSION },
{ CPP_PLUS, PLUS_EXPR, PREC_ADDITIVE_EXPRESSION },
{ CPP_MINUS, MINUS_EXPR, PREC_ADDITIVE_EXPRESSION },
{ CPP_LSHIFT, LSHIFT_EXPR, PREC_SHIFT_EXPRESSION },
{ CPP_RSHIFT, RSHIFT_EXPR, PREC_SHIFT_EXPRESSION },
{ CPP_LESS, LT_EXPR, PREC_RELATIONAL_EXPRESSION },
{ CPP_GREATER, GT_EXPR, PREC_RELATIONAL_EXPRESSION },
{ CPP_LESS_EQ, LE_EXPR, PREC_RELATIONAL_EXPRESSION },
{ CPP_GREATER_EQ, GE_EXPR, PREC_RELATIONAL_EXPRESSION },
{ CPP_EQ_EQ, EQ_EXPR, PREC_EQUALITY_EXPRESSION },
{ CPP_NOT_EQ, NE_EXPR, PREC_EQUALITY_EXPRESSION },
{ CPP_AND, BIT_AND_EXPR, PREC_AND_EXPRESSION },
{ CPP_XOR, BIT_XOR_EXPR, PREC_EXCLUSIVE_OR_EXPRESSION },
{ CPP_OR, BIT_IOR_EXPR, PREC_INCLUSIVE_OR_EXPRESSION },
{ CPP_AND_AND, TRUTH_ANDIF_EXPR, PREC_LOGICAL_AND_EXPRESSION },
{ CPP_OR_OR, TRUTH_ORIF_EXPR, PREC_LOGICAL_OR_EXPRESSION }
};
/* The same as binops, but initialized by cp_parser_new so that
binops_by_token[N].token_type == N. Used in cp_parser_binary_expression
for speed. */
static cp_parser_binary_operations_map_node binops_by_token[N_CP_TTYPES];
/* Constructors and destructors. */
/* Construct a new context. The context below this one on the stack
is given by NEXT. */
static cp_parser_context *
cp_parser_context_new (cp_parser_context* next)
{
cp_parser_context *context;
/* Allocate the storage. */
if (cp_parser_context_free_list != NULL)
{
/* Pull the first entry from the free list. */
context = cp_parser_context_free_list;
cp_parser_context_free_list = context->next;
memset (context, 0, sizeof (*context));
}
else
context = GGC_CNEW (cp_parser_context);
/* No errors have occurred yet in this context. */
context->status = CP_PARSER_STATUS_KIND_NO_ERROR;
/* If this is not the bottomost context, copy information that we
need from the previous context. */
if (next)
{
/* If, in the NEXT context, we are parsing an `x->' or `x.'
expression, then we are parsing one in this context, too. */
context->object_type = next->object_type;
/* Thread the stack. */
context->next = next;
}
return context;
}
/* The cp_parser structure represents the C++ parser. */
typedef struct cp_parser GTY(())
{
/* The lexer from which we are obtaining tokens. */
cp_lexer *lexer;
/* The scope in which names should be looked up. If NULL_TREE, then
we look up names in the scope that is currently open in the
source program. If non-NULL, this is either a TYPE or
NAMESPACE_DECL for the scope in which we should look. It can
also be ERROR_MARK, when we've parsed a bogus scope.
This value is not cleared automatically after a name is looked
up, so we must be careful to clear it before starting a new look
up sequence. (If it is not cleared, then `X::Y' followed by `Z'
will look up `Z' in the scope of `X', rather than the current
scope.) Unfortunately, it is difficult to tell when name lookup
is complete, because we sometimes peek at a token, look it up,
and then decide not to consume it. */
tree scope;
/* OBJECT_SCOPE and QUALIFYING_SCOPE give the scopes in which the
last lookup took place. OBJECT_SCOPE is used if an expression
like "x->y" or "x.y" was used; it gives the type of "*x" or "x",
respectively. QUALIFYING_SCOPE is used for an expression of the
form "X::Y"; it refers to X. */
tree object_scope;
tree qualifying_scope;
/* A stack of parsing contexts. All but the bottom entry on the
stack will be tentative contexts.
We parse tentatively in order to determine which construct is in
use in some situations. For example, in order to determine
whether a statement is an expression-statement or a
declaration-statement we parse it tentatively as a
declaration-statement. If that fails, we then reparse the same
token stream as an expression-statement. */
cp_parser_context *context;
/* True if we are parsing GNU C++. If this flag is not set, then
GNU extensions are not recognized. */
bool allow_gnu_extensions_p;
/* TRUE if the `>' token should be interpreted as the greater-than
operator. FALSE if it is the end of a template-id or
template-parameter-list. */
bool greater_than_is_operator_p;
/* TRUE if default arguments are allowed within a parameter list
that starts at this point. FALSE if only a gnu extension makes
them permissible. */
bool default_arg_ok_p;
/* TRUE if we are parsing an integral constant-expression. See
[expr.const] for a precise definition. */
bool integral_constant_expression_p;
/* TRUE if we are parsing an integral constant-expression -- but a
non-constant expression should be permitted as well. This flag
is used when parsing an array bound so that GNU variable-length
arrays are tolerated. */
bool allow_non_integral_constant_expression_p;
/* TRUE if ALLOW_NON_CONSTANT_EXPRESSION_P is TRUE and something has
been seen that makes the expression non-constant. */
bool non_integral_constant_expression_p;
/* TRUE if local variable names and `this' are forbidden in the
current context. */
bool local_variables_forbidden_p;
/* TRUE if the declaration we are parsing is part of a
linkage-specification of the form `extern string-literal
declaration'. */
bool in_unbraced_linkage_specification_p;
/* TRUE if we are presently parsing a declarator, after the
direct-declarator. */
bool in_declarator_p;
/* TRUE if we are presently parsing a template-argument-list. */
bool in_template_argument_list_p;
/* Set to IN_ITERATION_STMT if parsing an iteration-statement,
to IN_OMP_BLOCK if parsing OpenMP structured block and
IN_OMP_FOR if parsing OpenMP loop. If parsing a switch statement,
this is bitwise ORed with IN_SWITCH_STMT, unless parsing an
iteration-statement, OpenMP block or loop within that switch. */
#define IN_SWITCH_STMT 1
#define IN_ITERATION_STMT 2
#define IN_OMP_BLOCK 4
#define IN_OMP_FOR 8
unsigned char in_statement;
/* TRUE if we are presently parsing the body of a switch statement.
Note that this doesn't quite overlap with in_statement above.
The difference relates to giving the right sets of error messages:
"case not in switch" vs "break statement used with OpenMP...". */
bool in_switch_statement_p;
/* TRUE if we are parsing a type-id in an expression context. In
such a situation, both "type (expr)" and "type (type)" are valid
alternatives. */
bool in_type_id_in_expr_p;
/* TRUE if we are currently in a header file where declarations are
implicitly extern "C". */
bool implicit_extern_c;
/* TRUE if strings in expressions should be translated to the execution
character set. */
bool translate_strings_p;
/* TRUE if we are presently parsing the body of a function, but not
a local class. */
bool in_function_body;
/* If non-NULL, then we are parsing a construct where new type
definitions are not permitted. The string stored here will be
issued as an error message if a type is defined. */
const char *type_definition_forbidden_message;
/* A list of lists. The outer list is a stack, used for member
functions of local classes. At each level there are two sub-list,
one on TREE_VALUE and one on TREE_PURPOSE. Each of those
sub-lists has a FUNCTION_DECL or TEMPLATE_DECL on their
TREE_VALUE's. The functions are chained in reverse declaration
order.
The TREE_PURPOSE sublist contains those functions with default
arguments that need post processing, and the TREE_VALUE sublist
contains those functions with definitions that need post
processing.
These lists can only be processed once the outermost class being
defined is complete. */
tree unparsed_functions_queues;
/* The number of classes whose definitions are currently in
progress. */
unsigned num_classes_being_defined;
/* The number of template parameter lists that apply directly to the
current declaration. */
unsigned num_template_parameter_lists;
} cp_parser;
/* Prototypes. */
/* Constructors and destructors. */
static cp_parser *cp_parser_new
(void);
/* Routines to parse various constructs.
Those that return `tree' will return the error_mark_node (rather
than NULL_TREE) if a parse error occurs, unless otherwise noted.
Sometimes, they will return an ordinary node if error-recovery was
attempted, even though a parse error occurred. So, to check
whether or not a parse error occurred, you should always use
cp_parser_error_occurred. If the construct is optional (indicated
either by an `_opt' in the name of the function that does the
parsing or via a FLAGS parameter), then NULL_TREE is returned if
the construct is not present. */
/* Lexical conventions [gram.lex] */
static tree cp_parser_identifier
(cp_parser *);
static tree cp_parser_string_literal
(cp_parser *, bool, bool);
/* Basic concepts [gram.basic] */
static bool cp_parser_translation_unit
(cp_parser *);
/* Expressions [gram.expr] */
static tree cp_parser_primary_expression
(cp_parser *, bool, bool, bool, cp_id_kind *);
static tree cp_parser_id_expression
(cp_parser *, bool, bool, bool *, bool, bool);
static tree cp_parser_unqualified_id
(cp_parser *, bool, bool, bool, bool);
static tree cp_parser_nested_name_specifier_opt
(cp_parser *, bool, bool, bool, bool);
static tree cp_parser_nested_name_specifier
(cp_parser *, bool, bool, bool, bool);
static tree cp_parser_class_or_namespace_name
(cp_parser *, bool, bool, bool, bool, bool);
static tree cp_parser_postfix_expression
(cp_parser *, bool, bool);
static tree cp_parser_postfix_open_square_expression
(cp_parser *, tree, bool);
static tree cp_parser_postfix_dot_deref_expression
(cp_parser *, enum cpp_ttype, tree, bool, cp_id_kind *);
static tree cp_parser_parenthesized_expression_list
(cp_parser *, bool, bool, bool *);
static void cp_parser_pseudo_destructor_name
(cp_parser *, tree *, tree *);
static tree cp_parser_unary_expression
(cp_parser *, bool, bool);
static enum tree_code cp_parser_unary_operator
(cp_token *);
static tree cp_parser_new_expression
(cp_parser *);
static tree cp_parser_new_placement
(cp_parser *);
static tree cp_parser_new_type_id
(cp_parser *, tree *);
static cp_declarator *cp_parser_new_declarator_opt
(cp_parser *);
static cp_declarator *cp_parser_direct_new_declarator
(cp_parser *);
static tree cp_parser_new_initializer
(cp_parser *);
static tree cp_parser_delete_expression
(cp_parser *);
static tree cp_parser_cast_expression
(cp_parser *, bool, bool);
static tree cp_parser_binary_expression
(cp_parser *, bool);
static tree cp_parser_question_colon_clause
(cp_parser *, tree);
static tree cp_parser_assignment_expression
(cp_parser *, bool);
static enum tree_code cp_parser_assignment_operator_opt
(cp_parser *);
static tree cp_parser_expression
(cp_parser *, bool);
static tree cp_parser_constant_expression
(cp_parser *, bool, bool *);
static tree cp_parser_builtin_offsetof
(cp_parser *);
/* APPLE LOCAL begin blocks 6040305 (ca) */
static tree cp_parser_block_literal_expr (cp_parser *);
/* APPLE LOCAL end blocks 6040305 (ca) */
/* APPLE LOCAL begin C* language */
static void objc_foreach_stmt
(cp_parser *, tree);
/* APPLE LOCAL end C* language */
/* APPLE LOCAL begin C* property (Radar 4436866) */
static void objc_cp_parser_at_property
(cp_parser *);
static void objc_cp_parse_property_decl
(cp_parser *);
/* APPLE LOCAL end C* property (Radar 4436866) */
/* APPLE LOCAL begin objc new property */
static void objc_cp_parser_property_impl (cp_parser *parser,
enum rid keyword);
/* APPLE LOCAL end objc new property */
/* APPLE LOCAL begin radar 4548636 */
static bool objc_attr_follwed_by_at_keyword
(cp_parser *);
/* APPLE LOCAL end radar 4548636 */
/* Statements [gram.stmt.stmt] */
static void cp_parser_statement
(cp_parser *, tree, bool);
static void cp_parser_label_for_labeled_statement
(cp_parser *);
static tree cp_parser_expression_statement
(cp_parser *, tree);
static tree cp_parser_compound_statement
/* APPLE LOCAL radar 5982990 */
(cp_parser *, tree, bool, bool);
static void cp_parser_statement_seq_opt
(cp_parser *, tree);
static tree cp_parser_selection_statement
(cp_parser *);
static tree cp_parser_condition
(cp_parser *);
static tree cp_parser_iteration_statement
(cp_parser *);
static void cp_parser_for_init_statement
(cp_parser *);
static tree cp_parser_jump_statement
(cp_parser *);
static void cp_parser_declaration_statement
(cp_parser *);
static tree cp_parser_implicitly_scoped_statement
(cp_parser *);
static void cp_parser_already_scoped_statement
(cp_parser *);
/* Declarations [gram.dcl.dcl] */
static void cp_parser_declaration_seq_opt
(cp_parser *);
static void cp_parser_declaration
(cp_parser *);
static void cp_parser_block_declaration
(cp_parser *, bool);
static void cp_parser_simple_declaration
(cp_parser *, bool);
static void cp_parser_decl_specifier_seq
(cp_parser *, cp_parser_flags, cp_decl_specifier_seq *, int *);
static tree cp_parser_storage_class_specifier_opt
(cp_parser *);
static tree cp_parser_function_specifier_opt
(cp_parser *, cp_decl_specifier_seq *);
static tree cp_parser_type_specifier
(cp_parser *, cp_parser_flags, cp_decl_specifier_seq *, bool,
int *, bool *);
static tree cp_parser_simple_type_specifier
(cp_parser *, cp_decl_specifier_seq *, cp_parser_flags);
static tree cp_parser_type_name
(cp_parser *);
static tree cp_parser_elaborated_type_specifier
(cp_parser *, bool, bool);
static tree cp_parser_enum_specifier
(cp_parser *);
static void cp_parser_enumerator_list
(cp_parser *, tree);
static void cp_parser_enumerator_definition
(cp_parser *, tree);
static tree cp_parser_namespace_name
(cp_parser *);
static void cp_parser_namespace_definition
(cp_parser *);
static void cp_parser_namespace_body
(cp_parser *);
static tree cp_parser_qualified_namespace_specifier
(cp_parser *);
static void cp_parser_namespace_alias_definition
(cp_parser *);
static bool cp_parser_using_declaration
(cp_parser *, bool);
static void cp_parser_using_directive
(cp_parser *);
static void cp_parser_asm_definition
/* APPLE LOCAL CW asm blocks */
(cp_parser *, bool);
static void cp_parser_linkage_specification
(cp_parser *);
/* Declarators [gram.dcl.decl] */
static tree cp_parser_init_declarator
(cp_parser *, cp_decl_specifier_seq *, VEC (deferred_access_check,gc)*, bool, bool, int, bool *);
static cp_declarator *cp_parser_declarator
(cp_parser *, cp_parser_declarator_kind, int *, bool *, bool);
static cp_declarator *cp_parser_direct_declarator
(cp_parser *, cp_parser_declarator_kind, int *, bool);
static enum tree_code cp_parser_ptr_operator
(cp_parser *, tree *, cp_cv_quals *);
static cp_cv_quals cp_parser_cv_qualifier_seq_opt
(cp_parser *);
static tree cp_parser_declarator_id
(cp_parser *, bool);
static tree cp_parser_type_id
(cp_parser *);
static void cp_parser_type_specifier_seq
(cp_parser *, bool, cp_decl_specifier_seq *);
static cp_parameter_declarator *cp_parser_parameter_declaration_clause
(cp_parser *);
static cp_parameter_declarator *cp_parser_parameter_declaration_list
(cp_parser *, bool *);
static cp_parameter_declarator *cp_parser_parameter_declaration
(cp_parser *, bool, bool *);
static void cp_parser_function_body
(cp_parser *);
static tree cp_parser_initializer
(cp_parser *, bool *, bool *);
static tree cp_parser_initializer_clause
(cp_parser *, bool *);
static VEC(constructor_elt,gc) *cp_parser_initializer_list
(cp_parser *, bool *);
static bool cp_parser_ctor_initializer_opt_and_function_body
(cp_parser *);
/* Classes [gram.class] */
static tree cp_parser_class_name
(cp_parser *, bool, bool, enum tag_types, bool, bool, bool);
static tree cp_parser_class_specifier
(cp_parser *);
static tree cp_parser_class_head
(cp_parser *, bool *, tree *, tree *);
static enum tag_types cp_parser_class_key
(cp_parser *);
static void cp_parser_member_specification_opt
(cp_parser *);
static void cp_parser_member_declaration
(cp_parser *);
static tree cp_parser_pure_specifier
(cp_parser *);
static tree cp_parser_constant_initializer
(cp_parser *);
/* Derived classes [gram.class.derived] */
static tree cp_parser_base_clause
(cp_parser *);
static tree cp_parser_base_specifier
(cp_parser *);
/* Special member functions [gram.special] */
static tree cp_parser_conversion_function_id
(cp_parser *);
static tree cp_parser_conversion_type_id
(cp_parser *);
static cp_declarator *cp_parser_conversion_declarator_opt
(cp_parser *);
static bool cp_parser_ctor_initializer_opt
(cp_parser *);
static void cp_parser_mem_initializer_list
(cp_parser *);
static tree cp_parser_mem_initializer
(cp_parser *);
static tree cp_parser_mem_initializer_id
(cp_parser *);
/* Overloading [gram.over] */
static tree cp_parser_operator_function_id
(cp_parser *);
static tree cp_parser_operator
(cp_parser *);
/* Templates [gram.temp] */
static void cp_parser_template_declaration
(cp_parser *, bool);
static tree cp_parser_template_parameter_list
(cp_parser *);
static tree cp_parser_template_parameter
(cp_parser *, bool *);
static tree cp_parser_type_parameter
(cp_parser *);
static tree cp_parser_template_id
(cp_parser *, bool, bool, bool);
static tree cp_parser_template_name
(cp_parser *, bool, bool, bool, bool *);
static tree cp_parser_template_argument_list
(cp_parser *);
static tree cp_parser_template_argument
(cp_parser *);
static void cp_parser_explicit_instantiation
(cp_parser *);
static void cp_parser_explicit_specialization
(cp_parser *);
/* Exception handling [gram.exception] */
static tree cp_parser_try_block
(cp_parser *);
static bool cp_parser_function_try_block
(cp_parser *);
static void cp_parser_handler_seq
(cp_parser *);
static void cp_parser_handler
(cp_parser *);
static tree cp_parser_exception_declaration
(cp_parser *);
static tree cp_parser_throw_expression
(cp_parser *);
static tree cp_parser_exception_specification_opt
(cp_parser *);
static tree cp_parser_type_id_list
(cp_parser *);
/* GNU Extensions */
static tree cp_parser_asm_specification_opt
(cp_parser *);
static tree cp_parser_asm_operand_list
(cp_parser *);
static tree cp_parser_asm_clobber_list
(cp_parser *);
static tree cp_parser_attributes_opt
(cp_parser *);
static tree cp_parser_attribute_list
(cp_parser *);
static bool cp_parser_extension_opt
(cp_parser *, int *);
static void cp_parser_label_declaration
(cp_parser *);
enum pragma_context { pragma_external, pragma_stmt, pragma_compound };
static bool cp_parser_pragma
(cp_parser *, enum pragma_context);
/* Objective-C++ Productions */
static tree cp_parser_objc_message_receiver
(cp_parser *);
static tree cp_parser_objc_message_args
(cp_parser *);
static tree cp_parser_objc_message_expression
(cp_parser *);
/* APPLE LOCAL begin radar 5277239 */
static tree cp_parser_objc_reference_expression
(cp_parser *, tree);
/* APPLE LOCAL end radar 5277239 */
static tree cp_parser_objc_encode_expression
(cp_parser *);
static tree cp_parser_objc_defs_expression
(cp_parser *);
static tree cp_parser_objc_protocol_expression
(cp_parser *);
static tree cp_parser_objc_selector_expression
(cp_parser *);
static tree cp_parser_objc_expression
(cp_parser *);
static bool cp_parser_objc_selector_p
(enum cpp_ttype);
static tree cp_parser_objc_selector
(cp_parser *);
/* APPLE LOCAL begin radar 3803157 - objc attribute */
static void cp_parser_objc_maybe_attributes
(cp_parser *, tree *);
static tree cp_parser_objc_identifier_list
(cp_parser *);
/* APPLE LOCAL end radar 3803157 - objc attribute */
static tree cp_parser_objc_protocol_refs_opt
(cp_parser *);
/* APPLE LOCAL begin radar 5355344 */
static bool cp_parser_objc_tentative_protocol_refs_opt
(cp_parser *, tree *);
/* APPLE LOCAL end radar 5355344 */
static void cp_parser_objc_declaration
(cp_parser *);
static tree cp_parser_objc_statement
(cp_parser *);
/* Utility Routines */
static tree cp_parser_lookup_name
(cp_parser *, tree, enum tag_types, bool, bool, bool, tree *);
static tree cp_parser_lookup_name_simple
(cp_parser *, tree);
static tree cp_parser_maybe_treat_template_as_class
(tree, bool);
static bool cp_parser_check_declarator_template_parameters
(cp_parser *, cp_declarator *);
static bool cp_parser_check_template_parameters
(cp_parser *, unsigned);
static tree cp_parser_simple_cast_expression
(cp_parser *);
static tree cp_parser_global_scope_opt
(cp_parser *, bool);
static bool cp_parser_constructor_declarator_p
(cp_parser *, bool);
static tree cp_parser_function_definition_from_specifiers_and_declarator
(cp_parser *, cp_decl_specifier_seq *, tree, const cp_declarator *);
static tree cp_parser_function_definition_after_declarator
(cp_parser *, bool);
static void cp_parser_template_declaration_after_export
(cp_parser *, bool);
static void cp_parser_perform_template_parameter_access_checks
(VEC (deferred_access_check,gc)*);
static tree cp_parser_single_declaration
(cp_parser *, VEC (deferred_access_check,gc)*, bool, bool *);
static tree cp_parser_functional_cast
(cp_parser *, tree);
static tree cp_parser_save_member_function_body
(cp_parser *, cp_decl_specifier_seq *, cp_declarator *, tree);
static tree cp_parser_enclosed_template_argument_list
(cp_parser *);
static void cp_parser_save_default_args
(cp_parser *, tree);
static void cp_parser_late_parsing_for_member
(cp_parser *, tree);
static void cp_parser_late_parsing_default_args
(cp_parser *, tree);
static tree cp_parser_sizeof_operand
(cp_parser *, enum rid);
static bool cp_parser_declares_only_class_p
(cp_parser *);
static void cp_parser_set_storage_class
(cp_parser *, cp_decl_specifier_seq *, enum rid);
static void cp_parser_set_decl_spec_type
(cp_decl_specifier_seq *, tree, bool);
static bool cp_parser_friend_p
(const cp_decl_specifier_seq *);
static cp_token *cp_parser_require
(cp_parser *, enum cpp_ttype, const char *);
static cp_token *cp_parser_require_keyword
(cp_parser *, enum rid, const char *);
static bool cp_parser_token_starts_function_definition_p
(cp_token *);
static bool cp_parser_next_token_starts_class_definition_p
(cp_parser *);
static bool cp_parser_next_token_ends_template_argument_p
(cp_parser *);
static bool cp_parser_nth_token_starts_template_argument_list_p
(cp_parser *, size_t);
static enum tag_types cp_parser_token_is_class_key
(cp_token *);
static void cp_parser_check_class_key
(enum tag_types, tree type);
static void cp_parser_check_access_in_redeclaration
(tree type);
static bool cp_parser_optional_template_keyword
(cp_parser *);
static void cp_parser_pre_parsed_nested_name_specifier
(cp_parser *);
static void cp_parser_cache_group
(cp_parser *, enum cpp_ttype, unsigned);
static void cp_parser_parse_tentatively
(cp_parser *);
static void cp_parser_commit_to_tentative_parse
(cp_parser *);
static void cp_parser_abort_tentative_parse
(cp_parser *);
static bool cp_parser_parse_definitely
(cp_parser *);
static inline bool cp_parser_parsing_tentatively
(cp_parser *);
static bool cp_parser_uncommitted_to_tentative_parse_p
(cp_parser *);
static void cp_parser_error
(cp_parser *, const char *);
static void cp_parser_name_lookup_error
(cp_parser *, tree, tree, const char *);
static bool cp_parser_simulate_error
(cp_parser *);
static bool cp_parser_check_type_definition
(cp_parser *);
static void cp_parser_check_for_definition_in_return_type
(cp_declarator *, tree);
static void cp_parser_check_for_invalid_template_id
(cp_parser *, tree);
static bool cp_parser_non_integral_constant_expression
(cp_parser *, const char *);
static void cp_parser_diagnose_invalid_type_name
(cp_parser *, tree, tree);
static bool cp_parser_parse_and_diagnose_invalid_type_name
(cp_parser *);
static int cp_parser_skip_to_closing_parenthesis
(cp_parser *, bool, bool, bool);
static void cp_parser_skip_to_end_of_statement
(cp_parser *);
static void cp_parser_consume_semicolon_at_end_of_statement
(cp_parser *);
static void cp_parser_skip_to_end_of_block_or_statement
(cp_parser *);
static void cp_parser_skip_to_closing_brace
(cp_parser *);
static void cp_parser_skip_to_end_of_template_parameter_list
(cp_parser *);
static void cp_parser_skip_to_pragma_eol
(cp_parser*, cp_token *);
static bool cp_parser_error_occurred
(cp_parser *);
static bool cp_parser_allow_gnu_extensions_p
(cp_parser *);
static bool cp_parser_is_string_literal
(cp_token *);
static bool cp_parser_is_keyword
(cp_token *, enum rid);
static tree cp_parser_make_typename_type
(cp_parser *, tree, tree);
/* APPLE LOCAL begin CW asm blocks */
static tree cp_parser_iasm_compound_statement
(cp_parser *);
static void cp_parser_iasm_declaration_seq_opt
(cp_parser *);
static void cp_parser_iasm_line_seq_opt
(cp_parser *);
static void cp_parser_iasm_line
(cp_parser *);
static void cp_parser_iasm_statement_seq_opt
(cp_parser *);
static void cp_parser_iasm_statement
(cp_parser *);
static tree cp_parser_iasm_operands
(cp_parser *);
static tree cp_parser_iasm_operand
(cp_parser *);
static tree cp_parser_iasm_postfix_expression
(cp_parser *, bool, bool);
static tree cp_parser_iasm_identifier_or_number
(cp_parser* parser);
static tree iasm_build_identifier_string
(cp_parser* parser, const char* str);
static tree cp_parser_iasm_relative_branch
(cp_parser *parser);
static void cp_parser_iasm_top_statement
(cp_parser *parser);
#ifndef IASM_SEE_OPCODE
#define IASM_SEE_OPCODE(YYCHAR, T) YYCHAR
#endif
#define TYPESPEC 1
#define IDENTIFIER 2
/* APPLE LOCAL end CW asm blocks */
/* Returns nonzero if we are parsing tentatively. */
static inline bool
cp_parser_parsing_tentatively (cp_parser* parser)
{
return parser->context->next != NULL;
}
/* Returns nonzero if TOKEN is a string literal. */
static bool
cp_parser_is_string_literal (cp_token* token)
{
return (token->type == CPP_STRING || token->type == CPP_WSTRING);
}
/* Returns nonzero if TOKEN is the indicated KEYWORD. */
static bool
cp_parser_is_keyword (cp_token* token, enum rid keyword)
{
return token->keyword == keyword;
}
/* If not parsing tentatively, issue a diagnostic of the form
FILE:LINE: MESSAGE before TOKEN
where TOKEN is the next token in the input stream. MESSAGE
(specified by the caller) is usually of the form "expected
OTHER-TOKEN". */
static void
cp_parser_error (cp_parser* parser, const char* message)
{
if (!cp_parser_simulate_error (parser))
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
/* This diagnostic makes more sense if it is tagged to the line
of the token we just peeked at. */
cp_lexer_set_source_position_from_token (token);
if (token->type == CPP_PRAGMA)
{
error ("%<#pragma%> is not allowed here");
cp_parser_skip_to_pragma_eol (parser, token);
return;
}
c_parse_error (message,
/* Because c_parser_error does not understand
CPP_KEYWORD, keywords are treated like
identifiers. */
(token->type == CPP_KEYWORD ? CPP_NAME : token->type),
token->u.value);
}
}
/* Issue an error about name-lookup failing. NAME is the
IDENTIFIER_NODE DECL is the result of
the lookup (as returned from cp_parser_lookup_name). DESIRED is
the thing that we hoped to find. */
static void
cp_parser_name_lookup_error (cp_parser* parser,
tree name,
tree decl,
const char* desired)
{
/* If name lookup completely failed, tell the user that NAME was not
declared. */
if (decl == error_mark_node)
{
if (parser->scope && parser->scope != global_namespace)
error ("%<%D::%D%> has not been declared",
parser->scope, name);
else if (parser->scope == global_namespace)
error ("%<::%D%> has not been declared", name);
else if (parser->object_scope
&& !CLASS_TYPE_P (parser->object_scope))
error ("request for member %qD in non-class type %qT",
name, parser->object_scope);
else if (parser->object_scope)
error ("%<%T::%D%> has not been declared",
parser->object_scope, name);
else
error ("%qD has not been declared", name);
}
else if (parser->scope && parser->scope != global_namespace)
error ("%<%D::%D%> %s", parser->scope, name, desired);
else if (parser->scope == global_namespace)
error ("%<::%D%> %s", name, desired);
else
error ("%qD %s", name, desired);
}
/* If we are parsing tentatively, remember that an error has occurred
during this tentative parse. Returns true if the error was
simulated; false if a message should be issued by the caller. */
static bool
cp_parser_simulate_error (cp_parser* parser)
{
if (cp_parser_uncommitted_to_tentative_parse_p (parser))
{
parser->context->status = CP_PARSER_STATUS_KIND_ERROR;
return true;
}
return false;
}
/* Check for repeated decl-specifiers. */
static void
cp_parser_check_decl_spec (cp_decl_specifier_seq *decl_specs)
{
cp_decl_spec ds;
for (ds = ds_first; ds != ds_last; ++ds)
{
unsigned count = decl_specs->specs[(int)ds];
if (count < 2)
continue;
/* The "long" specifier is a special case because of "long long". */
if (ds == ds_long)
{
if (count > 2)
error ("%<long long long%> is too long for GCC");
else if (pedantic && !in_system_header && warn_long_long)
pedwarn ("ISO C++ does not support %<long long%>");
}
else if (count > 1)
{
static const char *const decl_spec_names[] = {
"signed",
"unsigned",
"short",
"long",
"const",
"volatile",
"restrict",
"inline",
"virtual",
"explicit",
"friend",
"typedef",
"__complex",
"__thread"
/* APPLE LOCAL CW asm blocks */
, "asm"
};
error ("duplicate %qs", decl_spec_names[(int)ds]);
}
}
}
/* This function is called when a type is defined. If type
definitions are forbidden at this point, an error message is
issued. */
static bool
cp_parser_check_type_definition (cp_parser* parser)
{
/* If types are forbidden here, issue a message. */
if (parser->type_definition_forbidden_message)
{
/* Use `%s' to print the string in case there are any escape
characters in the message. */
error ("%s", parser->type_definition_forbidden_message);
return false;
}
return true;
}
/* This function is called when the DECLARATOR is processed. The TYPE
was a type defined in the decl-specifiers. If it is invalid to
define a type in the decl-specifiers for DECLARATOR, an error is
issued. */
static void
cp_parser_check_for_definition_in_return_type (cp_declarator *declarator,
tree type)
{
/* [dcl.fct] forbids type definitions in return types.
Unfortunately, it's not easy to know whether or not we are
processing a return type until after the fact. */
while (declarator
&& (declarator->kind == cdk_pointer
|| declarator->kind == cdk_reference
|| declarator->kind == cdk_ptrmem))
declarator = declarator->declarator;
if (declarator
&& declarator->kind == cdk_function)
{
error ("new types may not be defined in a return type");
inform ("(perhaps a semicolon is missing after the definition of %qT)",
type);
}
}
/* A type-specifier (TYPE) has been parsed which cannot be followed by
"<" in any valid C++ program. If the next token is indeed "<",
issue a message warning the user about what appears to be an
invalid attempt to form a template-id. */
static void
cp_parser_check_for_invalid_template_id (cp_parser* parser,
tree type)
{
cp_token_position start = 0;
if (cp_lexer_next_token_is (parser->lexer, CPP_LESS))
{
if (TYPE_P (type))
error ("%qT is not a template", type);
else if (TREE_CODE (type) == IDENTIFIER_NODE)
error ("%qE is not a template", type);
else
error ("invalid template-id");
/* Remember the location of the invalid "<". */
if (cp_parser_uncommitted_to_tentative_parse_p (parser))
start = cp_lexer_token_position (parser->lexer, true);
/* Consume the "<". */
cp_lexer_consume_token (parser->lexer);
/* Parse the template arguments. */
cp_parser_enclosed_template_argument_list (parser);
/* Permanently remove the invalid template arguments so that
this error message is not issued again. */
if (start)
cp_lexer_purge_tokens_after (parser->lexer, start);
}
}
/* If parsing an integral constant-expression, issue an error message
about the fact that THING appeared and return true. Otherwise,
return false. In either case, set
PARSER->NON_INTEGRAL_CONSTANT_EXPRESSION_P. */
static bool
cp_parser_non_integral_constant_expression (cp_parser *parser,
const char *thing)
{
parser->non_integral_constant_expression_p = true;
if (parser->integral_constant_expression_p)
{
if (!parser->allow_non_integral_constant_expression_p)
{
error ("%s cannot appear in a constant-expression", thing);
return true;
}
}
return false;
}
/* Emit a diagnostic for an invalid type name. SCOPE is the
qualifying scope (or NULL, if none) for ID. This function commits
to the current active tentative parse, if any. (Otherwise, the
problematic construct might be encountered again later, resulting
in duplicate error messages.) */
static void
cp_parser_diagnose_invalid_type_name (cp_parser *parser, tree scope, tree id)
{
tree decl, old_scope;
/* Try to lookup the identifier. */
old_scope = parser->scope;
parser->scope = scope;
decl = cp_parser_lookup_name_simple (parser, id);
parser->scope = old_scope;
/* If the lookup found a template-name, it means that the user forgot
to specify an argument list. Emit a useful error message. */
if (TREE_CODE (decl) == TEMPLATE_DECL)
error ("invalid use of template-name %qE without an argument list", decl);
else if (TREE_CODE (id) == BIT_NOT_EXPR)
error ("invalid use of destructor %qD as a type", id);
else if (TREE_CODE (decl) == TYPE_DECL)
/* Something like 'unsigned A a;' */
error ("invalid combination of multiple type-specifiers");
else if (!parser->scope)
{
/* Issue an error message. */
error ("%qE does not name a type", id);
/* If we're in a template class, it's possible that the user was
referring to a type from a base class. For example:
template <typename T> struct A { typedef T X; };
template <typename T> struct B : public A<T> { X x; };
The user should have said "typename A<T>::X". */
if (processing_template_decl && current_class_type
&& TYPE_BINFO (current_class_type))
{
tree b;
for (b = TREE_CHAIN (TYPE_BINFO (current_class_type));
b;
b = TREE_CHAIN (b))
{
tree base_type = BINFO_TYPE (b);
if (CLASS_TYPE_P (base_type)
&& dependent_type_p (base_type))
{
tree field;
/* Go from a particular instantiation of the
template (which will have an empty TYPE_FIELDs),
to the main version. */
base_type = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (base_type);
for (field = TYPE_FIELDS (base_type);
field;
field = TREE_CHAIN (field))
if (TREE_CODE (field) == TYPE_DECL
&& DECL_NAME (field) == id)
{
inform ("(perhaps %<typename %T::%E%> was intended)",
BINFO_TYPE (b), id);
break;
}
if (field)
break;
}
}
}
}
/* Here we diagnose qualified-ids where the scope is actually correct,
but the identifier does not resolve to a valid type name. */
else if (parser->scope != error_mark_node)
{
if (TREE_CODE (parser->scope) == NAMESPACE_DECL)
error ("%qE in namespace %qE does not name a type",
id, parser->scope);
else if (TYPE_P (parser->scope))
error ("%qE in class %qT does not name a type", id, parser->scope);
else
gcc_unreachable ();
}
cp_parser_commit_to_tentative_parse (parser);
}
/* Check for a common situation where a type-name should be present,
but is not, and issue a sensible error message. Returns true if an
invalid type-name was detected.
The situation handled by this function are variable declarations of the
form `ID a', where `ID' is an id-expression and `a' is a plain identifier.
Usually, `ID' should name a type, but if we got here it means that it
does not. We try to emit the best possible error message depending on
how exactly the id-expression looks like. */
static bool
cp_parser_parse_and_diagnose_invalid_type_name (cp_parser *parser)
{
tree id;
cp_parser_parse_tentatively (parser);
id = cp_parser_id_expression (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
/*template_p=*/NULL,
/*declarator_p=*/true,
/*optional_p=*/false);
/* After the id-expression, there should be a plain identifier,
otherwise this is not a simple variable declaration. Also, if
the scope is dependent, we cannot do much. */
if (!cp_lexer_next_token_is (parser->lexer, CPP_NAME)
|| (parser->scope && TYPE_P (parser->scope)
&& dependent_type_p (parser->scope))
|| TREE_CODE (id) == TYPE_DECL)
{
cp_parser_abort_tentative_parse (parser);
return false;
}
if (!cp_parser_parse_definitely (parser))
return false;
/* Emit a diagnostic for the invalid type. */
cp_parser_diagnose_invalid_type_name (parser, parser->scope, id);
/* Skip to the end of the declaration; there's no point in
trying to process it. */
cp_parser_skip_to_end_of_block_or_statement (parser);
return true;
}
/* Consume tokens up to, and including, the next non-nested closing `)'.
Returns 1 iff we found a closing `)'. RECOVERING is true, if we
are doing error recovery. Returns -1 if OR_COMMA is true and we
found an unnested comma. */
static int
cp_parser_skip_to_closing_parenthesis (cp_parser *parser,
bool recovering,
bool or_comma,
bool consume_paren)
{
unsigned paren_depth = 0;
unsigned brace_depth = 0;
if (recovering && !or_comma
&& cp_parser_uncommitted_to_tentative_parse_p (parser))
return 0;
while (true)
{
cp_token * token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_EOF:
case CPP_PRAGMA_EOL:
/* If we've run out of tokens, then there is no closing `)'. */
return 0;
case CPP_SEMICOLON:
/* This matches the processing in skip_to_end_of_statement. */
if (!brace_depth)
return 0;
break;
case CPP_OPEN_BRACE:
++brace_depth;
break;
case CPP_CLOSE_BRACE:
if (!brace_depth--)
return 0;
break;
case CPP_COMMA:
if (recovering && or_comma && !brace_depth && !paren_depth)
return -1;
break;
case CPP_OPEN_PAREN:
if (!brace_depth)
++paren_depth;
break;
case CPP_CLOSE_PAREN:
if (!brace_depth && !paren_depth--)
{
if (consume_paren)
cp_lexer_consume_token (parser->lexer);
return 1;
}
break;
default:
break;
}
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
}
}
/* Consume tokens until we reach the end of the current statement.
Normally, that will be just before consuming a `;'. However, if a
non-nested `}' comes first, then we stop before consuming that. */
static void
cp_parser_skip_to_end_of_statement (cp_parser* parser)
{
unsigned nesting_depth = 0;
while (true)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_EOF:
case CPP_PRAGMA_EOL:
/* If we've run out of tokens, stop. */
return;
case CPP_SEMICOLON:
/* If the next token is a `;', we have reached the end of the
statement. */
if (!nesting_depth)
return;
break;
case CPP_CLOSE_BRACE:
/* If this is a non-nested '}', stop before consuming it.
That way, when confronted with something like:
{ 3 + }
we stop before consuming the closing '}', even though we
have not yet reached a `;'. */
if (nesting_depth == 0)
return;
/* If it is the closing '}' for a block that we have
scanned, stop -- but only after consuming the token.
That way given:
void f g () { ... }
typedef int I;
we will stop after the body of the erroneously declared
function, but before consuming the following `typedef'
declaration. */
if (--nesting_depth == 0)
{
cp_lexer_consume_token (parser->lexer);
return;
}
case CPP_OPEN_BRACE:
++nesting_depth;
break;
default:
break;
}
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
}
}
/* APPLE LOCAL begin radar 5277239 */
/* This routine checks that type_decl is a class or class object followed by a '.'
which is an alternative syntax to class-method messaging [class-name class-method]
*/
static bool
cp_objc_property_reference_prefix (cp_parser *parser, tree type)
{
return c_dialect_objc () && cp_lexer_peek_token (parser->lexer)->type == CPP_DOT
&& (objc_is_id (type) || objc_is_class_name (type));
}
/* APPLE LOCAL end radar 5277239 */
/* APPLE LOCAL begin C* property (Radar 4436866, 4591909) */
/* This routine parses the propery declarations. */
static void
objc_cp_parse_property_decl (cp_parser *parser)
{
int declares_class_or_enum;
cp_decl_specifier_seq declspecs;
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_NONE,
&declspecs,
&declares_class_or_enum);
/* Keep going until we hit the `;' at the end of the declaration. */
while (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
{
tree property;
cp_token *token;
cp_declarator *declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
NULL, NULL, false);
property = grokdeclarator (declarator, &declspecs, NORMAL,0, NULL);
/* Revover from any kind of error in property declaration. */
if (property == error_mark_node || property == NULL_TREE)
return;
/* APPLE LOCAL begin objc new property */
if (declspecs.attributes)
cplus_decl_attributes (&property, declspecs.attributes, 0);
/* APPLE LOCAL begin radar 4712415 */
token = cp_lexer_peek_token (parser->lexer);
if (token->keyword == RID_ATTRIBUTE)
{
/* Attribute on the property itself. */
declspecs.attributes = cp_parser_attributes_opt (parser);
cplus_decl_attributes (&property, declspecs.attributes, 0);
token = cp_lexer_peek_token (parser->lexer);
}
/* APPLE LOCAL end radar 4712415 */
/* APPLE LOCAL end objc new property */
/* Add to property list. */
objc_add_property_variable (copy_node (property));
if (token->type == CPP_COMMA)
{
cp_lexer_consume_token (parser->lexer); /* Eat ','. */
continue;
}
else if (token->type == CPP_EOF)
return;
}
cp_lexer_consume_token (parser->lexer); /* Eat ';'. */
}
/* APPLE LOCAL begin objc new property */
/* This routine parses @synthesize property_name[=ivar],... or
@dynamic paroperty_name,... syntax.
*/
static void
objc_cp_parser_property_impl (cp_parser *parser, enum rid keyword)
{
cp_lexer_consume_token (parser->lexer); /* Eat @synthesize or @dynamic */
if (keyword == RID_AT_DYNAMIC)
{
tree identifier_list = cp_parser_objc_identifier_list (parser);
objc_declare_property_impl (2, identifier_list);
}
else
{
cp_token *sep = cp_lexer_peek_token (parser->lexer);
tree list = NULL_TREE;
do
{
tree property;
tree identifier_list;
if (sep->type == CPP_COMMA)
cp_lexer_consume_token (parser->lexer); /* Eat ',' */
property = cp_parser_identifier (parser);
sep = cp_lexer_peek_token (parser->lexer);
if (sep->type == CPP_EQ)
{
cp_lexer_consume_token (parser->lexer); /* '=' */
identifier_list = build_tree_list (cp_parser_identifier (parser), property);
}
else
identifier_list = build_tree_list (NULL_TREE, property);
list = chainon (list, identifier_list);
sep = cp_lexer_peek_token (parser->lexer);
}
while (sep->type == CPP_COMMA);
objc_declare_property_impl (1, list);
}
cp_parser_consume_semicolon_at_end_of_statement (parser);
}
/* APPLE LOCAL end objc new property */
/* This function parses a @property declaration inside an objective class
or its implementation. */
static void
objc_cp_parser_at_property (cp_parser *parser)
{
cp_token *token;
objc_set_property_attr (0, NULL_TREE);
/* Consume @property */
cp_lexer_consume_token (parser->lexer);
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_OPEN_PAREN)
{
cp_lexer_consume_token (parser->lexer);
while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF)
{
tree node;
/* property has attribute list. */
/* Consume '(' */
node = cp_parser_identifier (parser);
if (node == ridpointers [(int) RID_READONLY])
{
/* Do the readyonly thing. */
objc_set_property_attr (1, NULL_TREE);
}
else if (node == ridpointers [(int) RID_GETTER]
|| node == ridpointers [(int) RID_SETTER])
{
/* Do the getter/setter attribute. */
token = cp_lexer_consume_token (parser->lexer);
if (token->type == CPP_EQ)
{
/* APPLE LOCAL radar 4675792 */
tree attr_ident = cp_parser_objc_selector (parser);
int num;
if (node == ridpointers [(int) RID_GETTER])
num = 2;
else
{
num = 3;
/* Consume the ':' which must always follow the setter name. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COLON))
cp_lexer_consume_token (parser->lexer);
}
objc_set_property_attr (num, attr_ident);
}
else
{
error ("getter/setter attribute must be followed by '='");
break;
}
}
/* APPLE LOCAL begin objc new property */
else if (node == ridpointers [(int) RID_READWRITE])
{
objc_set_property_attr (9, NULL_TREE);
}
else if (node == ridpointers [(int) RID_ASSIGN])
{
objc_set_property_attr (10, NULL_TREE);
}
else if (node == ridpointers [(int) RID_RETAIN])
{
objc_set_property_attr (11, NULL_TREE);
}
else if (node == ridpointers [(int) RID_COPY])
{
objc_set_property_attr (12, NULL_TREE);
}
/* APPLE LOCAL end objc new property */
/* APPLE LOCAL begin radar 4947014 - objc atomic property */
else if (node == ridpointers [(int) RID_NONATOMIC])
{
objc_set_property_attr (13, NULL_TREE);
}
/* APPLE LOCAL end radar 4947014 - objc atomic property */
else
{
error ("unknown property attribute");
break;
}
/* APPLE LOCAL begin radar 6302949 */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_PAREN)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_EOF))
warning (0, "property attributes must be separated by a comma");
/* APPLE LOCAL end radar 6302949 */
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
cp_lexer_consume_token (parser->lexer);
token = cp_lexer_peek_token (parser->lexer);
}
if (token->type != CPP_CLOSE_PAREN)
{
error ("syntax error in @property's attribute declaration");
}
/* Consume ')' */
cp_lexer_consume_token (parser->lexer);
}
/* APPLE LOCAL begin weak_import on property 7496972 */
note_objc_property_decl_context ();
objc_cp_parse_property_decl (parser);
note_end_objc_property_decl_context ();
/* APPLE LOCAL end weak_import on property 7496972 */
}
/* APPLE LOCAL end C* property (Radar 4436866, 4591909) */
/* This function is called at the end of a statement or declaration.
If the next token is a semicolon, it is consumed; otherwise, error
recovery is attempted. */
static void
cp_parser_consume_semicolon_at_end_of_statement (cp_parser *parser)
{
/* Look for the trailing `;'. */
if (!cp_parser_require (parser, CPP_SEMICOLON, "`;'"))
{
/* If there is additional (erroneous) input, skip to the end of
the statement. */
cp_parser_skip_to_end_of_statement (parser);
/* If the next token is now a `;', consume it. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
cp_lexer_consume_token (parser->lexer);
}
}
/* Skip tokens until we have consumed an entire block, or until we
have consumed a non-nested `;'. */
static void
cp_parser_skip_to_end_of_block_or_statement (cp_parser* parser)
{
int nesting_depth = 0;
while (nesting_depth >= 0)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_EOF:
case CPP_PRAGMA_EOL:
/* If we've run out of tokens, stop. */
return;
case CPP_SEMICOLON:
/* Stop if this is an unnested ';'. */
if (!nesting_depth)
nesting_depth = -1;
break;
case CPP_CLOSE_BRACE:
/* Stop if this is an unnested '}', or closes the outermost
nesting level. */
nesting_depth--;
if (!nesting_depth)
nesting_depth = -1;
break;
case CPP_OPEN_BRACE:
/* Nest. */
nesting_depth++;
break;
default:
break;
}
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
}
}
/* Skip tokens until a non-nested closing curly brace is the next
token. */
static void
cp_parser_skip_to_closing_brace (cp_parser *parser)
{
unsigned nesting_depth = 0;
while (true)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_EOF:
case CPP_PRAGMA_EOL:
/* If we've run out of tokens, stop. */
return;
case CPP_CLOSE_BRACE:
/* If the next token is a non-nested `}', then we have reached
the end of the current block. */
if (nesting_depth-- == 0)
return;
break;
case CPP_OPEN_BRACE:
/* If it the next token is a `{', then we are entering a new
block. Consume the entire block. */
++nesting_depth;
break;
default:
break;
}
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
}
}
/* Consume tokens until we reach the end of the pragma. The PRAGMA_TOK
parameter is the PRAGMA token, allowing us to purge the entire pragma
sequence. */
static void
cp_parser_skip_to_pragma_eol (cp_parser* parser, cp_token *pragma_tok)
{
cp_token *token;
parser->lexer->in_pragma = false;
do
token = cp_lexer_consume_token (parser->lexer);
while (token->type != CPP_PRAGMA_EOL && token->type != CPP_EOF);
/* Ensure that the pragma is not parsed again. */
cp_lexer_purge_tokens_after (parser->lexer, pragma_tok);
}
/* Require pragma end of line, resyncing with it as necessary. The
arguments are as for cp_parser_skip_to_pragma_eol. */
static void
cp_parser_require_pragma_eol (cp_parser *parser, cp_token *pragma_tok)
{
parser->lexer->in_pragma = false;
if (!cp_parser_require (parser, CPP_PRAGMA_EOL, "end of line"))
cp_parser_skip_to_pragma_eol (parser, pragma_tok);
}
/* This is a simple wrapper around make_typename_type. When the id is
an unresolved identifier node, we can provide a superior diagnostic
using cp_parser_diagnose_invalid_type_name. */
static tree
cp_parser_make_typename_type (cp_parser *parser, tree scope, tree id)
{
tree result;
if (TREE_CODE (id) == IDENTIFIER_NODE)
{
result = make_typename_type (scope, id, typename_type,
/*complain=*/tf_none);
if (result == error_mark_node)
cp_parser_diagnose_invalid_type_name (parser, scope, id);
return result;
}
return make_typename_type (scope, id, typename_type, tf_error);
}
/* Create a new C++ parser. */
static cp_parser *
cp_parser_new (void)
{
cp_parser *parser;
cp_lexer *lexer;
unsigned i;
/* cp_lexer_new_main is called before calling ggc_alloc because
cp_lexer_new_main might load a PCH file. */
lexer = cp_lexer_new_main ();
/* Initialize the binops_by_token so that we can get the tree
directly from the token. */
for (i = 0; i < sizeof (binops) / sizeof (binops[0]); i++)
binops_by_token[binops[i].token_type] = binops[i];
parser = GGC_CNEW (cp_parser);
parser->lexer = lexer;
parser->context = cp_parser_context_new (NULL);
/* For now, we always accept GNU extensions. */
parser->allow_gnu_extensions_p = 1;
/* The `>' token is a greater-than operator, not the end of a
template-id. */
parser->greater_than_is_operator_p = true;
parser->default_arg_ok_p = true;
/* We are not parsing a constant-expression. */
parser->integral_constant_expression_p = false;
parser->allow_non_integral_constant_expression_p = false;
parser->non_integral_constant_expression_p = false;
/* Local variable names are not forbidden. */
parser->local_variables_forbidden_p = false;
/* We are not processing an `extern "C"' declaration. */
parser->in_unbraced_linkage_specification_p = false;
/* We are not processing a declarator. */
parser->in_declarator_p = false;
/* We are not processing a template-argument-list. */
parser->in_template_argument_list_p = false;
/* We are not in an iteration statement. */
parser->in_statement = 0;
/* We are not in a switch statement. */
parser->in_switch_statement_p = false;
/* We are not parsing a type-id inside an expression. */
parser->in_type_id_in_expr_p = false;
/* Declarations aren't implicitly extern "C". */
parser->implicit_extern_c = false;
/* String literals should be translated to the execution character set. */
parser->translate_strings_p = true;
/* We are not parsing a function body. */
parser->in_function_body = false;
/* The unparsed function queue is empty. */
parser->unparsed_functions_queues = build_tree_list (NULL_TREE, NULL_TREE);
/* There are no classes being defined. */
parser->num_classes_being_defined = 0;
/* No template parameters apply. */
parser->num_template_parameter_lists = 0;
return parser;
}
/* Create a cp_lexer structure which will emit the tokens in CACHE
and push it onto the parser's lexer stack. This is used for delayed
parsing of in-class method bodies and default arguments, and should
not be confused with tentative parsing. */
static void
cp_parser_push_lexer_for_tokens (cp_parser *parser, cp_token_cache *cache)
{
cp_lexer *lexer = cp_lexer_new_from_tokens (cache);
lexer->next = parser->lexer;
parser->lexer = lexer;
/* Move the current source position to that of the first token in the
new lexer. */
cp_lexer_set_source_position_from_token (lexer->next_token);
}
/* Pop the top lexer off the parser stack. This is never used for the
"main" lexer, only for those pushed by cp_parser_push_lexer_for_tokens. */
static void
cp_parser_pop_lexer (cp_parser *parser)
{
cp_lexer *lexer = parser->lexer;
parser->lexer = lexer->next;
cp_lexer_destroy (lexer);
/* Put the current source position back where it was before this
lexer was pushed. */
cp_lexer_set_source_position_from_token (parser->lexer->next_token);
}
/* Lexical conventions [gram.lex] */
/* Parse an identifier. Returns an IDENTIFIER_NODE representing the
identifier. */
static tree
cp_parser_identifier (cp_parser* parser)
{
cp_token *token;
/* Look for the identifier. */
token = cp_parser_require (parser, CPP_NAME, "identifier");
/* Return the value. */
return token ? token->u.value : error_mark_node;
}
/* Parse a sequence of adjacent string constants. Returns a
TREE_STRING representing the combined, nul-terminated string
constant. If TRANSLATE is true, translate the string to the
execution character set. If WIDE_OK is true, a wide string is
invalid here.
C++98 [lex.string] says that if a narrow string literal token is
adjacent to a wide string literal token, the behavior is undefined.
However, C99 6.4.5p4 says that this results in a wide string literal.
We follow C99 here, for consistency with the C front end.
This code is largely lifted from lex_string() in c-lex.c.
FUTURE: ObjC++ will need to handle @-strings here. */
static tree
cp_parser_string_literal (cp_parser *parser, bool translate, bool wide_ok)
{
tree value;
bool wide = false;
/* APPLE LOCAL pascal strings */
bool pascal_p = false;
size_t count;
struct obstack str_ob;
cpp_string str, istr, *strs;
cp_token *tok;
tok = cp_lexer_peek_token (parser->lexer);
if (!cp_parser_is_string_literal (tok))
{
cp_parser_error (parser, "expected string-literal");
return error_mark_node;
}
/* Try to avoid the overhead of creating and destroying an obstack
for the common case of just one string. */
if (!cp_parser_is_string_literal
(cp_lexer_peek_nth_token (parser->lexer, 2)))
{
cp_lexer_consume_token (parser->lexer);
str.text = (const unsigned char *)TREE_STRING_POINTER (tok->u.value);
str.len = TREE_STRING_LENGTH (tok->u.value);
count = 1;
if (tok->type == CPP_WSTRING)
wide = true;
/* APPLE LOCAL begin pascal strings */
if (CPP_OPTION (parse_in, pascal_strings))
{
if (wide && str.text[0] == 'L' && str.text[2] == '\\' && str.text[3] == 'p')
pascal_p = true;
else if (str.text[1] == '\\' && str.text[2] == 'p')
pascal_p = true;
}
/* APPLE LOCAL end pascal strings */
strs = &str;
}
else
{
gcc_obstack_init (&str_ob);
count = 0;
do
{
cp_lexer_consume_token (parser->lexer);
count++;
str.text = (unsigned char *)TREE_STRING_POINTER (tok->u.value);
str.len = TREE_STRING_LENGTH (tok->u.value);
if (tok->type == CPP_WSTRING)
wide = true;
/* APPLE LOCAL begin pascal strings */
if (CPP_OPTION (parse_in, pascal_strings) && count == 1)
{
if (wide && str.text[0] == 'L' && str.text[2] == '\\' && str.text[3] == 'p')
pascal_p = true;
else if (str.text[1] == '\\' && str.text[2] == 'p')
pascal_p = true;
}
/* APPLE LOCAL end pascal strings */
obstack_grow (&str_ob, &str, sizeof (cpp_string));
tok = cp_lexer_peek_token (parser->lexer);
}
while (cp_parser_is_string_literal (tok));
strs = (cpp_string *) obstack_finish (&str_ob);
}
if (wide && !wide_ok)
{
cp_parser_error (parser, "a wide string is invalid in this context");
wide = false;
}
if ((translate ? cpp_interpret_string : cpp_interpret_string_notranslate)
/* APPLE LOCAL pascal strings */
(parse_in, strs, count, &istr, wide, pascal_p))
{
value = build_string (istr.len, (char *)istr.text);
free ((void *)istr.text);
/* APPLE LOCAL begin pascal strings */
TREE_TYPE (value) = wide ? wchar_array_type_node
: pascal_p ? pascal_string_type_node
: char_array_type_node;
/* APPLE LOCAL end pascal strings */
value = fix_string_type (value);
}
else
/* cpp_interpret_string has issued an error. */
value = error_mark_node;
if (count > 1)
obstack_free (&str_ob, 0);
return value;
}
/* Basic concepts [gram.basic] */
/* Parse a translation-unit.
translation-unit:
declaration-seq [opt]
Returns TRUE if all went well. */
static bool
cp_parser_translation_unit (cp_parser* parser)
{
/* The address of the first non-permanent object on the declarator
obstack. */
static void *declarator_obstack_base;
bool success;
/* Create the declarator obstack, if necessary. */
if (!cp_error_declarator)
{
gcc_obstack_init (&declarator_obstack);
/* Create the error declarator. */
cp_error_declarator = make_declarator (cdk_error);
/* Create the empty parameter list. */
no_parameters = make_parameter_declarator (NULL, NULL, NULL_TREE);
/* Remember where the base of the declarator obstack lies. */
declarator_obstack_base = obstack_next_free (&declarator_obstack);
}
cp_parser_declaration_seq_opt (parser);
/* If there are no tokens left then all went well. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EOF))
{
/* Get rid of the token array; we don't need it any more. */
cp_lexer_destroy (parser->lexer);
parser->lexer = NULL;
/* This file might have been a context that's implicitly extern
"C". If so, pop the lang context. (Only relevant for PCH.) */
if (parser->implicit_extern_c)
{
pop_lang_context ();
parser->implicit_extern_c = false;
}
/* Finish up. */
finish_translation_unit ();
success = true;
}
else
{
cp_parser_error (parser, "expected declaration");
success = false;
}
/* Make sure the declarator obstack was fully cleaned up. */
gcc_assert (obstack_next_free (&declarator_obstack)
== declarator_obstack_base);
/* All went well. */
return success;
}
/* Expressions [gram.expr] */
/* Parse a primary-expression.
primary-expression:
literal
this
( expression )
id-expression
GNU Extensions:
primary-expression:
( compound-statement )
__builtin_va_arg ( assignment-expression , type-id )
__builtin_offsetof ( type-id , offsetof-expression )
APPLE LOCAL blocks 6040305 (cf)
block-literal-expr
Objective-C++ Extension:
primary-expression:
objc-expression
literal:
__null
ADDRESS_P is true iff this expression was immediately preceded by
"&" and therefore might denote a pointer-to-member. CAST_P is true
iff this expression is the target of a cast. TEMPLATE_ARG_P is
true iff this expression is a template argument.
Returns a representation of the expression. Upon return, *IDK
indicates what kind of id-expression (if any) was present. */
static tree
cp_parser_primary_expression (cp_parser *parser,
bool address_p,
bool cast_p,
bool template_arg_p,
cp_id_kind *idk)
{
cp_token *token;
/* APPLE LOCAL CW asm blocks */
int atsignhack = 0;
/* Assume the primary expression is not an id-expression. */
*idk = CP_ID_KIND_NONE;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
/* APPLE LOCAL begin blocks 6040305 (cf) */
case CPP_XOR:
if (flag_blocks)
{
tree expr = cp_parser_block_literal_expr (parser);
return expr;
}
cp_parser_error (parser, "expected primary-expression");
return error_mark_node;
/* APPLE LOCAL end blocks 6040305 (cf) */
/* literal:
integer-literal
character-literal
floating-literal
string-literal
boolean-literal */
case CPP_CHAR:
case CPP_WCHAR:
case CPP_NUMBER:
token = cp_lexer_consume_token (parser->lexer);
/* Floating-point literals are only allowed in an integral
constant expression if they are cast to an integral or
enumeration type. */
if (TREE_CODE (token->u.value) == REAL_CST
&& parser->integral_constant_expression_p
&& pedantic)
{
/* CAST_P will be set even in invalid code like "int(2.7 +
...)". Therefore, we have to check that the next token
is sure to end the cast. */
if (cast_p)
{
cp_token *next_token;
next_token = cp_lexer_peek_token (parser->lexer);
if (/* The comma at the end of an
enumerator-definition. */
next_token->type != CPP_COMMA
/* The curly brace at the end of an enum-specifier. */
&& next_token->type != CPP_CLOSE_BRACE
/* The end of a statement. */
&& next_token->type != CPP_SEMICOLON
/* The end of the cast-expression. */
&& next_token->type != CPP_CLOSE_PAREN
/* The end of an array bound. */
&& next_token->type != CPP_CLOSE_SQUARE
/* The closing ">" in a template-argument-list. */
&& (next_token->type != CPP_GREATER
|| parser->greater_than_is_operator_p))
cast_p = false;
}
/* If we are within a cast, then the constraint that the
cast is to an integral or enumeration type will be
checked at that point. If we are not within a cast, then
this code is invalid. */
if (!cast_p)
cp_parser_non_integral_constant_expression
(parser, "floating-point literal");
}
return token->u.value;
case CPP_STRING:
case CPP_WSTRING:
/* ??? Should wide strings be allowed when parser->translate_strings_p
is false (i.e. in attributes)? If not, we can kill the third
argument to cp_parser_string_literal. */
return cp_parser_string_literal (parser,
parser->translate_strings_p,
true);
case CPP_OPEN_PAREN:
{
tree expr;
bool saved_greater_than_is_operator_p;
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Within a parenthesized expression, a `>' token is always
the greater-than operator. */
saved_greater_than_is_operator_p
= parser->greater_than_is_operator_p;
parser->greater_than_is_operator_p = true;
/* If we see `( { ' then we are looking at the beginning of
a GNU statement-expression. */
if (cp_parser_allow_gnu_extensions_p (parser)
&& cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
{
/* Statement-expressions are not allowed by the standard. */
if (pedantic)
pedwarn ("ISO C++ forbids braced-groups within expressions");
/* And they're not allowed outside of a function-body; you
cannot, for example, write:
int i = ({ int j = 3; j + 1; });
at class or namespace scope. */
if (!parser->in_function_body)
error ("statement-expressions are allowed only inside functions");
/* Start the statement-expression. */
expr = begin_stmt_expr ();
/* Parse the compound-statement. */
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, expr, false, false);
/* Finish up. */
expr = finish_stmt_expr (expr, false);
}
else
{
/* Parse the parenthesized expression. */
expr = cp_parser_expression (parser, cast_p);
/* Let the front end know that this expression was
enclosed in parentheses. This matters in case, for
example, the expression is of the form `A::B', since
`&A::B' might be a pointer-to-member, but `&(A::B)' is
not. */
finish_parenthesized_expr (expr);
}
/* The `>' token might be the end of a template-id or
template-parameter-list now. */
parser->greater_than_is_operator_p
= saved_greater_than_is_operator_p;
/* Consume the `)'. */
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_end_of_statement (parser);
return expr;
}
case CPP_KEYWORD:
switch (token->keyword)
{
/* These two are the boolean literals. */
case RID_TRUE:
cp_lexer_consume_token (parser->lexer);
return boolean_true_node;
case RID_FALSE:
cp_lexer_consume_token (parser->lexer);
return boolean_false_node;
/* The `__null' literal. */
case RID_NULL:
cp_lexer_consume_token (parser->lexer);
return null_node;
/* Recognize the `this' keyword. */
case RID_THIS:
cp_lexer_consume_token (parser->lexer);
if (parser->local_variables_forbidden_p)
{
error ("%<this%> may not be used in this context");
return error_mark_node;
}
/* Pointers cannot appear in constant-expressions. */
if (cp_parser_non_integral_constant_expression (parser,
"`this'"))
return error_mark_node;
return finish_this_expr ();
/* The `operator' keyword can be the beginning of an
id-expression. */
case RID_OPERATOR:
goto id_expression;
case RID_FUNCTION_NAME:
case RID_PRETTY_FUNCTION_NAME:
case RID_C99_FUNCTION_NAME:
/* The symbols __FUNCTION__, __PRETTY_FUNCTION__, and
__func__ are the names of variables -- but they are
treated specially. Therefore, they are handled here,
rather than relying on the generic id-expression logic
below. Grammatically, these names are id-expressions.
Consume the token. */
token = cp_lexer_consume_token (parser->lexer);
/* Look up the name. */
return finish_fname (token->u.value);
case RID_VA_ARG:
{
tree expression;
tree type;
/* The `__builtin_va_arg' construct is used to handle
`va_arg'. Consume the `__builtin_va_arg' token. */
cp_lexer_consume_token (parser->lexer);
/* Look for the opening `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Now, parse the assignment-expression. */
expression = cp_parser_assignment_expression (parser,
/*cast_p=*/false);
/* Look for the `,'. */
cp_parser_require (parser, CPP_COMMA, "`,'");
/* Parse the type-id. */
type = cp_parser_type_id (parser);
/* Look for the closing `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Using `va_arg' in a constant-expression is not
allowed. */
if (cp_parser_non_integral_constant_expression (parser,
"`va_arg'"))
return error_mark_node;
return build_x_va_arg (expression, type);
}
case RID_OFFSETOF:
return cp_parser_builtin_offsetof (parser);
/* Objective-C++ expressions. */
case RID_AT_ENCODE:
case RID_AT_PROTOCOL:
case RID_AT_SELECTOR:
return cp_parser_objc_expression (parser);
default:
cp_parser_error (parser, "expected primary-expression");
return error_mark_node;
}
/* APPLE LOCAL begin CW asm blocks */
case CPP_ATSIGN:
/* Recognize @-labels and handle them specially later. */
cp_lexer_consume_token (parser->lexer);
atsignhack = 1;
token = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL end CW asm blocks */
/* An id-expression can start with either an identifier, a
`::' as the beginning of a qualified-id, or the "operator"
keyword. */
case CPP_NAME:
case CPP_SCOPE:
case CPP_TEMPLATE_ID:
case CPP_NESTED_NAME_SPECIFIER:
{
tree id_expression;
tree decl;
const char *error_msg;
bool template_p;
bool done;
id_expression:
/* Parse the id-expression. */
id_expression
= cp_parser_id_expression (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
&template_p,
/*declarator_p=*/false,
/*optional_p=*/false);
/* APPLE LOCAL begin CW asm blocks */
/* Replace the id with an id prefixed with @. */
if (atsignhack && id_expression != error_mark_node)
id_expression = prepend_char_identifier (id_expression, '@');
/* APPLE LOCAL end CW asm blocks */
if (id_expression == error_mark_node)
return error_mark_node;
token = cp_lexer_peek_token (parser->lexer);
done = (token->type != CPP_OPEN_SQUARE
&& token->type != CPP_OPEN_PAREN
&& token->type != CPP_DOT
&& token->type != CPP_DEREF
&& token->type != CPP_PLUS_PLUS
&& token->type != CPP_MINUS_MINUS);
/* If we have a template-id, then no further lookup is
required. If the template-id was for a template-class, we
will sometimes have a TYPE_DECL at this point. */
if (TREE_CODE (id_expression) == TEMPLATE_ID_EXPR
|| TREE_CODE (id_expression) == TYPE_DECL)
decl = id_expression;
/* Look up the name. */
else
{
tree ambiguous_decls;
decl = cp_parser_lookup_name (parser, id_expression,
none_type,
template_p,
/*is_namespace=*/false,
/*check_dependency=*/true,
&ambiguous_decls);
/* If the lookup was ambiguous, an error will already have
been issued. */
if (ambiguous_decls)
return error_mark_node;
/* APPLE LOCAL begin radar 5277239 */
if (TREE_CODE (decl) == TYPE_DECL
&& cp_objc_property_reference_prefix (parser, TREE_TYPE (decl)))
return cp_parser_objc_reference_expression (parser, decl);
/* APPLE LOCAL end radar 5277239 */
/* In Objective-C++, an instance variable (ivar) may be preferred
to whatever cp_parser_lookup_name() found. */
decl = objc_lookup_ivar (decl, id_expression);
/* If name lookup gives us a SCOPE_REF, then the
qualifying scope was dependent. */
if (TREE_CODE (decl) == SCOPE_REF)
{
/* At this point, we do not know if DECL is a valid
integral constant expression. We assume that it is
in fact such an expression, so that code like:
template <int N> struct A {
int a[B<N>::i];
};
is accepted. At template-instantiation time, we
will check that B<N>::i is actually a constant. */
return decl;
}
/* Check to see if DECL is a local variable in a context
where that is forbidden. */
if (parser->local_variables_forbidden_p
&& local_variable_p (decl))
{
/* It might be that we only found DECL because we are
trying to be generous with pre-ISO scoping rules.
For example, consider:
int i;
void g() {
for (int i = 0; i < 10; ++i) {}
extern void f(int j = i);
}
Here, name look up will originally find the out
of scope `i'. We need to issue a warning message,
but then use the global `i'. */
decl = check_for_out_of_scope_variable (decl);
if (local_variable_p (decl))
{
error ("local variable %qD may not appear in this context",
decl);
return error_mark_node;
}
}
}
decl = (finish_id_expression
(id_expression, decl, parser->scope,
idk,
parser->integral_constant_expression_p,
parser->allow_non_integral_constant_expression_p,
&parser->non_integral_constant_expression_p,
template_p, done, address_p,
template_arg_p,
&error_msg));
if (error_msg)
cp_parser_error (parser, error_msg);
return decl;
}
/* Anything else is an error. */
default:
/* APPLE LOCAL begin CW asm blocks */
if (inside_iasm_block)
{
if (token->type == CPP_OPEN_SQUARE)
{
tree expr;
cp_lexer_consume_token (parser->lexer);
expr = cp_parser_iasm_operand (parser);
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
return iasm_build_bracket (expr, NULL_TREE);
}
}
/* APPLE LOCAL end CW asm blocks */
/* ...unless we have an Objective-C++ message or string literal, that is. */
if (c_dialect_objc ()
&& (token->type == CPP_OPEN_SQUARE || token->type == CPP_OBJC_STRING))
return cp_parser_objc_expression (parser);
cp_parser_error (parser, "expected primary-expression");
return error_mark_node;
}
}
/* Parse an id-expression.
id-expression:
unqualified-id
qualified-id
qualified-id:
:: [opt] nested-name-specifier template [opt] unqualified-id
:: identifier
:: operator-function-id
:: template-id
Return a representation of the unqualified portion of the
identifier. Sets PARSER->SCOPE to the qualifying scope if there is
a `::' or nested-name-specifier.
Often, if the id-expression was a qualified-id, the caller will
want to make a SCOPE_REF to represent the qualified-id. This
function does not do this in order to avoid wastefully creating
SCOPE_REFs when they are not required.
If TEMPLATE_KEYWORD_P is true, then we have just seen the
`template' keyword.
If CHECK_DEPENDENCY_P is false, then names are looked up inside
uninstantiated templates.
If *TEMPLATE_P is non-NULL, it is set to true iff the
`template' keyword is used to explicitly indicate that the entity
named is a template.
If DECLARATOR_P is true, the id-expression is appearing as part of
a declarator, rather than as part of an expression. */
static tree
cp_parser_id_expression (cp_parser *parser,
bool template_keyword_p,
bool check_dependency_p,
bool *template_p,
bool declarator_p,
bool optional_p)
{
bool global_scope_p;
bool nested_name_specifier_p;
/* Assume the `template' keyword was not used. */
if (template_p)
*template_p = template_keyword_p;
/* Look for the optional `::' operator. */
global_scope_p
= (cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false)
!= NULL_TREE);
/* Look for the optional nested-name-specifier. */
nested_name_specifier_p
= (cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
check_dependency_p,
/*type_p=*/false,
declarator_p)
!= NULL_TREE);
/* If there is a nested-name-specifier, then we are looking at
the first qualified-id production. */
if (nested_name_specifier_p)
{
tree saved_scope;
tree saved_object_scope;
tree saved_qualifying_scope;
tree unqualified_id;
bool is_template;
/* See if the next token is the `template' keyword. */
if (!template_p)
template_p = &is_template;
*template_p = cp_parser_optional_template_keyword (parser);
/* Name lookup we do during the processing of the
unqualified-id might obliterate SCOPE. */
saved_scope = parser->scope;
saved_object_scope = parser->object_scope;
saved_qualifying_scope = parser->qualifying_scope;
/* Process the final unqualified-id. */
unqualified_id = cp_parser_unqualified_id (parser, *template_p,
check_dependency_p,
declarator_p,
/*optional_p=*/false);
/* Restore the SAVED_SCOPE for our caller. */
parser->scope = saved_scope;
parser->object_scope = saved_object_scope;
parser->qualifying_scope = saved_qualifying_scope;
return unqualified_id;
}
/* Otherwise, if we are in global scope, then we are looking at one
of the other qualified-id productions. */
else if (global_scope_p)
{
cp_token *token;
tree id;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's an identifier, and the next token is not a "<", then
we can avoid the template-id case. This is an optimization
for this common case. */
if (token->type == CPP_NAME
&& !cp_parser_nth_token_starts_template_argument_list_p
(parser, 2))
return cp_parser_identifier (parser);
cp_parser_parse_tentatively (parser);
/* Try a template-id. */
id = cp_parser_template_id (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
declarator_p);
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
return id;
/* Peek at the next token. (Changes in the token buffer may
have invalidated the pointer obtained above.) */
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_NAME:
return cp_parser_identifier (parser);
case CPP_KEYWORD:
if (token->keyword == RID_OPERATOR)
return cp_parser_operator_function_id (parser);
/* Fall through. */
default:
cp_parser_error (parser, "expected id-expression");
return error_mark_node;
}
}
else
return cp_parser_unqualified_id (parser, template_keyword_p,
/*check_dependency_p=*/true,
declarator_p,
optional_p);
}
/* Parse an unqualified-id.
unqualified-id:
identifier
operator-function-id
conversion-function-id
~ class-name
template-id
If TEMPLATE_KEYWORD_P is TRUE, we have just seen the `template'
keyword, in a construct like `A::template ...'.
Returns a representation of unqualified-id. For the `identifier'
production, an IDENTIFIER_NODE is returned. For the `~ class-name'
production a BIT_NOT_EXPR is returned; the operand of the
BIT_NOT_EXPR is an IDENTIFIER_NODE for the class-name. For the
other productions, see the documentation accompanying the
corresponding parsing functions. If CHECK_DEPENDENCY_P is false,
names are looked up in uninstantiated templates. If DECLARATOR_P
is true, the unqualified-id is appearing as part of a declarator,
rather than as part of an expression. */
static tree
cp_parser_unqualified_id (cp_parser* parser,
bool template_keyword_p,
bool check_dependency_p,
bool declarator_p,
bool optional_p)
{
cp_token *token;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_NAME:
{
tree id;
/* We don't know yet whether or not this will be a
template-id. */
cp_parser_parse_tentatively (parser);
/* Try a template-id. */
id = cp_parser_template_id (parser, template_keyword_p,
check_dependency_p,
declarator_p);
/* If it worked, we're done. */
if (cp_parser_parse_definitely (parser))
return id;
/* Otherwise, it's an ordinary identifier. */
return cp_parser_identifier (parser);
}
case CPP_TEMPLATE_ID:
return cp_parser_template_id (parser, template_keyword_p,
check_dependency_p,
declarator_p);
case CPP_COMPL:
{
tree type_decl;
tree qualifying_scope;
tree object_scope;
tree scope;
bool done;
/* Consume the `~' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the class-name. The standard, as written, seems to
say that:
template <typename T> struct S { ~S (); };
template <typename T> S<T>::~S() {}
is invalid, since `~' must be followed by a class-name, but
`S<T>' is dependent, and so not known to be a class.
That's not right; we need to look in uninstantiated
templates. A further complication arises from:
template <typename T> void f(T t) {
t.T::~T();
}
Here, it is not possible to look up `T' in the scope of `T'
itself. We must look in both the current scope, and the
scope of the containing complete expression.
Yet another issue is:
struct S {
int S;
~S();
};
S::~S() {}
The standard does not seem to say that the `S' in `~S'
should refer to the type `S' and not the data member
`S::S'. */
/* DR 244 says that we look up the name after the "~" in the
same scope as we looked up the qualifying name. That idea
isn't fully worked out; it's more complicated than that. */
scope = parser->scope;
object_scope = parser->object_scope;
qualifying_scope = parser->qualifying_scope;
/* Check for invalid scopes. */
if (scope == error_mark_node)
{
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
cp_lexer_consume_token (parser->lexer);
return error_mark_node;
}
if (scope && TREE_CODE (scope) == NAMESPACE_DECL)
{
if (!cp_parser_uncommitted_to_tentative_parse_p (parser))
error ("scope %qT before %<~%> is not a class-name", scope);
cp_parser_simulate_error (parser);
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
cp_lexer_consume_token (parser->lexer);
return error_mark_node;
}
gcc_assert (!scope || TYPE_P (scope));
/* If the name is of the form "X::~X" it's OK. */
token = cp_lexer_peek_token (parser->lexer);
if (scope
&& token->type == CPP_NAME
&& (cp_lexer_peek_nth_token (parser->lexer, 2)->type
== CPP_OPEN_PAREN)
&& constructor_name_p (token->u.value, scope))
{
cp_lexer_consume_token (parser->lexer);
return build_nt (BIT_NOT_EXPR, scope);
}
/* If there was an explicit qualification (S::~T), first look
in the scope given by the qualification (i.e., S). */
done = false;
type_decl = NULL_TREE;
if (scope)
{
cp_parser_parse_tentatively (parser);
type_decl = cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
none_type,
/*check_dependency=*/false,
/*class_head_p=*/false,
declarator_p);
if (cp_parser_parse_definitely (parser))
done = true;
}
/* In "N::S::~S", look in "N" as well. */
if (!done && scope && qualifying_scope)
{
cp_parser_parse_tentatively (parser);
parser->scope = qualifying_scope;
parser->object_scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
type_decl
= cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
none_type,
/*check_dependency=*/false,
/*class_head_p=*/false,
declarator_p);
if (cp_parser_parse_definitely (parser))
done = true;
}
/* In "p->S::~T", look in the scope given by "*p" as well. */
else if (!done && object_scope)
{
cp_parser_parse_tentatively (parser);
parser->scope = object_scope;
parser->object_scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
type_decl
= cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
none_type,
/*check_dependency=*/false,
/*class_head_p=*/false,
declarator_p);
if (cp_parser_parse_definitely (parser))
done = true;
}
/* Look in the surrounding context. */
if (!done)
{
parser->scope = NULL_TREE;
parser->object_scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
type_decl
= cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
none_type,
/*check_dependency=*/false,
/*class_head_p=*/false,
declarator_p);
}
/* If an error occurred, assume that the name of the
destructor is the same as the name of the qualifying
class. That allows us to keep parsing after running
into ill-formed destructor names. */
if (type_decl == error_mark_node && scope)
return build_nt (BIT_NOT_EXPR, scope);
else if (type_decl == error_mark_node)
return error_mark_node;
/* Check that destructor name and scope match. */
if (declarator_p && scope && !check_dtor_name (scope, type_decl))
{
if (!cp_parser_uncommitted_to_tentative_parse_p (parser))
error ("declaration of %<~%T%> as member of %qT",
type_decl, scope);
cp_parser_simulate_error (parser);
return error_mark_node;
}
/* [class.dtor]
A typedef-name that names a class shall not be used as the
identifier in the declarator for a destructor declaration. */
if (declarator_p
&& !DECL_IMPLICIT_TYPEDEF_P (type_decl)
&& !DECL_SELF_REFERENCE_P (type_decl)
&& !cp_parser_uncommitted_to_tentative_parse_p (parser))
error ("typedef-name %qD used as destructor declarator",
type_decl);
return build_nt (BIT_NOT_EXPR, TREE_TYPE (type_decl));
}
/* APPLE LOCAL begin CW asm blocks C++ */
case CPP_NUMBER:
{
if (flag_iasm_blocks && inside_iasm_block
&& TREE_CODE (token->u.value) == INTEGER_CST)
{
char buf[60];
sprintf (buf, HOST_WIDE_INT_PRINT_UNSIGNED, tree_low_cst (token->u.value, 0));
cp_lexer_consume_token (parser->lexer);
return get_identifier (buf);
}
goto bad;
}
/* APPLE LOCAL end CW asm blocks C++ */
case CPP_KEYWORD:
if (token->keyword == RID_OPERATOR)
{
tree id;
/* This could be a template-id, so we try that first. */
cp_parser_parse_tentatively (parser);
/* Try a template-id. */
id = cp_parser_template_id (parser, template_keyword_p,
/*check_dependency_p=*/true,
declarator_p);
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
return id;
/* We still don't know whether we're looking at an
operator-function-id or a conversion-function-id. */
cp_parser_parse_tentatively (parser);
/* Try an operator-function-id. */
id = cp_parser_operator_function_id (parser);
/* If that didn't work, try a conversion-function-id. */
if (!cp_parser_parse_definitely (parser))
id = cp_parser_conversion_function_id (parser);
return id;
}
/* Fall through. */
default:
if (optional_p)
return NULL_TREE;
/* APPLE LOCAL CW asm blocks C++ */
bad:
cp_parser_error (parser, "expected unqualified-id");
return error_mark_node;
}
}
/* Parse an (optional) nested-name-specifier.
nested-name-specifier:
class-or-namespace-name :: nested-name-specifier [opt]
class-or-namespace-name :: template nested-name-specifier [opt]
PARSER->SCOPE should be set appropriately before this function is
called. TYPENAME_KEYWORD_P is TRUE if the `typename' keyword is in
effect. TYPE_P is TRUE if we non-type bindings should be ignored
in name lookups.
Sets PARSER->SCOPE to the class (TYPE) or namespace
(NAMESPACE_DECL) specified by the nested-name-specifier, or leaves
it unchanged if there is no nested-name-specifier. Returns the new
scope iff there is a nested-name-specifier, or NULL_TREE otherwise.
If IS_DECLARATION is TRUE, the nested-name-specifier is known to be
part of a declaration and/or decl-specifier. */
static tree
cp_parser_nested_name_specifier_opt (cp_parser *parser,
bool typename_keyword_p,
bool check_dependency_p,
bool type_p,
bool is_declaration)
{
bool success = false;
cp_token_position start = 0;
cp_token *token;
/* Remember where the nested-name-specifier starts. */
if (cp_parser_uncommitted_to_tentative_parse_p (parser))
{
start = cp_lexer_token_position (parser->lexer, false);
push_deferring_access_checks (dk_deferred);
}
while (true)
{
tree new_scope;
tree old_scope;
tree saved_qualifying_scope;
bool template_keyword_p;
/* Spot cases that cannot be the beginning of a
nested-name-specifier. */
token = cp_lexer_peek_token (parser->lexer);
/* If the next token is CPP_NESTED_NAME_SPECIFIER, just process
the already parsed nested-name-specifier. */
if (token->type == CPP_NESTED_NAME_SPECIFIER)
{
/* Grab the nested-name-specifier and continue the loop. */
cp_parser_pre_parsed_nested_name_specifier (parser);
/* If we originally encountered this nested-name-specifier
with IS_DECLARATION set to false, we will not have
resolved TYPENAME_TYPEs, so we must do so here. */
if (is_declaration
&& TREE_CODE (parser->scope) == TYPENAME_TYPE)
{
new_scope = resolve_typename_type (parser->scope,
/*only_current_p=*/false);
if (new_scope != error_mark_node)
parser->scope = new_scope;
}
success = true;
continue;
}
/* Spot cases that cannot be the beginning of a
nested-name-specifier. On the second and subsequent times
through the loop, we look for the `template' keyword. */
if (success && token->keyword == RID_TEMPLATE)
;
/* A template-id can start a nested-name-specifier. */
else if (token->type == CPP_TEMPLATE_ID)
;
else
{
/* If the next token is not an identifier, then it is
definitely not a class-or-namespace-name. */
if (token->type != CPP_NAME)
break;
/* If the following token is neither a `<' (to begin a
template-id), nor a `::', then we are not looking at a
nested-name-specifier. */
token = cp_lexer_peek_nth_token (parser->lexer, 2);
if (token->type != CPP_SCOPE
&& !cp_parser_nth_token_starts_template_argument_list_p
(parser, 2))
break;
}
/* The nested-name-specifier is optional, so we parse
tentatively. */
cp_parser_parse_tentatively (parser);
/* Look for the optional `template' keyword, if this isn't the
first time through the loop. */
if (success)
template_keyword_p = cp_parser_optional_template_keyword (parser);
else
template_keyword_p = false;
/* Save the old scope since the name lookup we are about to do
might destroy it. */
old_scope = parser->scope;
saved_qualifying_scope = parser->qualifying_scope;
/* In a declarator-id like "X<T>::I::Y<T>" we must be able to
look up names in "X<T>::I" in order to determine that "Y" is
a template. So, if we have a typename at this point, we make
an effort to look through it. */
if (is_declaration
&& !typename_keyword_p
&& parser->scope
&& TREE_CODE (parser->scope) == TYPENAME_TYPE)
parser->scope = resolve_typename_type (parser->scope,
/*only_current_p=*/false);
/* Parse the qualifying entity. */
new_scope
= cp_parser_class_or_namespace_name (parser,
typename_keyword_p,
template_keyword_p,
check_dependency_p,
type_p,
is_declaration);
/* Look for the `::' token. */
cp_parser_require (parser, CPP_SCOPE, "`::'");
/* If we found what we wanted, we keep going; otherwise, we're
done. */
if (!cp_parser_parse_definitely (parser))
{
bool error_p = false;
/* Restore the OLD_SCOPE since it was valid before the
failed attempt at finding the last
class-or-namespace-name. */
parser->scope = old_scope;
parser->qualifying_scope = saved_qualifying_scope;
if (cp_parser_uncommitted_to_tentative_parse_p (parser))
break;
/* If the next token is an identifier, and the one after
that is a `::', then any valid interpretation would have
found a class-or-namespace-name. */
while (cp_lexer_next_token_is (parser->lexer, CPP_NAME)
&& (cp_lexer_peek_nth_token (parser->lexer, 2)->type
== CPP_SCOPE)
&& (cp_lexer_peek_nth_token (parser->lexer, 3)->type
!= CPP_COMPL))
{
token = cp_lexer_consume_token (parser->lexer);
if (!error_p)
{
if (!token->ambiguous_p)
{
tree decl;
tree ambiguous_decls;
decl = cp_parser_lookup_name (parser, token->u.value,
none_type,
/*is_template=*/false,
/*is_namespace=*/false,
/*check_dependency=*/true,
&ambiguous_decls);
if (TREE_CODE (decl) == TEMPLATE_DECL)
error ("%qD used without template parameters", decl);
else if (ambiguous_decls)
{
error ("reference to %qD is ambiguous",
token->u.value);
print_candidates (ambiguous_decls);
decl = error_mark_node;
}
else
cp_parser_name_lookup_error
(parser, token->u.value, decl,
"is not a class or namespace");
}
parser->scope = error_mark_node;
error_p = true;
/* Treat this as a successful nested-name-specifier
due to:
[basic.lookup.qual]
If the name found is not a class-name (clause
_class_) or namespace-name (_namespace.def_), the
program is ill-formed. */
success = true;
}
cp_lexer_consume_token (parser->lexer);
}
break;
}
/* We've found one valid nested-name-specifier. */
success = true;
/* Name lookup always gives us a DECL. */
if (TREE_CODE (new_scope) == TYPE_DECL)
new_scope = TREE_TYPE (new_scope);
/* Uses of "template" must be followed by actual templates. */
if (template_keyword_p
&& !(CLASS_TYPE_P (new_scope)
&& ((CLASSTYPE_USE_TEMPLATE (new_scope)
&& PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (new_scope)))
|| CLASSTYPE_IS_TEMPLATE (new_scope)))
&& !(TREE_CODE (new_scope) == TYPENAME_TYPE
&& (TREE_CODE (TYPENAME_TYPE_FULLNAME (new_scope))
== TEMPLATE_ID_EXPR)))
pedwarn (TYPE_P (new_scope)
? "%qT is not a template"
: "%qD is not a template",
new_scope);
/* If it is a class scope, try to complete it; we are about to
be looking up names inside the class. */
if (TYPE_P (new_scope)
/* Since checking types for dependency can be expensive,
avoid doing it if the type is already complete. */
&& !COMPLETE_TYPE_P (new_scope)
/* Do not try to complete dependent types. */
&& !dependent_type_p (new_scope))
new_scope = complete_type (new_scope);
/* Make sure we look in the right scope the next time through
the loop. */
parser->scope = new_scope;
}
/* If parsing tentatively, replace the sequence of tokens that makes
up the nested-name-specifier with a CPP_NESTED_NAME_SPECIFIER
token. That way, should we re-parse the token stream, we will
not have to repeat the effort required to do the parse, nor will
we issue duplicate error messages. */
if (success && start)
{
cp_token *token;
token = cp_lexer_token_at (parser->lexer, start);
/* Reset the contents of the START token. */
token->type = CPP_NESTED_NAME_SPECIFIER;
/* Retrieve any deferred checks. Do not pop this access checks yet
so the memory will not be reclaimed during token replacing below. */
token->u.tree_check_value = GGC_CNEW (struct tree_check);
token->u.tree_check_value->value = parser->scope;
token->u.tree_check_value->checks = get_deferred_access_checks ();
token->u.tree_check_value->qualifying_scope =
parser->qualifying_scope;
token->keyword = RID_MAX;
/* Purge all subsequent tokens. */
cp_lexer_purge_tokens_after (parser->lexer, start);
}
if (start)
pop_to_parent_deferring_access_checks ();
return success ? parser->scope : NULL_TREE;
}
/* Parse a nested-name-specifier. See
cp_parser_nested_name_specifier_opt for details. This function
behaves identically, except that it will an issue an error if no
nested-name-specifier is present. */
static tree
cp_parser_nested_name_specifier (cp_parser *parser,
bool typename_keyword_p,
bool check_dependency_p,
bool type_p,
bool is_declaration)
{
tree scope;
/* Look for the nested-name-specifier. */
scope = cp_parser_nested_name_specifier_opt (parser,
typename_keyword_p,
check_dependency_p,
type_p,
is_declaration);
/* If it was not present, issue an error message. */
if (!scope)
{
cp_parser_error (parser, "expected nested-name-specifier");
parser->scope = NULL_TREE;
}
return scope;
}
/* Parse a class-or-namespace-name.
class-or-namespace-name:
class-name
namespace-name
TYPENAME_KEYWORD_P is TRUE iff the `typename' keyword is in effect.
TEMPLATE_KEYWORD_P is TRUE iff the `template' keyword is in effect.
CHECK_DEPENDENCY_P is FALSE iff dependent names should be looked up.
TYPE_P is TRUE iff the next name should be taken as a class-name,
even the same name is declared to be another entity in the same
scope.
Returns the class (TYPE_DECL) or namespace (NAMESPACE_DECL)
specified by the class-or-namespace-name. If neither is found the
ERROR_MARK_NODE is returned. */
static tree
cp_parser_class_or_namespace_name (cp_parser *parser,
bool typename_keyword_p,
bool template_keyword_p,
bool check_dependency_p,
bool type_p,
bool is_declaration)
{
tree saved_scope;
tree saved_qualifying_scope;
tree saved_object_scope;
tree scope;
bool only_class_p;
/* Before we try to parse the class-name, we must save away the
current PARSER->SCOPE since cp_parser_class_name will destroy
it. */
saved_scope = parser->scope;
saved_qualifying_scope = parser->qualifying_scope;
saved_object_scope = parser->object_scope;
/* Try for a class-name first. If the SAVED_SCOPE is a type, then
there is no need to look for a namespace-name. */
only_class_p = template_keyword_p || (saved_scope && TYPE_P (saved_scope));
if (!only_class_p)
cp_parser_parse_tentatively (parser);
scope = cp_parser_class_name (parser,
typename_keyword_p,
template_keyword_p,
type_p ? class_type : none_type,
check_dependency_p,
/*class_head_p=*/false,
is_declaration);
/* If that didn't work, try for a namespace-name. */
if (!only_class_p && !cp_parser_parse_definitely (parser))
{
/* Restore the saved scope. */
parser->scope = saved_scope;
parser->qualifying_scope = saved_qualifying_scope;
parser->object_scope = saved_object_scope;
/* If we are not looking at an identifier followed by the scope
resolution operator, then this is not part of a
nested-name-specifier. (Note that this function is only used
to parse the components of a nested-name-specifier.) */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_NAME)
|| cp_lexer_peek_nth_token (parser->lexer, 2)->type != CPP_SCOPE)
return error_mark_node;
scope = cp_parser_namespace_name (parser);
}
return scope;
}
/* Parse a postfix-expression.
postfix-expression:
primary-expression
postfix-expression [ expression ]
postfix-expression ( expression-list [opt] )
simple-type-specifier ( expression-list [opt] )
typename :: [opt] nested-name-specifier identifier
( expression-list [opt] )
typename :: [opt] nested-name-specifier template [opt] template-id
( expression-list [opt] )
postfix-expression . template [opt] id-expression
postfix-expression -> template [opt] id-expression
postfix-expression . pseudo-destructor-name
postfix-expression -> pseudo-destructor-name
postfix-expression ++
postfix-expression --
dynamic_cast < type-id > ( expression )
static_cast < type-id > ( expression )
reinterpret_cast < type-id > ( expression )
const_cast < type-id > ( expression )
typeid ( expression )
typeid ( type-id )
GNU Extension:
postfix-expression:
( type-id ) { initializer-list , [opt] }
This extension is a GNU version of the C99 compound-literal
construct. (The C99 grammar uses `type-name' instead of `type-id',
but they are essentially the same concept.)
If ADDRESS_P is true, the postfix expression is the operand of the
`&' operator. CAST_P is true if this expression is the target of a
cast.
Returns a representation of the expression. */
static tree
cp_parser_postfix_expression (cp_parser *parser, bool address_p, bool cast_p)
{
cp_token *token;
enum rid keyword;
cp_id_kind idk = CP_ID_KIND_NONE;
tree postfix_expression = NULL_TREE;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Some of the productions are determined by keywords. */
keyword = token->keyword;
switch (keyword)
{
case RID_DYNCAST:
case RID_STATCAST:
case RID_REINTCAST:
case RID_CONSTCAST:
{
tree type;
tree expression;
const char *saved_message;
/* All of these can be handled in the same way from the point
of view of parsing. Begin by consuming the token
identifying the cast. */
cp_lexer_consume_token (parser->lexer);
/* New types cannot be defined in the cast. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in casts";
/* Look for the opening `<'. */
cp_parser_require (parser, CPP_LESS, "`<'");
/* Parse the type to which we are casting. */
type = cp_parser_type_id (parser);
/* Look for the closing `>'. */
cp_parser_require (parser, CPP_GREATER, "`>'");
/* Restore the old message. */
parser->type_definition_forbidden_message = saved_message;
/* And the expression which is being cast. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
expression = cp_parser_expression (parser, /*cast_p=*/true);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Only type conversions to integral or enumeration types
can be used in constant-expressions. */
if (!cast_valid_in_integral_constant_expression_p (type)
&& (cp_parser_non_integral_constant_expression
(parser,
"a cast to a type other than an integral or "
"enumeration type")))
return error_mark_node;
switch (keyword)
{
case RID_DYNCAST:
postfix_expression
= build_dynamic_cast (type, expression);
break;
case RID_STATCAST:
postfix_expression
= build_static_cast (type, expression);
break;
case RID_REINTCAST:
postfix_expression
= build_reinterpret_cast (type, expression);
break;
case RID_CONSTCAST:
postfix_expression
= build_const_cast (type, expression);
break;
default:
gcc_unreachable ();
}
}
break;
case RID_TYPEID:
{
tree type;
const char *saved_message;
bool saved_in_type_id_in_expr_p;
/* Consume the `typeid' token. */
cp_lexer_consume_token (parser->lexer);
/* Look for the `(' token. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Types cannot be defined in a `typeid' expression. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in a `typeid\' expression";
/* We can't be sure yet whether we're looking at a type-id or an
expression. */
cp_parser_parse_tentatively (parser);
/* Try a type-id first. */
saved_in_type_id_in_expr_p = parser->in_type_id_in_expr_p;
parser->in_type_id_in_expr_p = true;
type = cp_parser_type_id (parser);
parser->in_type_id_in_expr_p = saved_in_type_id_in_expr_p;
/* Look for the `)' token. Otherwise, we can't be sure that
we're not looking at an expression: consider `typeid (int
(3))', for example. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* If all went well, simply lookup the type-id. */
if (cp_parser_parse_definitely (parser))
postfix_expression = get_typeid (type);
/* Otherwise, fall back to the expression variant. */
else
{
tree expression;
/* Look for an expression. */
expression = cp_parser_expression (parser, /*cast_p=*/false);
/* Compute its typeid. */
postfix_expression = build_typeid (expression);
/* Look for the `)' token. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
}
/* Restore the saved message. */
parser->type_definition_forbidden_message = saved_message;
/* `typeid' may not appear in an integral constant expression. */
if (cp_parser_non_integral_constant_expression(parser,
"`typeid' operator"))
return error_mark_node;
}
break;
case RID_TYPENAME:
{
tree type;
/* The syntax permitted here is the same permitted for an
elaborated-type-specifier. */
type = cp_parser_elaborated_type_specifier (parser,
/*is_friend=*/false,
/*is_declaration=*/false);
postfix_expression = cp_parser_functional_cast (parser, type);
}
break;
default:
{
tree type;
/* If the next thing is a simple-type-specifier, we may be
looking at a functional cast. We could also be looking at
an id-expression. So, we try the functional cast, and if
that doesn't work we fall back to the primary-expression. */
cp_parser_parse_tentatively (parser);
/* Look for the simple-type-specifier. */
type = cp_parser_simple_type_specifier (parser,
/*decl_specs=*/NULL,
CP_PARSER_FLAGS_NONE);
/* Parse the cast itself. */
if (!cp_parser_error_occurred (parser))
postfix_expression
= cp_parser_functional_cast (parser, type);
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
break;
/* If the functional-cast didn't work out, try a
compound-literal. */
if (cp_parser_allow_gnu_extensions_p (parser)
&& cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
VEC(constructor_elt,gc) *initializer_list = NULL;
bool saved_in_type_id_in_expr_p;
cp_parser_parse_tentatively (parser);
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Parse the type. */
saved_in_type_id_in_expr_p = parser->in_type_id_in_expr_p;
parser->in_type_id_in_expr_p = true;
type = cp_parser_type_id (parser);
parser->in_type_id_in_expr_p = saved_in_type_id_in_expr_p;
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Look for the `{'. */
cp_parser_require (parser, CPP_OPEN_BRACE, "`{'");
/* If things aren't going well, there's no need to
keep going. */
if (!cp_parser_error_occurred (parser))
{
bool non_constant_p;
/* Parse the initializer-list. */
initializer_list
= cp_parser_initializer_list (parser, &non_constant_p);
/* Allow a trailing `,'. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
cp_lexer_consume_token (parser->lexer);
/* Look for the final `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
}
/* If that worked, we're definitely looking at a
compound-literal expression. */
if (cp_parser_parse_definitely (parser))
{
/* Warn the user that a compound literal is not
allowed in standard C++. */
/* APPLE LOCAL Altivec initializers 3068233 */
if (pedantic && TREE_CODE (type) != VECTOR_TYPE)
pedwarn ("ISO C++ forbids compound-literals");
/* For simplicitly, we disallow compound literals in
constant-expressions for simpliicitly. We could
allow compound literals of integer type, whose
initializer was a constant, in constant
expressions. Permitting that usage, as a further
extension, would not change the meaning of any
currently accepted programs. (Of course, as
compound literals are not part of ISO C++, the
standard has nothing to say.) */
if (cp_parser_non_integral_constant_expression
(parser, "non-constant compound literals"))
{
postfix_expression = error_mark_node;
break;
}
/* Form the representation of the compound-literal. */
postfix_expression
= finish_compound_literal (type, initializer_list);
break;
}
}
/* It must be a primary-expression. */
postfix_expression
= cp_parser_primary_expression (parser, address_p, cast_p,
/*template_arg_p=*/false,
&idk);
}
break;
}
/* Keep looping until the postfix-expression is complete. */
while (true)
{
if (idk == CP_ID_KIND_UNQUALIFIED
&& TREE_CODE (postfix_expression) == IDENTIFIER_NODE
&& cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_PAREN))
/* It is not a Koenig lookup function call. */
postfix_expression
= unqualified_name_lookup_error (postfix_expression);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_OPEN_SQUARE:
postfix_expression
= cp_parser_postfix_open_square_expression (parser,
postfix_expression,
false);
idk = CP_ID_KIND_NONE;
break;
case CPP_OPEN_PAREN:
/* postfix-expression ( expression-list [opt] ) */
{
bool koenig_p;
bool is_builtin_constant_p;
bool saved_integral_constant_expression_p = false;
bool saved_non_integral_constant_expression_p = false;
tree args;
is_builtin_constant_p
= DECL_IS_BUILTIN_CONSTANT_P (postfix_expression);
if (is_builtin_constant_p)
{
/* The whole point of __builtin_constant_p is to allow
non-constant expressions to appear as arguments. */
saved_integral_constant_expression_p
= parser->integral_constant_expression_p;
saved_non_integral_constant_expression_p
= parser->non_integral_constant_expression_p;
parser->integral_constant_expression_p = false;
}
args = (cp_parser_parenthesized_expression_list
(parser, /*is_attribute_list=*/false,
/*cast_p=*/false,
/*non_constant_p=*/NULL));
if (is_builtin_constant_p)
{
parser->integral_constant_expression_p
= saved_integral_constant_expression_p;
parser->non_integral_constant_expression_p
= saved_non_integral_constant_expression_p;
}
if (args == error_mark_node)
{
postfix_expression = error_mark_node;
break;
}
/* Function calls are not permitted in
constant-expressions. */
if (! builtin_valid_in_constant_expr_p (postfix_expression)
&& cp_parser_non_integral_constant_expression (parser,
"a function call"))
{
postfix_expression = error_mark_node;
break;
}
koenig_p = false;
if (idk == CP_ID_KIND_UNQUALIFIED)
{
if (TREE_CODE (postfix_expression) == IDENTIFIER_NODE)
{
if (args)
{
koenig_p = true;
postfix_expression
= perform_koenig_lookup (postfix_expression, args);
}
else
postfix_expression
= unqualified_fn_lookup_error (postfix_expression);
}
/* We do not perform argument-dependent lookup if
normal lookup finds a non-function, in accordance
with the expected resolution of DR 218. */
else if (args && is_overloaded_fn (postfix_expression))
{
tree fn = get_first_fn (postfix_expression);
if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
fn = OVL_CURRENT (TREE_OPERAND (fn, 0));
/* Only do argument dependent lookup if regular
lookup does not find a set of member functions.
[basic.lookup.koenig]/2a */
if (!DECL_FUNCTION_MEMBER_P (fn))
{
koenig_p = true;
postfix_expression
= perform_koenig_lookup (postfix_expression, args);
}
}
}
if (TREE_CODE (postfix_expression) == COMPONENT_REF)
{
tree instance = TREE_OPERAND (postfix_expression, 0);
tree fn = TREE_OPERAND (postfix_expression, 1);
if (processing_template_decl
&& (type_dependent_expression_p (instance)
|| (!BASELINK_P (fn)
&& TREE_CODE (fn) != FIELD_DECL)
|| type_dependent_expression_p (fn)
|| any_type_dependent_arguments_p (args)))
{
postfix_expression
= build_min_nt (CALL_EXPR, postfix_expression,
args, NULL_TREE);
break;
}
if (BASELINK_P (fn))
postfix_expression
= (build_new_method_call
(instance, fn, args, NULL_TREE,
(idk == CP_ID_KIND_QUALIFIED
? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL),
/*fn_p=*/NULL));
else
postfix_expression
= finish_call_expr (postfix_expression, args,
/*disallow_virtual=*/false,
/*koenig_p=*/false);
}
else if (TREE_CODE (postfix_expression) == OFFSET_REF
|| TREE_CODE (postfix_expression) == MEMBER_REF
|| TREE_CODE (postfix_expression) == DOTSTAR_EXPR)
postfix_expression = (build_offset_ref_call_from_tree
(postfix_expression, args));
else if (idk == CP_ID_KIND_QUALIFIED)
/* A call to a static class member, or a namespace-scope
function. */
postfix_expression
= finish_call_expr (postfix_expression, args,
/*disallow_virtual=*/true,
koenig_p);
else
/* All other function calls. */
postfix_expression
= finish_call_expr (postfix_expression, args,
/*disallow_virtual=*/false,
koenig_p);
/* The POSTFIX_EXPRESSION is certainly no longer an id. */
idk = CP_ID_KIND_NONE;
}
break;
case CPP_DOT:
case CPP_DEREF:
/* postfix-expression . template [opt] id-expression
postfix-expression . pseudo-destructor-name
postfix-expression -> template [opt] id-expression
postfix-expression -> pseudo-destructor-name */
/* Consume the `.' or `->' operator. */
cp_lexer_consume_token (parser->lexer);
postfix_expression
= cp_parser_postfix_dot_deref_expression (parser, token->type,
postfix_expression,
false, &idk);
break;
case CPP_PLUS_PLUS:
/* postfix-expression ++ */
/* Consume the `++' token. */
cp_lexer_consume_token (parser->lexer);
/* Generate a representation for the complete expression. */
postfix_expression
= finish_increment_expr (postfix_expression,
POSTINCREMENT_EXPR);
/* Increments may not appear in constant-expressions. */
if (cp_parser_non_integral_constant_expression (parser,
"an increment"))
postfix_expression = error_mark_node;
idk = CP_ID_KIND_NONE;
break;
case CPP_MINUS_MINUS:
/* postfix-expression -- */
/* Consume the `--' token. */
cp_lexer_consume_token (parser->lexer);
/* Generate a representation for the complete expression. */
postfix_expression
= finish_increment_expr (postfix_expression,
POSTDECREMENT_EXPR);
/* Decrements may not appear in constant-expressions. */
if (cp_parser_non_integral_constant_expression (parser,
"a decrement"))
postfix_expression = error_mark_node;
idk = CP_ID_KIND_NONE;
break;
default:
return postfix_expression;
}
}
/* We should never get here. */
gcc_unreachable ();
return error_mark_node;
}
/* A subroutine of cp_parser_postfix_expression that also gets hijacked
by cp_parser_builtin_offsetof. We're looking for
postfix-expression [ expression ]
FOR_OFFSETOF is set if we're being called in that context, which
changes how we deal with integer constant expressions. */
static tree
cp_parser_postfix_open_square_expression (cp_parser *parser,
tree postfix_expression,
bool for_offsetof)
{
tree index;
/* Consume the `[' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the index expression. */
/* ??? For offsetof, there is a question of what to allow here. If
offsetof is not being used in an integral constant expression context,
then we *could* get the right answer by computing the value at runtime.
If we are in an integral constant expression context, then we might
could accept any constant expression; hard to say without analysis.
Rather than open the barn door too wide right away, allow only integer
constant expressions here. */
if (for_offsetof)
index = cp_parser_constant_expression (parser, false, NULL);
else
index = cp_parser_expression (parser, /*cast_p=*/false);
/* Look for the closing `]'. */
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
/* APPLE LOCAL begin CW asm blocks */
if (inside_iasm_block)
if (TREE_CODE (postfix_expression) == BRACKET_EXPR
|| TREE_CODE (index) == IDENTIFIER_NODE
|| TREE_TYPE (index) == NULL_TREE)
return iasm_build_bracket (postfix_expression, index);
/* APPLE LOCAL end CW asm blocks */
/* Build the ARRAY_REF. */
postfix_expression = grok_array_decl (postfix_expression, index);
/* When not doing offsetof, array references are not permitted in
constant-expressions. */
if (!for_offsetof
&& (cp_parser_non_integral_constant_expression
(parser, "an array reference")))
postfix_expression = error_mark_node;
return postfix_expression;
}
/* A subroutine of cp_parser_postfix_expression that also gets hijacked
by cp_parser_builtin_offsetof. We're looking for
postfix-expression . template [opt] id-expression
postfix-expression . pseudo-destructor-name
postfix-expression -> template [opt] id-expression
postfix-expression -> pseudo-destructor-name
FOR_OFFSETOF is set if we're being called in that context. That sorta
limits what of the above we'll actually accept, but nevermind.
TOKEN_TYPE is the "." or "->" token, which will already have been
removed from the stream. */
static tree
cp_parser_postfix_dot_deref_expression (cp_parser *parser,
enum cpp_ttype token_type,
tree postfix_expression,
bool for_offsetof, cp_id_kind *idk)
{
tree name;
bool dependent_p;
bool pseudo_destructor_p;
tree scope = NULL_TREE;
/* If this is a `->' operator, dereference the pointer. */
if (token_type == CPP_DEREF)
postfix_expression = build_x_arrow (postfix_expression);
/* Check to see whether or not the expression is type-dependent. */
dependent_p = type_dependent_expression_p (postfix_expression);
/* The identifier following the `->' or `.' is not qualified. */
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
*idk = CP_ID_KIND_NONE;
/* Enter the scope corresponding to the type of the object
given by the POSTFIX_EXPRESSION. */
if (!dependent_p && TREE_TYPE (postfix_expression) != NULL_TREE)
{
scope = TREE_TYPE (postfix_expression);
/* According to the standard, no expression should ever have
reference type. Unfortunately, we do not currently match
the standard in this respect in that our internal representation
of an expression may have reference type even when the standard
says it does not. Therefore, we have to manually obtain the
underlying type here. */
scope = non_reference (scope);
/* The type of the POSTFIX_EXPRESSION must be complete. */
if (scope == unknown_type_node)
{
error ("%qE does not have class type", postfix_expression);
scope = NULL_TREE;
}
else
scope = complete_type_or_else (scope, NULL_TREE);
/* Let the name lookup machinery know that we are processing a
class member access expression. */
parser->context->object_type = scope;
/* If something went wrong, we want to be able to discern that case,
as opposed to the case where there was no SCOPE due to the type
of expression being dependent. */
if (!scope)
scope = error_mark_node;
/* If the SCOPE was erroneous, make the various semantic analysis
functions exit quickly -- and without issuing additional error
messages. */
if (scope == error_mark_node)
postfix_expression = error_mark_node;
}
/* Assume this expression is not a pseudo-destructor access. */
pseudo_destructor_p = false;
/* If the SCOPE is a scalar type, then, if this is a valid program,
we must be looking at a pseudo-destructor-name. */
if (scope && SCALAR_TYPE_P (scope))
{
tree s;
tree type;
cp_parser_parse_tentatively (parser);
/* Parse the pseudo-destructor-name. */
s = NULL_TREE;
cp_parser_pseudo_destructor_name (parser, &s, &type);
if (cp_parser_parse_definitely (parser))
{
pseudo_destructor_p = true;
postfix_expression
= finish_pseudo_destructor_expr (postfix_expression,
s, TREE_TYPE (type));
}
}
if (!pseudo_destructor_p)
{
/* If the SCOPE is not a scalar type, we are looking at an
ordinary class member access expression, rather than a
pseudo-destructor-name. */
bool template_p;
/* Parse the id-expression. */
name = (cp_parser_id_expression
(parser,
cp_parser_optional_template_keyword (parser),
/*check_dependency_p=*/true,
&template_p,
/*declarator_p=*/false,
/*optional_p=*/false));
/* In general, build a SCOPE_REF if the member name is qualified.
However, if the name was not dependent and has already been
resolved; there is no need to build the SCOPE_REF. For example;
struct X { void f(); };
template <typename T> void f(T* t) { t->X::f(); }
Even though "t" is dependent, "X::f" is not and has been resolved
to a BASELINK; there is no need to include scope information. */
/* But we do need to remember that there was an explicit scope for
virtual function calls. */
if (parser->scope)
*idk = CP_ID_KIND_QUALIFIED;
/* If the name is a template-id that names a type, we will get a
TYPE_DECL here. That is invalid code. */
if (TREE_CODE (name) == TYPE_DECL)
{
error ("invalid use of %qD", name);
postfix_expression = error_mark_node;
}
else
{
if (name != error_mark_node && !BASELINK_P (name) && parser->scope)
{
name = build_qualified_name (/*type=*/NULL_TREE,
parser->scope,
name,
template_p);
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
}
if (scope && name && BASELINK_P (name))
adjust_result_of_qualified_name_lookup
(name, BINFO_TYPE (BASELINK_ACCESS_BINFO (name)), scope);
postfix_expression
= finish_class_member_access_expr (postfix_expression, name,
template_p);
}
}
/* We no longer need to look up names in the scope of the object on
the left-hand side of the `.' or `->' operator. */
parser->context->object_type = NULL_TREE;
/* Outside of offsetof, these operators may not appear in
constant-expressions. */
if (!for_offsetof
&& (cp_parser_non_integral_constant_expression
(parser, token_type == CPP_DEREF ? "'->'" : "`.'")))
postfix_expression = error_mark_node;
return postfix_expression;
}
/* Parse a parenthesized expression-list.
expression-list:
assignment-expression
expression-list, assignment-expression
attribute-list:
expression-list
identifier
identifier, expression-list
CAST_P is true if this expression is the target of a cast.
Returns a TREE_LIST. The TREE_VALUE of each node is a
representation of an assignment-expression. Note that a TREE_LIST
is returned even if there is only a single expression in the list.
error_mark_node is returned if the ( and or ) are
missing. NULL_TREE is returned on no expressions. The parentheses
are eaten. IS_ATTRIBUTE_LIST is true if this is really an attribute
list being parsed. If NON_CONSTANT_P is non-NULL, *NON_CONSTANT_P
indicates whether or not all of the expressions in the list were
constant. */
static tree
cp_parser_parenthesized_expression_list (cp_parser* parser,
bool is_attribute_list,
bool cast_p,
bool *non_constant_p)
{
tree expression_list = NULL_TREE;
bool fold_expr_p = is_attribute_list;
tree identifier = NULL_TREE;
/* Assume all the expressions will be constant. */
if (non_constant_p)
*non_constant_p = false;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return error_mark_node;
/* Consume expressions until there are no more. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_PAREN))
while (true)
{
tree expr;
/* At the beginning of attribute lists, check to see if the
next token is an identifier. */
if (is_attribute_list
&& cp_lexer_peek_token (parser->lexer)->type == CPP_NAME)
{
cp_token *token;
/* Consume the identifier. */
token = cp_lexer_consume_token (parser->lexer);
/* Save the identifier. */
identifier = token->u.value;
}
else
{
/* Parse the next assignment-expression. */
if (non_constant_p)
{
bool expr_non_constant_p;
expr = (cp_parser_constant_expression
(parser, /*allow_non_constant_p=*/true,
&expr_non_constant_p));
if (expr_non_constant_p)
*non_constant_p = true;
}
else
expr = cp_parser_assignment_expression (parser, cast_p);
if (fold_expr_p)
expr = fold_non_dependent_expr (expr);
/* Add it to the list. We add error_mark_node
expressions to the list, so that we can still tell if
the correct form for a parenthesized expression-list
is found. That gives better errors. */
expression_list = tree_cons (NULL_TREE, expr, expression_list);
if (expr == error_mark_node)
goto skip_comma;
}
/* After the first item, attribute lists look the same as
expression lists. */
is_attribute_list = false;
get_comma:;
/* If the next token isn't a `,', then we are done. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Otherwise, consume the `,' and keep going. */
cp_lexer_consume_token (parser->lexer);
}
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
{
int ending;
skip_comma:;
/* We try and resync to an unnested comma, as that will give the
user better diagnostics. */
ending = cp_parser_skip_to_closing_parenthesis (parser,
/*recovering=*/true,
/*or_comma=*/true,
/*consume_paren=*/true);
if (ending < 0)
goto get_comma;
if (!ending)
return error_mark_node;
}
/* We built up the list in reverse order so we must reverse it now. */
expression_list = nreverse (expression_list);
if (identifier)
expression_list = tree_cons (NULL_TREE, identifier, expression_list);
return expression_list;
}
/* Parse a pseudo-destructor-name.
pseudo-destructor-name:
:: [opt] nested-name-specifier [opt] type-name :: ~ type-name
:: [opt] nested-name-specifier template template-id :: ~ type-name
:: [opt] nested-name-specifier [opt] ~ type-name
If either of the first two productions is used, sets *SCOPE to the
TYPE specified before the final `::'. Otherwise, *SCOPE is set to
NULL_TREE. *TYPE is set to the TYPE_DECL for the final type-name,
or ERROR_MARK_NODE if the parse fails. */
static void
cp_parser_pseudo_destructor_name (cp_parser* parser,
tree* scope,
tree* type)
{
bool nested_name_specifier_p;
/* Assume that things will not work out. */
*type = error_mark_node;
/* Look for the optional `::' operator. */
cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/true);
/* Look for the optional nested-name-specifier. */
nested_name_specifier_p
= (cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/true)
!= NULL_TREE);
/* Now, if we saw a nested-name-specifier, we might be doing the
second production. */
if (nested_name_specifier_p
&& cp_lexer_next_token_is_keyword (parser->lexer, RID_TEMPLATE))
{
/* Consume the `template' keyword. */
cp_lexer_consume_token (parser->lexer);
/* Parse the template-id. */
cp_parser_template_id (parser,
/*template_keyword_p=*/true,
/*check_dependency_p=*/false,
/*is_declaration=*/true);
/* Look for the `::' token. */
cp_parser_require (parser, CPP_SCOPE, "`::'");
}
/* If the next token is not a `~', then there might be some
additional qualification. */
else if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMPL))
{
/* Look for the type-name. */
*scope = TREE_TYPE (cp_parser_type_name (parser));
if (*scope == error_mark_node)
return;
/* If we don't have ::~, then something has gone wrong. Since
the only caller of this function is looking for something
after `.' or `->' after a scalar type, most likely the
program is trying to get a member of a non-aggregate
type. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SCOPE)
|| cp_lexer_peek_nth_token (parser->lexer, 2)->type != CPP_COMPL)
{
cp_parser_error (parser, "request for member of non-aggregate type");
return;
}
/* Look for the `::' token. */
cp_parser_require (parser, CPP_SCOPE, "`::'");
}
else
*scope = NULL_TREE;
/* Look for the `~'. */
cp_parser_require (parser, CPP_COMPL, "`~'");
/* Look for the type-name again. We are not responsible for
checking that it matches the first type-name. */
*type = cp_parser_type_name (parser);
}
/* Parse a unary-expression.
unary-expression:
postfix-expression
++ cast-expression
-- cast-expression
unary-operator cast-expression
sizeof unary-expression
sizeof ( type-id )
new-expression
delete-expression
GNU Extensions:
unary-expression:
__extension__ cast-expression
__alignof__ unary-expression
__alignof__ ( type-id )
__real__ cast-expression
__imag__ cast-expression
&& identifier
ADDRESS_P is true iff the unary-expression is appearing as the
operand of the `&' operator. CAST_P is true if this expression is
the target of a cast.
Returns a representation of the expression. */
static tree
cp_parser_unary_expression (cp_parser *parser, bool address_p, bool cast_p)
{
cp_token *token;
enum tree_code unary_operator;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Some keywords give away the kind of expression. */
if (token->type == CPP_KEYWORD)
{
enum rid keyword = token->keyword;
switch (keyword)
{
/* APPLE LOCAL begin CW asm blocks */
case RID_SIZEOF:
if (inside_iasm_block)
break;
case RID_ALIGNOF:
/* APPLE LOCAL end CW asm blocks */
{
tree operand;
enum tree_code op;
op = keyword == RID_ALIGNOF ? ALIGNOF_EXPR : SIZEOF_EXPR;
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the operand. */
operand = cp_parser_sizeof_operand (parser, keyword);
if (TYPE_P (operand))
return cxx_sizeof_or_alignof_type (operand, op, true);
else
return cxx_sizeof_or_alignof_expr (operand, op);
}
case RID_NEW:
return cp_parser_new_expression (parser);
case RID_DELETE:
return cp_parser_delete_expression (parser);
case RID_EXTENSION:
{
/* The saved value of the PEDANTIC flag. */
int saved_pedantic;
tree expr;
/* Save away the PEDANTIC flag. */
cp_parser_extension_opt (parser, &saved_pedantic);
/* Parse the cast-expression. */
expr = cp_parser_simple_cast_expression (parser);
/* Restore the PEDANTIC flag. */
pedantic = saved_pedantic;
return expr;
}
case RID_REALPART:
case RID_IMAGPART:
{
tree expression;
/* Consume the `__real__' or `__imag__' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the cast-expression. */
expression = cp_parser_simple_cast_expression (parser);
/* Create the complete representation. */
return build_x_unary_op ((keyword == RID_REALPART
? REALPART_EXPR : IMAGPART_EXPR),
expression);
}
break;
default:
break;
}
}
/* Look for the `:: new' and `:: delete', which also signal the
beginning of a new-expression, or delete-expression,
respectively. If the next token is `::', then it might be one of
these. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SCOPE))
{
enum rid keyword;
/* See if the token after the `::' is one of the keywords in
which we're interested. */
keyword = cp_lexer_peek_nth_token (parser->lexer, 2)->keyword;
/* If it's `new', we have a new-expression. */
if (keyword == RID_NEW)
return cp_parser_new_expression (parser);
/* Similarly, for `delete'. */
else if (keyword == RID_DELETE)
return cp_parser_delete_expression (parser);
}
/* Look for a unary operator. */
unary_operator = cp_parser_unary_operator (token);
/* APPLE LOCAL begin CW asm blocks */
/* In the context of CW asm block, '*' followed by '+' or '-' is for
relative branch syntax. This is to allow "b *+8" which
is disallwed by darwin's assembler but nevertheless is needed to
be compatible with CW tools. */
if (inside_iasm_block && unary_operator == INDIRECT_REF)
{
cp_token *token = cp_lexer_peek_nth_token (parser->lexer, 2);
if (token->type == CPP_PLUS || token->type == CPP_MINUS)
unary_operator = ERROR_MARK;
}
/* APPLE LOCAL end CW asm blocks */
/* The `++' and `--' operators can be handled similarly, even though
they are not technically unary-operators in the grammar. */
if (unary_operator == ERROR_MARK)
{
if (token->type == CPP_PLUS_PLUS)
unary_operator = PREINCREMENT_EXPR;
else if (token->type == CPP_MINUS_MINUS)
unary_operator = PREDECREMENT_EXPR;
/* Handle the GNU address-of-label extension. */
else if (cp_parser_allow_gnu_extensions_p (parser)
&& token->type == CPP_AND_AND)
{
tree identifier;
/* Consume the '&&' token. */
cp_lexer_consume_token (parser->lexer);
/* Look for the identifier. */
identifier = cp_parser_identifier (parser);
/* Create an expression representing the address. */
return finish_label_address_expr (identifier);
}
}
if (unary_operator != ERROR_MARK)
{
tree cast_expression;
tree expression = error_mark_node;
const char *non_constant_p = NULL;
/* Consume the operator token. */
token = cp_lexer_consume_token (parser->lexer);
/* Parse the cast-expression. */
cast_expression
= cp_parser_cast_expression (parser,
unary_operator == ADDR_EXPR,
/*cast_p=*/false);
/* Now, build an appropriate representation. */
switch (unary_operator)
{
case INDIRECT_REF:
non_constant_p = "`*'";
expression = build_x_indirect_ref (cast_expression, "unary *");
break;
case ADDR_EXPR:
non_constant_p = "`&'";
/* Fall through. */
case BIT_NOT_EXPR:
/* APPLE LOCAL begin CW asm blocks */
if (inside_iasm_block
&& unary_operator == ADDR_EXPR
&& TREE_CODE (cast_expression) == LABEL_DECL)
{
expression = finish_label_address_expr (DECL_NAME (cast_expression));
break;
}
/* APPLE LOCAL end CW asm blocks */
expression = build_x_unary_op (unary_operator, cast_expression);
break;
case PREINCREMENT_EXPR:
case PREDECREMENT_EXPR:
non_constant_p = (unary_operator == PREINCREMENT_EXPR
? "`++'" : "`--'");
/* Fall through. */
case UNARY_PLUS_EXPR:
case NEGATE_EXPR:
case TRUTH_NOT_EXPR:
/* APPLE LOCAL begin CW asm blocks */
if (inside_iasm_block && TREE_TYPE (cast_expression) == 0)
{
expression = build1 (unary_operator, NULL_TREE, cast_expression);
break;
}
/* APPLE LOCAL end CW asm blocks */
expression = finish_unary_op_expr (unary_operator, cast_expression);
break;
default:
gcc_unreachable ();
}
if (non_constant_p
&& cp_parser_non_integral_constant_expression (parser,
non_constant_p))
expression = error_mark_node;
return expression;
}
/* APPLE LOCAL begin CW asm blocks */
/* Postfix expressions in CW asm are more restricted and handled
quite differently, so diverge from the usual expression
precedence sequence here. */
if (inside_iasm_block)
return cp_parser_iasm_postfix_expression (parser, address_p, cast_p);
/* APPLE LOCAL end CW asm blocks */
return cp_parser_postfix_expression (parser, address_p, cast_p);
}
/* Returns ERROR_MARK if TOKEN is not a unary-operator. If TOKEN is a
unary-operator, the corresponding tree code is returned. */
static enum tree_code
cp_parser_unary_operator (cp_token* token)
{
switch (token->type)
{
case CPP_MULT:
return INDIRECT_REF;
case CPP_AND:
return ADDR_EXPR;
case CPP_PLUS:
return UNARY_PLUS_EXPR;
case CPP_MINUS:
return NEGATE_EXPR;
case CPP_NOT:
return TRUTH_NOT_EXPR;
case CPP_COMPL:
return BIT_NOT_EXPR;
/* APPLE LOCAL begin CW asm blocks */
case CPP_NAME:
if (iasm_state >= iasm_decls
&& flag_ms_asms
&& strcasecmp (IDENTIFIER_POINTER (token->u.value), "offset") == 0)
return ADDR_EXPR;
/* APPLE LOCAL end CW asm blocks */
default:
return ERROR_MARK;
}
}
/* Parse a new-expression.
new-expression:
:: [opt] new new-placement [opt] new-type-id new-initializer [opt]
:: [opt] new new-placement [opt] ( type-id ) new-initializer [opt]
Returns a representation of the expression. */
static tree
cp_parser_new_expression (cp_parser* parser)
{
bool global_scope_p;
tree placement;
tree type;
tree initializer;
tree nelts;
/* Look for the optional `::' operator. */
global_scope_p
= (cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false)
!= NULL_TREE);
/* Look for the `new' operator. */
cp_parser_require_keyword (parser, RID_NEW, "`new'");
/* There's no easy way to tell a new-placement from the
`( type-id )' construct. */
cp_parser_parse_tentatively (parser);
/* Look for a new-placement. */
placement = cp_parser_new_placement (parser);
/* If that didn't work out, there's no new-placement. */
if (!cp_parser_parse_definitely (parser))
placement = NULL_TREE;
/* If the next token is a `(', then we have a parenthesized
type-id. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Parse the type-id. */
type = cp_parser_type_id (parser);
/* Look for the closing `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* There should not be a direct-new-declarator in this production,
but GCC used to allowed this, so we check and emit a sensible error
message for this case. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_SQUARE))
{
error ("array bound forbidden after parenthesized type-id");
inform ("try removing the parentheses around the type-id");
cp_parser_direct_new_declarator (parser);
}
nelts = NULL_TREE;
}
/* Otherwise, there must be a new-type-id. */
else
type = cp_parser_new_type_id (parser, &nelts);
/* If the next token is a `(', then we have a new-initializer. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
initializer = cp_parser_new_initializer (parser);
else
initializer = NULL_TREE;
/* A new-expression may not appear in an integral constant
expression. */
if (cp_parser_non_integral_constant_expression (parser, "`new'"))
return error_mark_node;
/* Create a representation of the new-expression. */
return build_new (placement, type, nelts, initializer, global_scope_p);
}
/* Parse a new-placement.
new-placement:
( expression-list )
Returns the same representation as for an expression-list. */
static tree
cp_parser_new_placement (cp_parser* parser)
{
tree expression_list;
/* Parse the expression-list. */
expression_list = (cp_parser_parenthesized_expression_list
(parser, false, /*cast_p=*/false,
/*non_constant_p=*/NULL));
return expression_list;
}
/* Parse a new-type-id.
new-type-id:
type-specifier-seq new-declarator [opt]
Returns the TYPE allocated. If the new-type-id indicates an array
type, *NELTS is set to the number of elements in the last array
bound; the TYPE will not include the last array bound. */
static tree
cp_parser_new_type_id (cp_parser* parser, tree *nelts)
{
cp_decl_specifier_seq type_specifier_seq;
cp_declarator *new_declarator;
cp_declarator *declarator;
cp_declarator *outer_declarator;
const char *saved_message;
tree type;
/* The type-specifier sequence must not contain type definitions.
(It cannot contain declarations of new types either, but if they
are not definitions we will catch that because they are not
complete.) */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in a new-type-id";
/* Parse the type-specifier-seq. */
cp_parser_type_specifier_seq (parser, /*is_condition=*/false,
&type_specifier_seq);
/* Restore the old message. */
parser->type_definition_forbidden_message = saved_message;
/* Parse the new-declarator. */
new_declarator = cp_parser_new_declarator_opt (parser);
/* Determine the number of elements in the last array dimension, if
any. */
*nelts = NULL_TREE;
/* Skip down to the last array dimension. */
declarator = new_declarator;
outer_declarator = NULL;
while (declarator && (declarator->kind == cdk_pointer
|| declarator->kind == cdk_ptrmem))
{
outer_declarator = declarator;
declarator = declarator->declarator;
}
while (declarator
&& declarator->kind == cdk_array
&& declarator->declarator
&& declarator->declarator->kind == cdk_array)
{
outer_declarator = declarator;
declarator = declarator->declarator;
}
if (declarator && declarator->kind == cdk_array)
{
*nelts = declarator->u.array.bounds;
if (*nelts == error_mark_node)
*nelts = integer_one_node;
if (outer_declarator)
outer_declarator->declarator = declarator->declarator;
else
new_declarator = NULL;
}
type = groktypename (&type_specifier_seq, new_declarator);
if (TREE_CODE (type) == ARRAY_TYPE && *nelts == NULL_TREE)
{
*nelts = array_type_nelts_top (type);
type = TREE_TYPE (type);
}
return type;
}
/* Parse an (optional) new-declarator.
new-declarator:
ptr-operator new-declarator [opt]
direct-new-declarator
Returns the declarator. */
static cp_declarator *
cp_parser_new_declarator_opt (cp_parser* parser)
{
enum tree_code code;
tree type;
cp_cv_quals cv_quals;
/* We don't know if there's a ptr-operator next, or not. */
cp_parser_parse_tentatively (parser);
/* Look for a ptr-operator. */
code = cp_parser_ptr_operator (parser, &type, &cv_quals);
/* If that worked, look for more new-declarators. */
if (cp_parser_parse_definitely (parser))
{
cp_declarator *declarator;
/* Parse another optional declarator. */
declarator = cp_parser_new_declarator_opt (parser);
/* Create the representation of the declarator. */
if (type)
declarator = make_ptrmem_declarator (cv_quals, type, declarator);
else if (code == INDIRECT_REF)
declarator = make_pointer_declarator (cv_quals, declarator);
else
declarator = make_reference_declarator (cv_quals, declarator);
return declarator;
}
/* If the next token is a `[', there is a direct-new-declarator. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_SQUARE))
return cp_parser_direct_new_declarator (parser);
return NULL;
}
/* Parse a direct-new-declarator.
direct-new-declarator:
[ expression ]
direct-new-declarator [constant-expression]
*/
static cp_declarator *
cp_parser_direct_new_declarator (cp_parser* parser)
{
cp_declarator *declarator = NULL;
while (true)
{
tree expression;
/* Look for the opening `['. */
cp_parser_require (parser, CPP_OPEN_SQUARE, "`['");
/* The first expression is not required to be constant. */
if (!declarator)
{
expression = cp_parser_expression (parser, /*cast_p=*/false);
/* The standard requires that the expression have integral
type. DR 74 adds enumeration types. We believe that the
real intent is that these expressions be handled like the
expression in a `switch' condition, which also allows
classes with a single conversion to integral or
enumeration type. */
if (!processing_template_decl)
{
expression
= build_expr_type_conversion (WANT_INT | WANT_ENUM,
expression,
/*complain=*/true);
if (!expression)
{
error ("expression in new-declarator must have integral "
"or enumeration type");
expression = error_mark_node;
}
}
}
/* But all the other expressions must be. */
else
expression
= cp_parser_constant_expression (parser,
/*allow_non_constant=*/false,
NULL);
/* Look for the closing `]'. */
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
/* Add this bound to the declarator. */
declarator = make_array_declarator (declarator, expression);
/* If the next token is not a `[', then there are no more
bounds. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_SQUARE))
break;
}
return declarator;
}
/* Parse a new-initializer.
new-initializer:
( expression-list [opt] )
Returns a representation of the expression-list. If there is no
expression-list, VOID_ZERO_NODE is returned. */
static tree
cp_parser_new_initializer (cp_parser* parser)
{
tree expression_list;
expression_list = (cp_parser_parenthesized_expression_list
(parser, false, /*cast_p=*/false,
/*non_constant_p=*/NULL));
if (!expression_list)
expression_list = void_zero_node;
return expression_list;
}
/* Parse a delete-expression.
delete-expression:
:: [opt] delete cast-expression
:: [opt] delete [ ] cast-expression
Returns a representation of the expression. */
static tree
cp_parser_delete_expression (cp_parser* parser)
{
bool global_scope_p;
bool array_p;
tree expression;
/* Look for the optional `::' operator. */
global_scope_p
= (cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false)
!= NULL_TREE);
/* Look for the `delete' keyword. */
cp_parser_require_keyword (parser, RID_DELETE, "`delete'");
/* See if the array syntax is in use. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_SQUARE))
{
/* Consume the `[' token. */
cp_lexer_consume_token (parser->lexer);
/* Look for the `]' token. */
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
/* Remember that this is the `[]' construct. */
array_p = true;
}
else
array_p = false;
/* Parse the cast-expression. */
expression = cp_parser_simple_cast_expression (parser);
/* A delete-expression may not appear in an integral constant
expression. */
if (cp_parser_non_integral_constant_expression (parser, "`delete'"))
return error_mark_node;
return delete_sanity (expression, NULL_TREE, array_p, global_scope_p);
}
/* Parse a cast-expression.
cast-expression:
unary-expression
( type-id ) cast-expression
ADDRESS_P is true iff the unary-expression is appearing as the
operand of the `&' operator. CAST_P is true if this expression is
the target of a cast.
Returns a representation of the expression. */
static tree
cp_parser_cast_expression (cp_parser *parser, bool address_p, bool cast_p)
{
/* If it's a `(', then we might be looking at a cast. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
tree type = NULL_TREE;
tree expr = NULL_TREE;
bool compound_literal_p;
const char *saved_message;
/* There's no way to know yet whether or not this is a cast.
For example, `(int (3))' is a unary-expression, while `(int)
3' is a cast. So, we resort to parsing tentatively. */
cp_parser_parse_tentatively (parser);
/* Types may not be defined in a cast. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in casts";
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* A very tricky bit is that `(struct S) { 3 }' is a
compound-literal (which we permit in C++ as an extension).
But, that construct is not a cast-expression -- it is a
postfix-expression. (The reason is that `(struct S) { 3 }.i'
is legal; if the compound-literal were a cast-expression,
you'd need an extra set of parentheses.) But, if we parse
the type-id, and it happens to be a class-specifier, then we
will commit to the parse at that point, because we cannot
undo the action that is done when creating a new class. So,
then we cannot back up and do a postfix-expression.
Therefore, we scan ahead to the closing `)', and check to see
if the token after the `)' is a `{'. If so, we are not
looking at a cast-expression.
Save tokens so that we can put them back. */
cp_lexer_save_tokens (parser->lexer);
/* Skip tokens until the next token is a closing parenthesis.
If we find the closing `)', and the next token is a `{', then
we are looking at a compound-literal. */
compound_literal_p
= (cp_parser_skip_to_closing_parenthesis (parser, false, false,
/*consume_paren=*/true)
&& cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE));
/* Roll back the tokens we skipped. */
cp_lexer_rollback_tokens (parser->lexer);
/* If we were looking at a compound-literal, simulate an error
so that the call to cp_parser_parse_definitely below will
fail. */
if (compound_literal_p)
cp_parser_simulate_error (parser);
else
{
bool saved_in_type_id_in_expr_p = parser->in_type_id_in_expr_p;
parser->in_type_id_in_expr_p = true;
/* Look for the type-id. */
type = cp_parser_type_id (parser);
/* Look for the closing `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
parser->in_type_id_in_expr_p = saved_in_type_id_in_expr_p;
}
/* Restore the saved message. */
parser->type_definition_forbidden_message = saved_message;
/* If ok so far, parse the dependent expression. We cannot be
sure it is a cast. Consider `(T ())'. It is a parenthesized
ctor of T, but looks like a cast to function returning T
without a dependent expression. */
if (!cp_parser_error_occurred (parser))
expr = cp_parser_cast_expression (parser,
/*address_p=*/false,
/*cast_p=*/true);
if (cp_parser_parse_definitely (parser))
{
/* Warn about old-style casts, if so requested. */
if (warn_old_style_cast
&& !in_system_header
&& !VOID_TYPE_P (type)
&& current_lang_name != lang_name_c)
warning (OPT_Wold_style_cast, "use of old-style cast");
/* Only type conversions to integral or enumeration types
can be used in constant-expressions. */
if (!cast_valid_in_integral_constant_expression_p (type)
&& (cp_parser_non_integral_constant_expression
(parser,
"a cast to a type other than an integral or "
"enumeration type")))
return error_mark_node;
/* Perform the cast. */
expr = build_c_cast (type, expr);
/* APPLE LOCAL begin radar 4426814 */
return (c_dialect_objc() && flag_objc_gc)
/* APPLE LOCAL radar 5276085 */
? objc_build_weak_reference_tree (expr) : expr;
/* APPLE LOCAL end radar 4426814 */
}
}
/* If we get here, then it's not a cast, so it must be a
unary-expression. */
/* APPLE LOCAL begin radar 4426814 */
if (c_dialect_objc() && flag_objc_gc)
/* APPLE LOCAL radar 5276085 */
return objc_build_weak_reference_tree (
cp_parser_unary_expression (parser, address_p, cast_p));
else
return cp_parser_unary_expression (parser, address_p, cast_p);
/* APPLE LOCAL end radar 4426814 */
}
/* Parse a binary expression of the general form:
pm-expression:
cast-expression
pm-expression .* cast-expression
pm-expression ->* cast-expression
multiplicative-expression:
pm-expression
multiplicative-expression * pm-expression
multiplicative-expression / pm-expression
multiplicative-expression % pm-expression
additive-expression:
multiplicative-expression
additive-expression + multiplicative-expression
additive-expression - multiplicative-expression
shift-expression:
additive-expression
shift-expression << additive-expression
shift-expression >> additive-expression
relational-expression:
shift-expression
relational-expression < shift-expression
relational-expression > shift-expression
relational-expression <= shift-expression
relational-expression >= shift-expression
GNU Extension:
relational-expression:
relational-expression <? shift-expression
relational-expression >? shift-expression
equality-expression:
relational-expression
equality-expression == relational-expression
equality-expression != relational-expression
and-expression:
equality-expression
and-expression & equality-expression
exclusive-or-expression:
and-expression
exclusive-or-expression ^ and-expression
inclusive-or-expression:
exclusive-or-expression
inclusive-or-expression | exclusive-or-expression
logical-and-expression:
inclusive-or-expression
logical-and-expression && inclusive-or-expression
logical-or-expression:
logical-and-expression
logical-or-expression || logical-and-expression
All these are implemented with a single function like:
binary-expression:
simple-cast-expression
binary-expression <token> binary-expression
CAST_P is true if this expression is the target of a cast.
The binops_by_token map is used to get the tree codes for each <token> type.
binary-expressions are associated according to a precedence table. */
#define TOKEN_PRECEDENCE(token) \
((token->type == CPP_GREATER && !parser->greater_than_is_operator_p) \
? PREC_NOT_OPERATOR \
: binops_by_token[token->type].prec)
static tree
cp_parser_binary_expression (cp_parser* parser, bool cast_p)
{
cp_parser_expression_stack stack;
cp_parser_expression_stack_entry *sp = &stack[0];
tree lhs, rhs;
cp_token *token;
enum tree_code tree_type;
enum cp_parser_prec prec = PREC_NOT_OPERATOR, new_prec, lookahead_prec;
bool overloaded_p;
/* Parse the first expression. */
lhs = cp_parser_cast_expression (parser, /*address_p=*/false, cast_p);
for (;;)
{
/* Get an operator token. */
token = cp_lexer_peek_token (parser->lexer);
new_prec = TOKEN_PRECEDENCE (token);
/* APPLE LOCAL begin CW asm blocks */
if (flag_iasm_blocks && inside_iasm_block)
{
if ((token->flags & BOL) != 0)
new_prec = PREC_NOT_OPERATOR;
}
/* APPLE LOCAL end CW asm blocks */
/* Popping an entry off the stack means we completed a subexpression:
- either we found a token which is not an operator (`>' where it is not
an operator, or prec == PREC_NOT_OPERATOR), in which case popping
will happen repeatedly;
- or, we found an operator which has lower priority. This is the case
where the recursive descent *ascends*, as in `3 * 4 + 5' after
parsing `3 * 4'. */
if (new_prec <= prec)
{
if (sp == stack)
break;
else
goto pop;
}
get_rhs:
tree_type = binops_by_token[token->type].tree_type;
/* We used the operator token. */
cp_lexer_consume_token (parser->lexer);
/* Extract another operand. It may be the RHS of this expression
or the LHS of a new, higher priority expression. */
rhs = cp_parser_simple_cast_expression (parser);
/* Get another operator token. Look up its precedence to avoid
building a useless (immediately popped) stack entry for common
cases such as 3 + 4 + 5 or 3 * 4 + 5. */
token = cp_lexer_peek_token (parser->lexer);
lookahead_prec = TOKEN_PRECEDENCE (token);
/* APPLE LOCAL begin CW asm blocks */
if (flag_iasm_blocks && inside_iasm_block)
{
if ((token->flags & BOL) != 0)
lookahead_prec = PREC_NOT_OPERATOR;
}
/* APPLE LOCAL end CW asm blocks */
if (lookahead_prec > new_prec)
{
/* ... and prepare to parse the RHS of the new, higher priority
expression. Since precedence levels on the stack are
monotonically increasing, we do not have to care about
stack overflows. */
sp->prec = prec;
sp->tree_type = tree_type;
sp->lhs = lhs;
sp++;
lhs = rhs;
prec = new_prec;
new_prec = lookahead_prec;
goto get_rhs;
pop:
/* If the stack is not empty, we have parsed into LHS the right side
(`4' in the example above) of an expression we had suspended.
We can use the information on the stack to recover the LHS (`3')
from the stack together with the tree code (`MULT_EXPR'), and
the precedence of the higher level subexpression
(`PREC_ADDITIVE_EXPRESSION'). TOKEN is the CPP_PLUS token,
which will be used to actually build the additive expression. */
--sp;
prec = sp->prec;
tree_type = sp->tree_type;
rhs = lhs;
lhs = sp->lhs;
}
/* APPLE LOCAL begin CW asm blocks */
if (inside_iasm_block && TREE_CODE (rhs) == COMPOUND_EXPR)
{
gcc_assert (TREE_CODE (TREE_OPERAND (rhs, 1)) == IDENTIFIER_NODE);
lhs = build_x_binary_op (tree_type, lhs, TREE_OPERAND (rhs, 0), &overloaded_p);
lhs = iasm_build_register_offset (lhs, TREE_OPERAND (rhs, 1));
return lhs;
}
if (inside_iasm_block)
{
if (TREE_CODE (rhs) == IDENTIFIER_NODE
|| TREE_CODE (lhs) == IDENTIFIER_NODE
|| TREE_TYPE (rhs) == NULL_TREE
|| TREE_TYPE (lhs) == NULL_TREE)
{
lhs = build2 (tree_type, NULL_TREE, lhs, rhs);
continue;
}
}
/* APPLE LOCAL end CW asm blocks */
overloaded_p = false;
lhs = build_x_binary_op (tree_type, lhs, rhs, &overloaded_p);
/* If the binary operator required the use of an overloaded operator,
then this expression cannot be an integral constant-expression.
An overloaded operator can be used even if both operands are
otherwise permissible in an integral constant-expression if at
least one of the operands is of enumeration type. */
if (overloaded_p
&& (cp_parser_non_integral_constant_expression
(parser, "calls to overloaded operators")))
return error_mark_node;
}
return lhs;
}
/* Parse the `? expression : assignment-expression' part of a
conditional-expression. The LOGICAL_OR_EXPR is the
logical-or-expression that started the conditional-expression.
Returns a representation of the entire conditional-expression.
This routine is used by cp_parser_assignment_expression.
? expression : assignment-expression
GNU Extensions:
? : assignment-expression */
static tree
cp_parser_question_colon_clause (cp_parser* parser, tree logical_or_expr)
{
tree expr;
tree assignment_expr;
/* Consume the `?' token. */
cp_lexer_consume_token (parser->lexer);
if (cp_parser_allow_gnu_extensions_p (parser)
&& cp_lexer_next_token_is (parser->lexer, CPP_COLON))
/* Implicit true clause. */
expr = NULL_TREE;
else
/* Parse the expression. */
expr = cp_parser_expression (parser, /*cast_p=*/false);
/* The next token should be a `:'. */
cp_parser_require (parser, CPP_COLON, "`:'");
/* Parse the assignment-expression. */
assignment_expr = cp_parser_assignment_expression (parser, /*cast_p=*/false);
/* Build the conditional-expression. */
return build_x_conditional_expr (logical_or_expr,
expr,
assignment_expr);
}
/* Parse an assignment-expression.
assignment-expression:
conditional-expression
logical-or-expression assignment-operator assignment_expression
throw-expression
CAST_P is true if this expression is the target of a cast.
Returns a representation for the expression. */
static tree
cp_parser_assignment_expression (cp_parser* parser, bool cast_p)
{
tree expr;
/* If the next token is the `throw' keyword, then we're looking at
a throw-expression. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_THROW))
expr = cp_parser_throw_expression (parser);
/* Otherwise, it must be that we are looking at a
logical-or-expression. */
else
{
/* Parse the binary expressions (logical-or-expression). */
expr = cp_parser_binary_expression (parser, cast_p);
/* If the next token is a `?' then we're actually looking at a
conditional-expression. */
if (cp_lexer_next_token_is (parser->lexer, CPP_QUERY))
return cp_parser_question_colon_clause (parser, expr);
else
{
enum tree_code assignment_operator;
/* If it's an assignment-operator, we're using the second
production. */
assignment_operator
= cp_parser_assignment_operator_opt (parser);
if (assignment_operator != ERROR_MARK)
{
tree rhs;
/* Parse the right-hand side of the assignment. */
rhs = cp_parser_assignment_expression (parser, cast_p);
/* An assignment may not appear in a
constant-expression. */
if (cp_parser_non_integral_constant_expression (parser,
"an assignment"))
return error_mark_node;
/* Build the assignment expression. */
expr = build_x_modify_expr (expr,
assignment_operator,
rhs);
}
}
}
return expr;
}
/* Parse an (optional) assignment-operator.
assignment-operator: one of
= *= /= %= += -= >>= <<= &= ^= |=
GNU Extension:
assignment-operator: one of
<?= >?=
If the next token is an assignment operator, the corresponding tree
code is returned, and the token is consumed. For example, for
`+=', PLUS_EXPR is returned. For `=' itself, the code returned is
NOP_EXPR. For `/', TRUNC_DIV_EXPR is returned; for `%',
TRUNC_MOD_EXPR is returned. If TOKEN is not an assignment
operator, ERROR_MARK is returned. */
static enum tree_code
cp_parser_assignment_operator_opt (cp_parser* parser)
{
enum tree_code op;
cp_token *token;
/* Peek at the next toen. */
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_EQ:
op = NOP_EXPR;
break;
case CPP_MULT_EQ:
op = MULT_EXPR;
break;
case CPP_DIV_EQ:
op = TRUNC_DIV_EXPR;
break;
case CPP_MOD_EQ:
op = TRUNC_MOD_EXPR;
break;
case CPP_PLUS_EQ:
op = PLUS_EXPR;
break;
case CPP_MINUS_EQ:
op = MINUS_EXPR;
break;
case CPP_RSHIFT_EQ:
op = RSHIFT_EXPR;
break;
case CPP_LSHIFT_EQ:
op = LSHIFT_EXPR;
break;
case CPP_AND_EQ:
op = BIT_AND_EXPR;
break;
case CPP_XOR_EQ:
op = BIT_XOR_EXPR;
break;
case CPP_OR_EQ:
op = BIT_IOR_EXPR;
break;
default:
/* Nothing else is an assignment operator. */
op = ERROR_MARK;
}
/* If it was an assignment operator, consume it. */
if (op != ERROR_MARK)
cp_lexer_consume_token (parser->lexer);
return op;
}
/* Parse an expression.
expression:
assignment-expression
expression , assignment-expression
CAST_P is true if this expression is the target of a cast.
Returns a representation of the expression. */
static tree
cp_parser_expression (cp_parser* parser, bool cast_p)
{
tree expression = NULL_TREE;
while (true)
{
tree assignment_expression;
/* Parse the next assignment-expression. */
assignment_expression
= cp_parser_assignment_expression (parser, cast_p);
/* If this is the first assignment-expression, we can just
save it away. */
if (!expression)
expression = assignment_expression;
else
expression = build_x_compound_expr (expression,
assignment_expression);
/* If the next token is not a comma, then we are done with the
expression. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Consume the `,'. */
cp_lexer_consume_token (parser->lexer);
/* A comma operator cannot appear in a constant-expression. */
if (cp_parser_non_integral_constant_expression (parser,
"a comma operator"))
expression = error_mark_node;
}
return expression;
}
/* Parse a constant-expression.
constant-expression:
conditional-expression
If ALLOW_NON_CONSTANT_P a non-constant expression is silently
accepted. If ALLOW_NON_CONSTANT_P is true and the expression is not
constant, *NON_CONSTANT_P is set to TRUE. If ALLOW_NON_CONSTANT_P
is false, NON_CONSTANT_P should be NULL. */
static tree
cp_parser_constant_expression (cp_parser* parser,
bool allow_non_constant_p,
bool *non_constant_p)
{
bool saved_integral_constant_expression_p;
bool saved_allow_non_integral_constant_expression_p;
bool saved_non_integral_constant_expression_p;
tree expression;
/* It might seem that we could simply parse the
conditional-expression, and then check to see if it were
TREE_CONSTANT. However, an expression that is TREE_CONSTANT is
one that the compiler can figure out is constant, possibly after
doing some simplifications or optimizations. The standard has a
precise definition of constant-expression, and we must honor
that, even though it is somewhat more restrictive.
For example:
int i[(2, 3)];
is not a legal declaration, because `(2, 3)' is not a
constant-expression. The `,' operator is forbidden in a
constant-expression. However, GCC's constant-folding machinery
will fold this operation to an INTEGER_CST for `3'. */
/* Save the old settings. */
saved_integral_constant_expression_p = parser->integral_constant_expression_p;
saved_allow_non_integral_constant_expression_p
= parser->allow_non_integral_constant_expression_p;
saved_non_integral_constant_expression_p = parser->non_integral_constant_expression_p;
/* We are now parsing a constant-expression. */
parser->integral_constant_expression_p = true;
parser->allow_non_integral_constant_expression_p = allow_non_constant_p;
parser->non_integral_constant_expression_p = false;
/* Although the grammar says "conditional-expression", we parse an
"assignment-expression", which also permits "throw-expression"
and the use of assignment operators. In the case that
ALLOW_NON_CONSTANT_P is false, we get better errors than we would
otherwise. In the case that ALLOW_NON_CONSTANT_P is true, it is
actually essential that we look for an assignment-expression.
For example, cp_parser_initializer_clauses uses this function to
determine whether a particular assignment-expression is in fact
constant. */
expression = cp_parser_assignment_expression (parser, /*cast_p=*/false);
/* Restore the old settings. */
parser->integral_constant_expression_p
= saved_integral_constant_expression_p;
parser->allow_non_integral_constant_expression_p
= saved_allow_non_integral_constant_expression_p;
if (allow_non_constant_p)
*non_constant_p = parser->non_integral_constant_expression_p;
else if (parser->non_integral_constant_expression_p)
expression = error_mark_node;
parser->non_integral_constant_expression_p
= saved_non_integral_constant_expression_p;
return expression;
}
/* Parse __builtin_offsetof.
offsetof-expression:
"__builtin_offsetof" "(" type-id "," offsetof-member-designator ")"
offsetof-member-designator:
id-expression
| offsetof-member-designator "." id-expression
| offsetof-member-designator "[" expression "]" */
static tree
cp_parser_builtin_offsetof (cp_parser *parser)
{
int save_ice_p, save_non_ice_p;
tree type, expr;
cp_id_kind dummy;
/* We're about to accept non-integral-constant things, but will
definitely yield an integral constant expression. Save and
restore these values around our local parsing. */
save_ice_p = parser->integral_constant_expression_p;
save_non_ice_p = parser->non_integral_constant_expression_p;
/* Consume the "__builtin_offsetof" token. */
cp_lexer_consume_token (parser->lexer);
/* Consume the opening `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Parse the type-id. */
type = cp_parser_type_id (parser);
/* Look for the `,'. */
cp_parser_require (parser, CPP_COMMA, "`,'");
/* Build the (type *)null that begins the traditional offsetof macro. */
expr = build_static_cast (build_pointer_type (type), null_pointer_node);
/* Parse the offsetof-member-designator. We begin as if we saw "expr->". */
expr = cp_parser_postfix_dot_deref_expression (parser, CPP_DEREF, expr,
true, &dummy);
while (true)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_OPEN_SQUARE:
/* offsetof-member-designator "[" expression "]" */
expr = cp_parser_postfix_open_square_expression (parser, expr, true);
break;
case CPP_DOT:
/* offsetof-member-designator "." identifier */
cp_lexer_consume_token (parser->lexer);
expr = cp_parser_postfix_dot_deref_expression (parser, CPP_DOT, expr,
true, &dummy);
break;
case CPP_CLOSE_PAREN:
/* Consume the ")" token. */
cp_lexer_consume_token (parser->lexer);
goto success;
default:
/* Error. We know the following require will fail, but
that gives the proper error message. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
cp_parser_skip_to_closing_parenthesis (parser, true, false, true);
expr = error_mark_node;
goto failure;
}
}
success:
/* If we're processing a template, we can't finish the semantics yet.
Otherwise we can fold the entire expression now. */
if (processing_template_decl)
expr = build1 (OFFSETOF_EXPR, size_type_node, expr);
else
expr = finish_offsetof (expr);
failure:
parser->integral_constant_expression_p = save_ice_p;
parser->non_integral_constant_expression_p = save_non_ice_p;
return expr;
}
/* Statements [gram.stmt.stmt] */
/* Parse a statement.
statement:
labeled-statement
expression-statement
compound-statement
selection-statement
iteration-statement
jump-statement
declaration-statement
try-block
IN_COMPOUND is true when the statement is nested inside a
cp_parser_compound_statement; this matters for certain pragmas. */
static void
cp_parser_statement (cp_parser* parser, tree in_statement_expr,
bool in_compound)
{
tree statement;
cp_token *token;
location_t statement_location;
restart:
/* There is no statement yet. */
statement = NULL_TREE;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Remember the location of the first token in the statement. */
statement_location = token->location;
/* If this is a keyword, then that will often determine what kind of
statement we have. */
if (token->type == CPP_KEYWORD)
{
enum rid keyword = token->keyword;
switch (keyword)
{
case RID_CASE:
case RID_DEFAULT:
/* Looks like a labeled-statement with a case label.
Parse the label, and then use tail recursion to parse
the statement. */
cp_parser_label_for_labeled_statement (parser);
goto restart;
case RID_IF:
case RID_SWITCH:
statement = cp_parser_selection_statement (parser);
break;
case RID_WHILE:
case RID_DO:
case RID_FOR:
statement = cp_parser_iteration_statement (parser);
break;
case RID_BREAK:
case RID_CONTINUE:
case RID_RETURN:
case RID_GOTO:
statement = cp_parser_jump_statement (parser);
break;
/* Objective-C++ exception-handling constructs. */
case RID_AT_TRY:
case RID_AT_CATCH:
case RID_AT_FINALLY:
case RID_AT_SYNCHRONIZED:
case RID_AT_THROW:
statement = cp_parser_objc_statement (parser);
break;
case RID_TRY:
statement = cp_parser_try_block (parser);
break;
default:
/* It might be a keyword like `int' that can start a
declaration-statement. */
break;
}
}
else if (token->type == CPP_NAME)
{
/* If the next token is a `:', then we are looking at a
labeled-statement. */
token = cp_lexer_peek_nth_token (parser->lexer, 2);
if (token->type == CPP_COLON)
{
/* Looks like a labeled-statement with an ordinary label.
Parse the label, and then use tail recursion to parse
the statement. */
cp_parser_label_for_labeled_statement (parser);
goto restart;
}
}
/* Anything that starts with a `{' must be a compound-statement. */
else if (token->type == CPP_OPEN_BRACE)
/* APPLE LOCAL radar 5982990 */
statement = cp_parser_compound_statement (parser, NULL, false, false);
/* CPP_PRAGMA is a #pragma inside a function body, which constitutes
a statement all its own. */
else if (token->type == CPP_PRAGMA)
{
/* Only certain OpenMP pragmas are attached to statements, and thus
are considered statements themselves. All others are not. In
the context of a compound, accept the pragma as a "statement" and
return so that we can check for a close brace. Otherwise we
require a real statement and must go back and read one. */
if (in_compound)
cp_parser_pragma (parser, pragma_compound);
else if (!cp_parser_pragma (parser, pragma_stmt))
goto restart;
return;
}
else if (token->type == CPP_EOF)
{
cp_parser_error (parser, "expected statement");
return;
}
/* Everything else must be a declaration-statement or an
expression-statement. Try for the declaration-statement
first, unless we are looking at a `;', in which case we know that
we have an expression-statement. */
if (!statement)
{
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
{
cp_parser_parse_tentatively (parser);
/* Try to parse the declaration-statement. */
cp_parser_declaration_statement (parser);
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
return;
}
/* Look for an expression-statement instead. */
statement = cp_parser_expression_statement (parser, in_statement_expr);
}
/* Set the line number for the statement. */
if (statement && STATEMENT_CODE_P (TREE_CODE (statement)))
SET_EXPR_LOCATION (statement, statement_location);
}
/* Parse the label for a labeled-statement, i.e.
identifier :
case constant-expression :
default :
GNU Extension:
case constant-expression ... constant-expression : statement
When a label is parsed without errors, the label is added to the
parse tree by the finish_* functions, so this function doesn't
have to return the label. */
static void
cp_parser_label_for_labeled_statement (cp_parser* parser)
{
cp_token *token;
/* The next token should be an identifier. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type != CPP_NAME
&& token->type != CPP_KEYWORD)
{
cp_parser_error (parser, "expected labeled-statement");
return;
}
switch (token->keyword)
{
case RID_CASE:
{
tree expr, expr_hi;
cp_token *ellipsis;
/* Consume the `case' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the constant-expression. */
expr = cp_parser_constant_expression (parser,
/*allow_non_constant_p=*/false,
NULL);
ellipsis = cp_lexer_peek_token (parser->lexer);
if (ellipsis->type == CPP_ELLIPSIS)
{
/* Consume the `...' token. */
cp_lexer_consume_token (parser->lexer);
expr_hi =
cp_parser_constant_expression (parser,
/*allow_non_constant_p=*/false,
NULL);
/* We don't need to emit warnings here, as the common code
will do this for us. */
}
else
expr_hi = NULL_TREE;
if (parser->in_switch_statement_p)
finish_case_label (expr, expr_hi);
else
error ("case label %qE not within a switch statement", expr);
}
break;
case RID_DEFAULT:
/* Consume the `default' token. */
cp_lexer_consume_token (parser->lexer);
if (parser->in_switch_statement_p)
finish_case_label (NULL_TREE, NULL_TREE);
else
error ("case label not within a switch statement");
break;
default:
/* Anything else must be an ordinary label. */
finish_label_stmt (cp_parser_identifier (parser));
break;
}
/* Require the `:' token. */
cp_parser_require (parser, CPP_COLON, "`:'");
}
/* Parse an expression-statement.
expression-statement:
expression [opt] ;
Returns the new EXPR_STMT -- or NULL_TREE if the expression
statement consists of nothing more than an `;'. IN_STATEMENT_EXPR_P
indicates whether this expression-statement is part of an
expression statement. */
static tree
cp_parser_expression_statement (cp_parser* parser, tree in_statement_expr)
{
tree statement = NULL_TREE;
/* If the next token is a ';', then there is no expression
statement. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
statement = cp_parser_expression (parser, /*cast_p=*/false);
/* Consume the final `;'. */
cp_parser_consume_semicolon_at_end_of_statement (parser);
if (in_statement_expr
&& cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE))
/* This is the final expression statement of a statement
expression. */
statement = finish_stmt_expr_expr (statement, in_statement_expr);
else if (statement)
statement = finish_expr_stmt (statement);
else
finish_stmt ();
return statement;
}
/* Parse a compound-statement.
compound-statement:
{ statement-seq [opt] }
Returns a tree representing the statement. */
static tree
cp_parser_compound_statement (cp_parser *parser, tree in_statement_expr,
/* APPLE LOCAL radar 5982990 */
bool in_try, bool objc_sjlj_exceptions)
{
tree compound_stmt;
/* Consume the `{'. */
if (!cp_parser_require (parser, CPP_OPEN_BRACE, "`{'"))
return error_mark_node;
/* Begin the compound-statement. */
compound_stmt = begin_compound_stmt (in_try ? BCS_TRY_BLOCK : 0);
/* APPLE LOCAL begin CW asm blocks */
/* Maybe this is the body of an asm function, which has asm lines
following the decls. */
if (iasm_state >= iasm_decls)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
iasm_in_decl = true;
if (token->u.value && IASM_SEE_OPCODE (TYPESPEC, token->u.value) == IDENTIFIER)
{
token->keyword = RID_MAX;
token->type = CPP_NAME;
}
cp_parser_iasm_declaration_seq_opt (parser);
iasm_in_decl = false;
iasm_state = iasm_asm;
inside_iasm_block = true;
iasm_kill_regs = true;
/* LLVM LOCAL */
iasm_label_counter = 0;
cp_parser_iasm_line_seq_opt (parser);
iasm_state = iasm_none;
iasm_end_block ();
}
else
/* APPLE LOCAL end CW asm blocks */
/* Parse an (optional) statement-seq. */
cp_parser_statement_seq_opt (parser, in_statement_expr);
/* APPLE LOCAL begin radar 5982990 */
if (objc_sjlj_exceptions)
objc_mark_locals_volatile (NULL);
/* APPLE LOCAL end radar 5982990 */
/* Finish the compound-statement. */
finish_compound_stmt (compound_stmt);
/* Consume the `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
return compound_stmt;
}
/* APPLE LOCAL begin CW asm blocks */
static bool
cp_lexer_iasm_bol (cp_lexer* lexer)
{
/* We can't use cp_lexer_peek_token here, as it will give errors for things like
1st in MS-stype asm. */
cp_token *token = lexer->next_token;
return (token->flags & BOL) != 0;
}
/* APPLE LOCAL end CW asm blocks */
/* Parse an (optional) statement-seq.
statement-seq:
statement
statement-seq [opt] statement */
static void
cp_parser_statement_seq_opt (cp_parser* parser, tree in_statement_expr)
{
/* APPLE LOCAL begin omit calls to empty destructors 5559195 */
tree class_type = DECL_CONTEXT (current_function_decl);
bool determine_destructor_triviality =
DECL_DESTRUCTOR_P (current_function_decl) && class_type != NULL_TREE
&& !CLASSTYPE_DESTRUCTOR_TRIVIALITY_FINAL (class_type);
/* Assume that the destructor is trivial at first, and mark nontrivial if
any statement is parsed. */
if (determine_destructor_triviality)
{
CLASSTYPE_HAS_NONTRIVIAL_DESTRUCTOR_BODY (class_type) = 0;
CLASSTYPE_DESTRUCTOR_TRIVIALITY_FINAL (class_type) = 1;
}
/* APPLE LOCAL end omit calls to empty destructors 5559195 */
/* Scan statements until there aren't any more. */
while (true)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL begin ObjC++ 4185810 */
/* If we're looking at a `}', then we've run out of
statements; the same is true if we have reached the end
of file, or have stumbled upon a stray 'else' or '@end'. */
if (token->type == CPP_CLOSE_BRACE
|| token->type == CPP_EOF
|| token->type == CPP_PRAGMA_EOL
|| (token->type == CPP_KEYWORD
&& (token->keyword == RID_ELSE
|| token->keyword == RID_AT_END)))
/* APPLE LOCAL end ObjC++ 4185810 */
break;
/* APPLE LOCAL begin omit calls to empty destructors 5559195 */
if (determine_destructor_triviality)
CLASSTYPE_HAS_NONTRIVIAL_DESTRUCTOR_BODY (class_type) = 1;
/* APPLE LOCAL end omit calls to empty destructors 5559195 */
/* Parse the statement. */
cp_parser_statement (parser, in_statement_expr, true);
/* APPLE LOCAL begin CW asm blocks */
if (flag_iasm_blocks
&& iasm_state >= iasm_decls
&& (cp_lexer_iasm_bol (parser->lexer)
|| cp_lexer_next_token_is (parser->lexer, CPP_NAME)))
break;
/* APPLE LOCAL end CW asm blocks */
}
}
/* Parse a selection-statement.
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
Returns the new IF_STMT or SWITCH_STMT. */
static tree
cp_parser_selection_statement (cp_parser* parser)
{
cp_token *token;
enum rid keyword;
/* Peek at the next token. */
token = cp_parser_require (parser, CPP_KEYWORD, "selection-statement");
/* See what kind of keyword it is. */
keyword = token->keyword;
switch (keyword)
{
case RID_IF:
case RID_SWITCH:
{
tree statement;
tree condition;
/* Look for the `('. */
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
{
cp_parser_skip_to_end_of_statement (parser);
return error_mark_node;
}
/* Begin the selection-statement. */
if (keyword == RID_IF)
statement = begin_if_stmt ();
else
statement = begin_switch_stmt ();
/* Parse the condition. */
condition = cp_parser_condition (parser);
/* Look for the `)'. */
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, true, false,
/*consume_paren=*/true);
if (keyword == RID_IF)
{
/* Add the condition. */
finish_if_stmt_cond (condition, statement);
/* Parse the then-clause. */
cp_parser_implicitly_scoped_statement (parser);
finish_then_clause (statement);
/* If the next token is `else', parse the else-clause. */
if (cp_lexer_next_token_is_keyword (parser->lexer,
RID_ELSE))
{
/* Consume the `else' keyword. */
cp_lexer_consume_token (parser->lexer);
begin_else_clause (statement);
/* Parse the else-clause. */
cp_parser_implicitly_scoped_statement (parser);
finish_else_clause (statement);
}
/* Now we're all done with the if-statement. */
finish_if_stmt (statement);
}
else
{
bool in_switch_statement_p;
unsigned char in_statement;
/* Add the condition. */
finish_switch_cond (condition, statement);
/* Parse the body of the switch-statement. */
in_switch_statement_p = parser->in_switch_statement_p;
in_statement = parser->in_statement;
parser->in_switch_statement_p = true;
parser->in_statement |= IN_SWITCH_STMT;
cp_parser_implicitly_scoped_statement (parser);
parser->in_switch_statement_p = in_switch_statement_p;
parser->in_statement = in_statement;
/* Now we're all done with the switch-statement. */
finish_switch_stmt (statement);
}
return statement;
}
break;
default:
cp_parser_error (parser, "expected selection-statement");
return error_mark_node;
}
}
/* Parse a condition.
condition:
expression
type-specifier-seq declarator = assignment-expression
GNU Extension:
condition:
type-specifier-seq declarator asm-specification [opt]
attributes [opt] = assignment-expression
Returns the expression that should be tested. */
static tree
cp_parser_condition (cp_parser* parser)
{
cp_decl_specifier_seq type_specifiers;
const char *saved_message;
/* Try the declaration first. */
cp_parser_parse_tentatively (parser);
/* New types are not allowed in the type-specifier-seq for a
condition. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in conditions";
/* Parse the type-specifier-seq. */
cp_parser_type_specifier_seq (parser, /*is_condition==*/true,
&type_specifiers);
/* Restore the saved message. */
parser->type_definition_forbidden_message = saved_message;
/* If all is well, we might be looking at a declaration. */
if (!cp_parser_error_occurred (parser))
{
tree decl;
tree asm_specification;
tree attributes;
cp_declarator *declarator;
tree initializer = NULL_TREE;
/* Parse the declarator. */
declarator = cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
/*ctor_dtor_or_conv_p=*/NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
/* Parse the attributes. */
attributes = cp_parser_attributes_opt (parser);
/* Parse the asm-specification. */
asm_specification = cp_parser_asm_specification_opt (parser);
/* If the next token is not an `=', then we might still be
looking at an expression. For example:
if (A(a).x)
looks like a decl-specifier-seq and a declarator -- but then
there is no `=', so this is an expression. */
cp_parser_require (parser, CPP_EQ, "`='");
/* If we did see an `=', then we are looking at a declaration
for sure. */
if (cp_parser_parse_definitely (parser))
{
tree pushed_scope;
bool non_constant_p;
/* Create the declaration. */
decl = start_decl (declarator, &type_specifiers,
/*initialized_p=*/true,
attributes, /*prefix_attributes=*/NULL_TREE,
&pushed_scope);
/* Parse the assignment-expression. */
initializer
= cp_parser_constant_expression (parser,
/*allow_non_constant_p=*/true,
&non_constant_p);
if (!non_constant_p)
initializer = fold_non_dependent_expr (initializer);
/* Process the initializer. */
cp_finish_decl (decl,
initializer, !non_constant_p,
asm_specification,
LOOKUP_ONLYCONVERTING);
if (pushed_scope)
pop_scope (pushed_scope);
return convert_from_reference (decl);
}
}
/* If we didn't even get past the declarator successfully, we are
definitely not looking at a declaration. */
else
cp_parser_abort_tentative_parse (parser);
/* Otherwise, we are looking at an expression. */
return cp_parser_expression (parser, /*cast_p=*/false);
}
/* APPLE LOCAL begin radar 4631818 */
/* This routine looks for objective-c++'s foreach statement by scanning for-loop
header looking for either 1) 'for (type selector in...)' or 2) 'for (selector in...)'
where selector is already declared in outer scope. If it failed, it undoes the lexical
look-ahead and returns false. If it succeeded, it adds the 'selector' to the statement
list and returns true. At success, lexer points to token following the 'in' keyword.
*/
static bool
cp_parser_parse_foreach_stmt (cp_parser *parser)
{
int decl_spec_declares_class_or_enum;
bool is_cv_qualifier;
tree type_spec;
cp_decl_specifier_seq decl_specs;
tree node;
cp_token *token;
bool is_legit_foreach = false;
cp_declarator *declarator;
/* Exclude class/struct/enum type definition in for-loop header, which is
aparently legal in c++. Otherwise, it causes side-effect (type is enterred
in function's scope) when type is re-parsed. */
token = cp_lexer_peek_token (parser->lexer);
if (cp_parser_token_is_class_key (token) || token->keyword == RID_ENUM)
return false;
cp_parser_parse_tentatively (parser);
clear_decl_specs (&decl_specs);
type_spec
= cp_parser_type_specifier (parser, CP_PARSER_FLAGS_OPTIONAL,
&decl_specs,
/*is_declaration=*/true,
&decl_spec_declares_class_or_enum,
&is_cv_qualifier);
declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
if (declarator == cp_error_declarator)
{
cp_parser_abort_tentative_parse (parser);
return false;
}
token = cp_lexer_peek_token (parser->lexer);
node = token->u.value;
if (node && TREE_CODE (node) == IDENTIFIER_NODE
&& node == ridpointers [(int) RID_IN])
{
enum cpp_ttype nt = cp_lexer_peek_nth_token (parser->lexer, 2)->type;
switch (nt)
{
case CPP_NAME:
case CPP_OPEN_PAREN:
case CPP_MULT:
case CPP_PLUS: case CPP_PLUS_PLUS:
case CPP_MINUS: case CPP_MINUS_MINUS:
case CPP_OPEN_SQUARE:
is_legit_foreach = true;
default:
break;
}
}
if (is_legit_foreach)
{
tree pushed_scope = NULL;
tree decl;
if (type_spec)
{
/* we have: 'for (type selector in...)' */
cp_parser_commit_to_tentative_parse (parser);
decl = start_decl (declarator, &decl_specs,
false /*is_initialized*/,
NULL_TREE /*attributes*/,
NULL_TREE /*prefix_attributes*/,
&pushed_scope);
/* APPLE LOCAL begin radar 5130983 */
if (!decl || decl == error_mark_node)
{
error ("selector is undeclared");
is_legit_foreach = false;
}
else
cp_finish_decl (decl,
NULL_TREE /*initializer*/,
false /*init_const_expr_p=*/,
NULL_TREE /*asm_specification*/,
0 /*flags */);
}
else {
tree statement;
/* we have: 'for (selector in...)' */
/* Parse it as an expression. */
cp_parser_abort_tentative_parse (parser);
statement = cp_parser_expression (parser, /*cast_p=*/false);
add_stmt (statement);
}
/* APPLE LOCAL end radar 5130983 */
/* Consume the 'in' token */
cp_lexer_consume_token (parser->lexer);
}
else
cp_parser_abort_tentative_parse (parser);
return is_legit_foreach;
}
/* APPLE LOCAL end radar 4631818 */
/* APPLE LOCAL begin mainline */
/* We check for a ) immediately followed by ; with no whitespacing
between. This is used to issue a warning for:
while (...);
and:
for (...);
as the semicolon is probably extraneous.
On parse errors, the next token might not be a ), so do nothing in
that case. */
static void
check_empty_body (cp_parser* parser, const char* type)
{
cp_token *token;
cp_token *close_paren;
expanded_location close_loc;
expanded_location semi_loc;
close_paren = cp_lexer_peek_token (parser->lexer);
if (close_paren->type != CPP_CLOSE_PAREN)
return;
close_loc = expand_location (close_paren->location);
token = cp_lexer_peek_nth_token (parser->lexer, 2);
if (token->type != CPP_SEMICOLON
|| (token->flags & PREV_WHITE))
return;
semi_loc = expand_location (token->location);
if (close_loc.line == semi_loc.line
#ifdef USE_MAPPED_LOCATION
&& close_loc.column+1 == semi_loc.column
#endif
)
warning (OPT_Wempty_body,
"suggest a space before %<;%> or explicit braces around empty "
"body in %<%s%> statement",
type);
}
/* APPLE LOCAL end mainline */
/* Parse an iteration-statement.
iteration-statement:
while ( condition ) statement
do statement while ( expression ) ;
for ( for-init-statement condition [opt] ; expression [opt] )
statement
APPLE LOCAL begin for-fsf-4_4 3274130 5295549
GNU extension:
while attributes [opt] ( condition ) statement
do attributes [opt] statement while ( expression ) ;
for attributes [opt]
( for-init-statement condition [opt] ; expression [opt] )
statement
APPLE LOCAL end for-fsf-4_4 3274130 5295549
Returns the new WHILE_STMT, DO_STMT, or FOR_STMT. */
static tree
cp_parser_iteration_statement (cp_parser* parser)
{
cp_token *token;
enum rid keyword;
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
tree statement, attributes;
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
unsigned char in_statement;
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
/* Get the keyword at the start of the loop. */
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
token = cp_parser_require (parser, CPP_KEYWORD, "iteration-statement");
if (!token)
return error_mark_node;
/* Remember whether or not we are already within an iteration
statement. */
in_statement = parser->in_statement;
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
/* Parse the attributes, if any. */
attributes = cp_parser_attributes_opt (parser);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
/* See what kind of keyword it is. */
keyword = token->keyword;
switch (keyword)
{
case RID_WHILE:
{
tree condition;
/* Begin the while-statement. */
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
statement = begin_while_stmt (attributes);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
/* Look for the `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Parse the condition. */
condition = cp_parser_condition (parser);
finish_while_stmt_cond (condition, statement);
/* APPLE LOCAL mainline */
check_empty_body (parser, "while");
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Parse the dependent statement. */
parser->in_statement = IN_ITERATION_STMT;
cp_parser_already_scoped_statement (parser);
parser->in_statement = in_statement;
/* We're done with the while-statement. */
finish_while_stmt (statement);
}
break;
case RID_DO:
{
tree expression;
/* Begin the do-statement. */
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
statement = begin_do_stmt (attributes);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
/* Parse the body of the do-statement. */
parser->in_statement = IN_ITERATION_STMT;
cp_parser_implicitly_scoped_statement (parser);
parser->in_statement = in_statement;
finish_do_body (statement);
/* Look for the `while' keyword. */
cp_parser_require_keyword (parser, RID_WHILE, "`while'");
/* Look for the `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Parse the expression. */
expression = cp_parser_expression (parser, /*cast_p=*/false);
/* We're done with the do-statement. */
finish_do_stmt (expression, statement);
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Look for the `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
}
break;
case RID_FOR:
{
tree condition = NULL_TREE;
tree expression = NULL_TREE;
/* Begin the for-statement. */
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
statement = begin_for_stmt (attributes);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
/* Look for the `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* APPLE LOCAL begin radar 4631818 */
if (c_dialect_objc ()
&& cp_parser_parse_foreach_stmt (parser))
{
objc_foreach_stmt (parser, statement);
break;
}
/* APPLE LOCAL end radar 4631818 */
/* Parse the initialization. */
cp_parser_for_init_statement (parser);
finish_for_init_stmt (statement);
/* If there's a condition, process it. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
condition = cp_parser_condition (parser);
finish_for_cond (condition, statement);
/* Look for the `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
/* If there's an expression, process it. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_PAREN))
expression = cp_parser_expression (parser, /*cast_p=*/false);
finish_for_expr (expression, statement);
/* APPLE LOCAL mainline */
check_empty_body (parser, "for");
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Parse the body of the for-statement. */
parser->in_statement = IN_ITERATION_STMT;
cp_parser_already_scoped_statement (parser);
parser->in_statement = in_statement;
/* We're done with the for-statement. */
finish_for_stmt (statement);
}
break;
default:
cp_parser_error (parser, "expected iteration-statement");
statement = error_mark_node;
break;
}
return statement;
}
/* Parse a for-init-statement.
for-init-statement:
expression-statement
simple-declaration */
static void
cp_parser_for_init_statement (cp_parser* parser)
{
/* If the next token is a `;', then we have an empty
expression-statement. Grammatically, this is also a
simple-declaration, but an invalid one, because it does not
declare anything. Therefore, if we did not handle this case
specially, we would issue an error message about an invalid
declaration. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
{
/* We're going to speculatively look for a declaration, falling back
to an expression, if necessary. */
cp_parser_parse_tentatively (parser);
/* Parse the declaration. */
cp_parser_simple_declaration (parser,
/*function_definition_allowed_p=*/false);
/* If the tentative parse failed, then we shall need to look for an
expression-statement. */
if (cp_parser_parse_definitely (parser))
return;
}
cp_parser_expression_statement (parser, false);
}
/* Parse a jump-statement.
jump-statement:
break ;
continue ;
return expression [opt] ;
goto identifier ;
GNU extension:
jump-statement:
goto * expression ;
Returns the new BREAK_STMT, CONTINUE_STMT, RETURN_EXPR, or GOTO_EXPR. */
static tree
cp_parser_jump_statement (cp_parser* parser)
{
tree statement = error_mark_node;
cp_token *token;
enum rid keyword;
/* Peek at the next token. */
token = cp_parser_require (parser, CPP_KEYWORD, "jump-statement");
if (!token)
return error_mark_node;
/* See what kind of keyword it is. */
keyword = token->keyword;
switch (keyword)
{
case RID_BREAK:
switch (parser->in_statement)
{
case 0:
error ("break statement not within loop or switch");
break;
default:
gcc_assert ((parser->in_statement & IN_SWITCH_STMT)
|| parser->in_statement == IN_ITERATION_STMT);
statement = finish_break_stmt ();
break;
case IN_OMP_BLOCK:
error ("invalid exit from OpenMP structured block");
break;
case IN_OMP_FOR:
error ("break statement used with OpenMP for loop");
break;
}
cp_parser_require (parser, CPP_SEMICOLON, "%<;%>");
break;
case RID_CONTINUE:
switch (parser->in_statement & ~IN_SWITCH_STMT)
{
case 0:
error ("continue statement not within a loop");
break;
case IN_ITERATION_STMT:
case IN_OMP_FOR:
statement = finish_continue_stmt ();
break;
case IN_OMP_BLOCK:
error ("invalid exit from OpenMP structured block");
break;
default:
gcc_unreachable ();
}
cp_parser_require (parser, CPP_SEMICOLON, "%<;%>");
break;
case RID_RETURN:
{
tree expr;
/* If the next token is a `;', then there is no
expression. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
expr = cp_parser_expression (parser, /*cast_p=*/false);
else
expr = NULL_TREE;
/* Build the return-statement. */
statement = finish_return_stmt (expr);
/* Look for the final `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "%<;%>");
}
break;
case RID_GOTO:
/* APPLE LOCAL begin blocks 6040305 (cb) */
if (cur_block)
error ("goto not allowed in block literal");
/* APPLE LOCAL end blocks 6040305 (cb) */
/* Create the goto-statement. */
if (cp_lexer_next_token_is (parser->lexer, CPP_MULT))
{
/* Issue a warning about this use of a GNU extension. */
if (pedantic)
pedwarn ("ISO C++ forbids computed gotos");
/* Consume the '*' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the dependent expression. */
finish_goto_stmt (cp_parser_expression (parser, /*cast_p=*/false));
}
else
finish_goto_stmt (cp_parser_identifier (parser));
/* Look for the final `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "%<;%>");
break;
default:
cp_parser_error (parser, "expected jump-statement");
break;
}
return statement;
}
/* Parse a declaration-statement.
declaration-statement:
block-declaration */
static void
cp_parser_declaration_statement (cp_parser* parser)
{
void *p;
/* Get the high-water mark for the DECLARATOR_OBSTACK. */
p = obstack_alloc (&declarator_obstack, 0);
/* Parse the block-declaration. */
cp_parser_block_declaration (parser, /*statement_p=*/true);
/* Free any declarators allocated. */
obstack_free (&declarator_obstack, p);
/* Finish off the statement. */
finish_stmt ();
}
/* Some dependent statements (like `if (cond) statement'), are
implicitly in their own scope. In other words, if the statement is
a single statement (as opposed to a compound-statement), it is
none-the-less treated as if it were enclosed in braces. Any
declarations appearing in the dependent statement are out of scope
after control passes that point. This function parses a statement,
but ensures that is in its own scope, even if it is not a
compound-statement.
Returns the new statement. */
static tree
cp_parser_implicitly_scoped_statement (cp_parser* parser)
{
tree statement;
/* Mark if () ; with a special NOP_EXPR. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
{
cp_lexer_consume_token (parser->lexer);
statement = add_stmt (build_empty_stmt ());
}
/* if a compound is opened, we simply parse the statement directly. */
else if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
/* APPLE LOCAL radar 5982990 */
statement = cp_parser_compound_statement (parser, NULL, false, false);
/* If the token is not a `{', then we must take special action. */
else
{
/* Create a compound-statement. */
statement = begin_compound_stmt (0);
/* Parse the dependent-statement. */
cp_parser_statement (parser, NULL_TREE, false);
/* Finish the dummy compound-statement. */
finish_compound_stmt (statement);
}
/* Return the statement. */
return statement;
}
/* For some dependent statements (like `while (cond) statement'), we
have already created a scope. Therefore, even if the dependent
statement is a compound-statement, we do not want to create another
scope. */
static void
cp_parser_already_scoped_statement (cp_parser* parser)
{
/* If the token is a `{', then we must take special action. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_BRACE))
cp_parser_statement (parser, NULL_TREE, false);
else
{
/* Avoid calling cp_parser_compound_statement, so that we
don't create a new scope. Do everything else by hand. */
cp_parser_require (parser, CPP_OPEN_BRACE, "`{'");
cp_parser_statement_seq_opt (parser, NULL_TREE);
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
}
}
/* Declarations [gram.dcl.dcl] */
/* Parse an optional declaration-sequence.
declaration-seq:
declaration
declaration-seq declaration */
static void
cp_parser_declaration_seq_opt (cp_parser* parser)
{
while (true)
{
cp_token *token;
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_CLOSE_BRACE
|| token->type == CPP_EOF
|| token->type == CPP_PRAGMA_EOL)
break;
if (token->type == CPP_SEMICOLON)
{
/* A declaration consisting of a single semicolon is
invalid. Allow it unless we're being pedantic. */
cp_lexer_consume_token (parser->lexer);
if (pedantic && !in_system_header)
pedwarn ("extra %<;%>");
continue;
}
/* If we're entering or exiting a region that's implicitly
extern "C", modify the lang context appropriately. */
if (!parser->implicit_extern_c && token->implicit_extern_c)
{
push_lang_context (lang_name_c);
parser->implicit_extern_c = true;
}
else if (parser->implicit_extern_c && !token->implicit_extern_c)
{
pop_lang_context ();
parser->implicit_extern_c = false;
}
if (token->type == CPP_PRAGMA)
{
/* A top-level declaration can consist solely of a #pragma.
A nested declaration cannot, so this is done here and not
in cp_parser_declaration. (A #pragma at block scope is
handled in cp_parser_statement.) */
cp_parser_pragma (parser, pragma_external);
continue;
}
/* Parse the declaration itself. */
cp_parser_declaration (parser);
}
}
/* APPLE LOCAL begin radar 4548636 */
static bool
/* This routine is called when lexer has seen an '__attribute__' token.
It does look-ahead to see of __attribute__ list declaration is followed
by an objective-c at_keyword. If so, it returns true. This is to
disambiguate use of attribute before types and before objective-c's
@interface declaration. */
objc_attr_follwed_by_at_keyword (cp_parser* parser)
{
cp_token token1;
tree attributes = NULL_TREE;
cp_lexer_save_tokens (parser->lexer);
cp_parser_objc_maybe_attributes (parser, &attributes);
gcc_assert (attributes);
token1 = *cp_lexer_peek_token (parser->lexer);
cp_lexer_rollback_tokens (parser->lexer);
return OBJC_IS_AT_KEYWORD (token1.keyword);
}
/* APPLE LOCAL end radar 4548636 */
/* Parse a declaration.
declaration:
block-declaration
function-definition
template-declaration
explicit-instantiation
explicit-specialization
linkage-specification
namespace-definition
GNU extension:
declaration:
__extension__ declaration */
static void
cp_parser_declaration (cp_parser* parser)
{
cp_token token1;
cp_token token2;
int saved_pedantic;
void *p;
/* Check for the `__extension__' keyword. */
if (cp_parser_extension_opt (parser, &saved_pedantic))
{
/* Parse the qualified declaration. */
cp_parser_declaration (parser);
/* Restore the PEDANTIC flag. */
pedantic = saved_pedantic;
return;
}
/* Try to figure out what kind of declaration is present. */
token1 = *cp_lexer_peek_token (parser->lexer);
if (token1.type != CPP_EOF)
token2 = *cp_lexer_peek_nth_token (parser->lexer, 2);
else
{
token2.type = CPP_EOF;
token2.keyword = RID_MAX;
}
/* Get the high-water mark for the DECLARATOR_OBSTACK. */
p = obstack_alloc (&declarator_obstack, 0);
/* If the next token is `extern' and the following token is a string
literal, then we have a linkage specification. */
if (token1.keyword == RID_EXTERN
&& cp_parser_is_string_literal (&token2))
cp_parser_linkage_specification (parser);
/* If the next token is `template', then we have either a template
declaration, an explicit instantiation, or an explicit
specialization. */
else if (token1.keyword == RID_TEMPLATE)
{
/* `template <>' indicates a template specialization. */
if (token2.type == CPP_LESS
&& cp_lexer_peek_nth_token (parser->lexer, 3)->type == CPP_GREATER)
cp_parser_explicit_specialization (parser);
/* `template <' indicates a template declaration. */
else if (token2.type == CPP_LESS)
cp_parser_template_declaration (parser, /*member_p=*/false);
/* Anything else must be an explicit instantiation. */
else
cp_parser_explicit_instantiation (parser);
}
/* If the next token is `export', then we have a template
declaration. */
else if (token1.keyword == RID_EXPORT)
cp_parser_template_declaration (parser, /*member_p=*/false);
/* If the next token is `extern', 'static' or 'inline' and the one
after that is `template', we have a GNU extended explicit
instantiation directive. */
else if (cp_parser_allow_gnu_extensions_p (parser)
&& (token1.keyword == RID_EXTERN
|| token1.keyword == RID_STATIC
|| token1.keyword == RID_INLINE)
&& token2.keyword == RID_TEMPLATE)
cp_parser_explicit_instantiation (parser);
/* If the next token is `namespace', check for a named or unnamed
namespace definition. */
else if (token1.keyword == RID_NAMESPACE
&& (/* A named namespace definition. */
(token2.type == CPP_NAME
&& (cp_lexer_peek_nth_token (parser->lexer, 3)->type
!= CPP_EQ))
/* An unnamed namespace definition. */
|| token2.type == CPP_OPEN_BRACE
|| token2.keyword == RID_ATTRIBUTE))
cp_parser_namespace_definition (parser);
/* Objective-C++ declaration/definition. */
/* APPLE LOCAL begin radar 4548636 */
else if (c_dialect_objc ()
&& (OBJC_IS_AT_KEYWORD (token1.keyword)
|| (token1.keyword == RID_ATTRIBUTE
&& objc_attr_follwed_by_at_keyword (parser))))
/* APPLE LOCAL end radar 4548636 */
cp_parser_objc_declaration (parser);
/* We must have either a block declaration or a function
definition. */
else
/* Try to parse a block-declaration, or a function-definition. */
cp_parser_block_declaration (parser, /*statement_p=*/false);
/* Free any declarators allocated. */
obstack_free (&declarator_obstack, p);
}
/* Parse a block-declaration.
block-declaration:
simple-declaration
asm-definition
namespace-alias-definition
using-declaration
using-directive
GNU Extension:
block-declaration:
__extension__ block-declaration
label-declaration
If STATEMENT_P is TRUE, then this block-declaration is occurring as
part of a declaration-statement. */
static void
cp_parser_block_declaration (cp_parser *parser,
bool statement_p)
{
cp_token *token1;
int saved_pedantic;
/* Check for the `__extension__' keyword. */
if (cp_parser_extension_opt (parser, &saved_pedantic))
{
/* Parse the qualified declaration. */
cp_parser_block_declaration (parser, statement_p);
/* Restore the PEDANTIC flag. */
pedantic = saved_pedantic;
return;
}
/* Peek at the next token to figure out which kind of declaration is
present. */
token1 = cp_lexer_peek_token (parser->lexer);
/* If the next keyword is `asm', we have an asm-definition. */
if (token1->keyword == RID_ASM)
{
if (statement_p)
cp_parser_commit_to_tentative_parse (parser);
/* APPLE LOCAL CW asm blocks */
cp_parser_asm_definition (parser, statement_p);
}
/* If the next keyword is `namespace', we have a
namespace-alias-definition. */
else if (token1->keyword == RID_NAMESPACE)
cp_parser_namespace_alias_definition (parser);
/* If the next keyword is `using', we have either a
using-declaration or a using-directive. */
else if (token1->keyword == RID_USING)
{
cp_token *token2;
if (statement_p)
cp_parser_commit_to_tentative_parse (parser);
/* If the token after `using' is `namespace', then we have a
using-directive. */
token2 = cp_lexer_peek_nth_token (parser->lexer, 2);
if (token2->keyword == RID_NAMESPACE)
cp_parser_using_directive (parser);
/* Otherwise, it's a using-declaration. */
else
cp_parser_using_declaration (parser,
/*access_declaration_p=*/false);
}
/* If the next keyword is `__label__' we have a label declaration. */
else if (token1->keyword == RID_LABEL)
{
if (statement_p)
cp_parser_commit_to_tentative_parse (parser);
cp_parser_label_declaration (parser);
}
/* Anything else must be a simple-declaration. */
else
cp_parser_simple_declaration (parser, !statement_p);
}
/* Parse a simple-declaration.
simple-declaration:
decl-specifier-seq [opt] init-declarator-list [opt] ;
init-declarator-list:
init-declarator
init-declarator-list , init-declarator
If FUNCTION_DEFINITION_ALLOWED_P is TRUE, then we also recognize a
function-definition as a simple-declaration. */
static void
cp_parser_simple_declaration (cp_parser* parser,
bool function_definition_allowed_p)
{
cp_decl_specifier_seq decl_specifiers;
int declares_class_or_enum;
bool saw_declarator;
/* Defer access checks until we know what is being declared; the
checks for names appearing in the decl-specifier-seq should be
done as if we were in the scope of the thing being declared. */
push_deferring_access_checks (dk_deferred);
/* Parse the decl-specifier-seq. We have to keep track of whether
or not the decl-specifier-seq declares a named class or
enumeration type, since that is the only case in which the
init-declarator-list is allowed to be empty.
[dcl.dcl]
In a simple-declaration, the optional init-declarator-list can be
omitted only when declaring a class or enumeration, that is when
the decl-specifier-seq contains either a class-specifier, an
elaborated-type-specifier, or an enum-specifier. */
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_OPTIONAL,
&decl_specifiers,
&declares_class_or_enum);
/* We no longer need to defer access checks. */
stop_deferring_access_checks ();
/* In a block scope, a valid declaration must always have a
decl-specifier-seq. By not trying to parse declarators, we can
resolve the declaration/expression ambiguity more quickly. */
if (!function_definition_allowed_p
&& !decl_specifiers.any_specifiers_p)
{
/* APPLE LOCAL begin CW asm blocks */
/* We might have seen an asm opcode, and it's time to switch to
asm instruction handling. */
if (flag_iasm_blocks && iasm_state >= iasm_decls)
return;
/* APPLE LOCAL end CW asm blocks */
cp_parser_error (parser, "expected declaration");
goto done;
}
/* If the next two tokens are both identifiers, the code is
erroneous. The usual cause of this situation is code like:
T t;
where "T" should name a type -- but does not. */
if (!decl_specifiers.type
&& cp_parser_parse_and_diagnose_invalid_type_name (parser))
{
/* If parsing tentatively, we should commit; we really are
looking at a declaration. */
cp_parser_commit_to_tentative_parse (parser);
/* Give up. */
goto done;
}
/* If we have seen at least one decl-specifier, and the next token
is not a parenthesis, then we must be looking at a declaration.
(After "int (" we might be looking at a functional cast.) */
if (decl_specifiers.any_specifiers_p
&& cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_PAREN))
cp_parser_commit_to_tentative_parse (parser);
/* Keep going until we hit the `;' at the end of the simple
declaration. */
saw_declarator = false;
while (cp_lexer_next_token_is_not (parser->lexer,
CPP_SEMICOLON))
{
cp_token *token;
bool function_definition_p;
tree decl;
if (saw_declarator)
{
/* If we are processing next declarator, coma is expected */
token = cp_lexer_peek_token (parser->lexer);
gcc_assert (token->type == CPP_COMMA);
cp_lexer_consume_token (parser->lexer);
}
else
saw_declarator = true;
/* Parse the init-declarator. */
decl = cp_parser_init_declarator (parser, &decl_specifiers,
/*checks=*/NULL,
function_definition_allowed_p,
/*member_p=*/false,
declares_class_or_enum,
&function_definition_p);
/* If an error occurred while parsing tentatively, exit quickly.
(That usually happens when in the body of a function; each
statement is treated as a declaration-statement until proven
otherwise.) */
if (cp_parser_error_occurred (parser))
goto done;
/* Handle function definitions specially. */
if (function_definition_p)
{
/* If the next token is a `,', then we are probably
processing something like:
void f() {}, *p;
which is erroneous. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
error ("mixing declarations and function-definitions is forbidden");
/* Otherwise, we're done with the list of declarators. */
else
{
pop_deferring_access_checks ();
return;
}
}
/* The next token should be either a `,' or a `;'. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's a `,', there are more declarators to come. */
if (token->type == CPP_COMMA)
/* will be consumed next time around */;
/* If it's a `;', we are done. */
else if (token->type == CPP_SEMICOLON)
break;
/* Anything else is an error. */
else
{
/* If we have already issued an error message we don't need
to issue another one. */
if (decl != error_mark_node
|| cp_parser_uncommitted_to_tentative_parse_p (parser))
cp_parser_error (parser, "expected %<,%> or %<;%>");
/* Skip tokens until we reach the end of the statement. */
cp_parser_skip_to_end_of_statement (parser);
/* If the next token is now a `;', consume it. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
cp_lexer_consume_token (parser->lexer);
goto done;
}
/* After the first time around, a function-definition is not
allowed -- even if it was OK at first. For example:
int i, f() {}
is not valid. */
function_definition_allowed_p = false;
}
/* Issue an error message if no declarators are present, and the
decl-specifier-seq does not itself declare a class or
enumeration. */
if (!saw_declarator)
{
if (cp_parser_declares_only_class_p (parser))
shadow_tag (&decl_specifiers);
/* Perform any deferred access checks. */
perform_deferred_access_checks ();
}
/* Consume the `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
/* APPLE LOCAL begin CW asm blocks */
if (flag_iasm_blocks)
iasm_in_decl = false;
/* APPLE LOCAL end CW asm blocks */
done:
pop_deferring_access_checks ();
}
/* Parse a decl-specifier-seq.
decl-specifier-seq:
decl-specifier-seq [opt] decl-specifier
decl-specifier:
storage-class-specifier
type-specifier
function-specifier
friend
typedef
GNU Extension:
decl-specifier:
attributes
Set *DECL_SPECS to a representation of the decl-specifier-seq.
The parser flags FLAGS is used to control type-specifier parsing.
*DECLARES_CLASS_OR_ENUM is set to the bitwise or of the following
flags:
1: one of the decl-specifiers is an elaborated-type-specifier
(i.e., a type declaration)
2: one of the decl-specifiers is an enum-specifier or a
class-specifier (i.e., a type definition)
*/
static void
cp_parser_decl_specifier_seq (cp_parser* parser,
cp_parser_flags flags,
cp_decl_specifier_seq *decl_specs,
int* declares_class_or_enum)
{
bool constructor_possible_p = !parser->in_declarator_p;
/* Clear DECL_SPECS. */
clear_decl_specs (decl_specs);
/* Assume no class or enumeration type is declared. */
*declares_class_or_enum = 0;
/* Keep reading specifiers until there are no more to read. */
while (true)
{
bool constructor_p;
bool found_decl_spec;
cp_token *token;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Handle attributes. */
if (token->keyword == RID_ATTRIBUTE)
{
/* Parse the attributes. */
decl_specs->attributes
= chainon (decl_specs->attributes,
cp_parser_attributes_opt (parser));
continue;
}
/* Assume we will find a decl-specifier keyword. */
found_decl_spec = true;
/* If the next token is an appropriate keyword, we can simply
add it to the list. */
switch (token->keyword)
{
/* decl-specifier:
friend */
case RID_FRIEND:
if (!at_class_scope_p ())
{
error ("%<friend%> used outside of class");
cp_lexer_purge_token (parser->lexer);
}
else
{
++decl_specs->specs[(int) ds_friend];
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
}
break;
/* function-specifier:
inline
virtual
explicit */
case RID_INLINE:
case RID_VIRTUAL:
case RID_EXPLICIT:
cp_parser_function_specifier_opt (parser, decl_specs);
break;
/* decl-specifier:
typedef */
case RID_TYPEDEF:
++decl_specs->specs[(int) ds_typedef];
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
/* A constructor declarator cannot appear in a typedef. */
constructor_possible_p = false;
/* The "typedef" keyword can only occur in a declaration; we
may as well commit at this point. */
cp_parser_commit_to_tentative_parse (parser);
if (decl_specs->storage_class != sc_none)
decl_specs->conflicting_specifiers_p = true;
break;
/* storage-class-specifier:
auto
register
static
extern
mutable
GNU Extension:
thread */
case RID_AUTO:
case RID_REGISTER:
case RID_STATIC:
case RID_EXTERN:
case RID_MUTABLE:
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
cp_parser_set_storage_class (parser, decl_specs, token->keyword);
break;
case RID_THREAD:
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
++decl_specs->specs[(int) ds_thread];
break;
/* APPLE LOCAL begin CW asm blocks */
/* If we ever get here, we must be in CW asm mode. */
case RID_ASM:
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
++decl_specs->specs[(int) ds_iasm_asm];
break;
/* APPLE LOCAL end CW asm blocks */
default:
/* We did not yet find a decl-specifier yet. */
found_decl_spec = false;
break;
}
/* Constructors are a special case. The `S' in `S()' is not a
decl-specifier; it is the beginning of the declarator. */
constructor_p
= (!found_decl_spec
&& constructor_possible_p
&& (cp_parser_constructor_declarator_p
(parser, decl_specs->specs[(int) ds_friend] != 0)));
/* If we don't have a DECL_SPEC yet, then we must be looking at
a type-specifier. */
if (!found_decl_spec && !constructor_p)
{
int decl_spec_declares_class_or_enum;
bool is_cv_qualifier;
tree type_spec;
type_spec
= cp_parser_type_specifier (parser, flags,
decl_specs,
/*is_declaration=*/true,
&decl_spec_declares_class_or_enum,
&is_cv_qualifier);
*declares_class_or_enum |= decl_spec_declares_class_or_enum;
/* If this type-specifier referenced a user-defined type
(a typedef, class-name, etc.), then we can't allow any
more such type-specifiers henceforth.
[dcl.spec]
The longest sequence of decl-specifiers that could
possibly be a type name is taken as the
decl-specifier-seq of a declaration. The sequence shall
be self-consistent as described below.
[dcl.type]
As a general rule, at most one type-specifier is allowed
in the complete decl-specifier-seq of a declaration. The
only exceptions are the following:
-- const or volatile can be combined with any other
type-specifier.
-- signed or unsigned can be combined with char, long,
short, or int.
-- ..
Example:
typedef char* Pc;
void g (const int Pc);
Here, Pc is *not* part of the decl-specifier seq; it's
the declarator. Therefore, once we see a type-specifier
(other than a cv-qualifier), we forbid any additional
user-defined types. We *do* still allow things like `int
int' to be considered a decl-specifier-seq, and issue the
error message later. */
if (type_spec && !is_cv_qualifier)
flags |= CP_PARSER_FLAGS_NO_USER_DEFINED_TYPES;
/* A constructor declarator cannot follow a type-specifier. */
if (type_spec)
{
constructor_possible_p = false;
found_decl_spec = true;
}
}
/* If we still do not have a DECL_SPEC, then there are no more
decl-specifiers. */
if (!found_decl_spec)
break;
decl_specs->any_specifiers_p = true;
/* After we see one decl-specifier, further decl-specifiers are
always optional. */
flags |= CP_PARSER_FLAGS_OPTIONAL;
}
cp_parser_check_decl_spec (decl_specs);
/* Don't allow a friend specifier with a class definition. */
if (decl_specs->specs[(int) ds_friend] != 0
&& (*declares_class_or_enum & 2))
error ("class definition may not be declared a friend");
}
/* Parse an (optional) storage-class-specifier.
storage-class-specifier:
auto
register
static
extern
mutable
GNU Extension:
storage-class-specifier:
thread
Returns an IDENTIFIER_NODE corresponding to the keyword used. */
static tree
cp_parser_storage_class_specifier_opt (cp_parser* parser)
{
switch (cp_lexer_peek_token (parser->lexer)->keyword)
{
case RID_AUTO:
case RID_REGISTER:
case RID_STATIC:
case RID_EXTERN:
case RID_MUTABLE:
case RID_THREAD:
/* APPLE LOCAL begin CW asm blocks */
/* If we ever get here, we must be in CW asm mode. */
case RID_ASM:
/* APPLE LOCAL end CW asm blocks */
/* Consume the token. */
return cp_lexer_consume_token (parser->lexer)->u.value;
default:
return NULL_TREE;
}
}
/* Parse an (optional) function-specifier.
function-specifier:
inline
virtual
explicit
Returns an IDENTIFIER_NODE corresponding to the keyword used.
Updates DECL_SPECS, if it is non-NULL. */
static tree
cp_parser_function_specifier_opt (cp_parser* parser,
cp_decl_specifier_seq *decl_specs)
{
switch (cp_lexer_peek_token (parser->lexer)->keyword)
{
case RID_INLINE:
if (decl_specs)
++decl_specs->specs[(int) ds_inline];
break;
case RID_VIRTUAL:
/* 14.5.2.3 [temp.mem]
A member function template shall not be virtual. */
if (PROCESSING_REAL_TEMPLATE_DECL_P ())
error ("templates may not be %<virtual%>");
else if (decl_specs)
++decl_specs->specs[(int) ds_virtual];
break;
case RID_EXPLICIT:
if (decl_specs)
++decl_specs->specs[(int) ds_explicit];
break;
default:
return NULL_TREE;
}
/* Consume the token. */
return cp_lexer_consume_token (parser->lexer)->u.value;
}
/* Parse a linkage-specification.
linkage-specification:
extern string-literal { declaration-seq [opt] }
extern string-literal declaration */
static void
cp_parser_linkage_specification (cp_parser* parser)
{
tree linkage;
/* Look for the `extern' keyword. */
cp_parser_require_keyword (parser, RID_EXTERN, "`extern'");
/* Look for the string-literal. */
linkage = cp_parser_string_literal (parser, false, false);
/* Transform the literal into an identifier. If the literal is a
wide-character string, or contains embedded NULs, then we can't
handle it as the user wants. */
if (strlen (TREE_STRING_POINTER (linkage))
!= (size_t) (TREE_STRING_LENGTH (linkage) - 1))
{
cp_parser_error (parser, "invalid linkage-specification");
/* Assume C++ linkage. */
linkage = lang_name_cplusplus;
}
else
linkage = get_identifier (TREE_STRING_POINTER (linkage));
/* We're now using the new linkage. */
push_lang_context (linkage);
/* If the next token is a `{', then we're using the first
production. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
{
/* Consume the `{' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the declarations. */
cp_parser_declaration_seq_opt (parser);
/* Look for the closing `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
}
/* Otherwise, there's just one declaration. */
else
{
bool saved_in_unbraced_linkage_specification_p;
saved_in_unbraced_linkage_specification_p
= parser->in_unbraced_linkage_specification_p;
parser->in_unbraced_linkage_specification_p = true;
cp_parser_declaration (parser);
parser->in_unbraced_linkage_specification_p
= saved_in_unbraced_linkage_specification_p;
}
/* We're done with the linkage-specification. */
pop_lang_context ();
}
/* Special member functions [gram.special] */
/* Parse a conversion-function-id.
conversion-function-id:
operator conversion-type-id
Returns an IDENTIFIER_NODE representing the operator. */
static tree
cp_parser_conversion_function_id (cp_parser* parser)
{
tree type;
tree saved_scope;
tree saved_qualifying_scope;
tree saved_object_scope;
tree pushed_scope = NULL_TREE;
/* Look for the `operator' token. */
if (!cp_parser_require_keyword (parser, RID_OPERATOR, "`operator'"))
return error_mark_node;
/* When we parse the conversion-type-id, the current scope will be
reset. However, we need that information in able to look up the
conversion function later, so we save it here. */
saved_scope = parser->scope;
saved_qualifying_scope = parser->qualifying_scope;
saved_object_scope = parser->object_scope;
/* We must enter the scope of the class so that the names of
entities declared within the class are available in the
conversion-type-id. For example, consider:
struct S {
typedef int I;
operator I();
};
S::operator I() { ... }
In order to see that `I' is a type-name in the definition, we
must be in the scope of `S'. */
if (saved_scope)
pushed_scope = push_scope (saved_scope);
/* Parse the conversion-type-id. */
type = cp_parser_conversion_type_id (parser);
/* Leave the scope of the class, if any. */
if (pushed_scope)
pop_scope (pushed_scope);
/* Restore the saved scope. */
parser->scope = saved_scope;
parser->qualifying_scope = saved_qualifying_scope;
parser->object_scope = saved_object_scope;
/* If the TYPE is invalid, indicate failure. */
if (type == error_mark_node)
return error_mark_node;
return mangle_conv_op_name_for_type (type);
}
/* Parse a conversion-type-id:
conversion-type-id:
type-specifier-seq conversion-declarator [opt]
Returns the TYPE specified. */
static tree
cp_parser_conversion_type_id (cp_parser* parser)
{
tree attributes;
cp_decl_specifier_seq type_specifiers;
cp_declarator *declarator;
tree type_specified;
/* Parse the attributes. */
attributes = cp_parser_attributes_opt (parser);
/* Parse the type-specifiers. */
cp_parser_type_specifier_seq (parser, /*is_condition=*/false,
&type_specifiers);
/* If that didn't work, stop. */
if (type_specifiers.type == error_mark_node)
return error_mark_node;
/* Parse the conversion-declarator. */
declarator = cp_parser_conversion_declarator_opt (parser);
type_specified = grokdeclarator (declarator, &type_specifiers, TYPENAME,
/*initialized=*/0, &attributes);
if (attributes)
cplus_decl_attributes (&type_specified, attributes, /*flags=*/0);
return type_specified;
}
/* Parse an (optional) conversion-declarator.
conversion-declarator:
ptr-operator conversion-declarator [opt]
*/
static cp_declarator *
cp_parser_conversion_declarator_opt (cp_parser* parser)
{
enum tree_code code;
tree class_type;
cp_cv_quals cv_quals;
/* We don't know if there's a ptr-operator next, or not. */
cp_parser_parse_tentatively (parser);
/* Try the ptr-operator. */
code = cp_parser_ptr_operator (parser, &class_type, &cv_quals);
/* If it worked, look for more conversion-declarators. */
if (cp_parser_parse_definitely (parser))
{
cp_declarator *declarator;
/* Parse another optional declarator. */
declarator = cp_parser_conversion_declarator_opt (parser);
/* Create the representation of the declarator. */
if (class_type)
declarator = make_ptrmem_declarator (cv_quals, class_type,
declarator);
else if (code == INDIRECT_REF)
declarator = make_pointer_declarator (cv_quals, declarator);
else
declarator = make_reference_declarator (cv_quals, declarator);
return declarator;
}
return NULL;
}
/* Parse an (optional) ctor-initializer.
ctor-initializer:
: mem-initializer-list
Returns TRUE iff the ctor-initializer was actually present. */
static bool
cp_parser_ctor_initializer_opt (cp_parser* parser)
{
/* If the next token is not a `:', then there is no
ctor-initializer. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COLON))
{
/* Do default initialization of any bases and members. */
if (DECL_CONSTRUCTOR_P (current_function_decl))
finish_mem_initializers (NULL_TREE);
return false;
}
/* Consume the `:' token. */
cp_lexer_consume_token (parser->lexer);
/* And the mem-initializer-list. */
cp_parser_mem_initializer_list (parser);
return true;
}
/* Parse a mem-initializer-list.
mem-initializer-list:
mem-initializer
mem-initializer , mem-initializer-list */
static void
cp_parser_mem_initializer_list (cp_parser* parser)
{
tree mem_initializer_list = NULL_TREE;
/* Let the semantic analysis code know that we are starting the
mem-initializer-list. */
if (!DECL_CONSTRUCTOR_P (current_function_decl))
error ("only constructors take base initializers");
/* Loop through the list. */
while (true)
{
tree mem_initializer;
/* Parse the mem-initializer. */
mem_initializer = cp_parser_mem_initializer (parser);
/* Add it to the list, unless it was erroneous. */
if (mem_initializer != error_mark_node)
{
TREE_CHAIN (mem_initializer) = mem_initializer_list;
mem_initializer_list = mem_initializer;
}
/* If the next token is not a `,', we're done. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Consume the `,' token. */
cp_lexer_consume_token (parser->lexer);
}
/* Perform semantic analysis. */
if (DECL_CONSTRUCTOR_P (current_function_decl))
finish_mem_initializers (mem_initializer_list);
}
/* Parse a mem-initializer.
mem-initializer:
mem-initializer-id ( expression-list [opt] )
GNU extension:
mem-initializer:
( expression-list [opt] )
Returns a TREE_LIST. The TREE_PURPOSE is the TYPE (for a base
class) or FIELD_DECL (for a non-static data member) to initialize;
the TREE_VALUE is the expression-list. An empty initialization
list is represented by void_list_node. */
static tree
cp_parser_mem_initializer (cp_parser* parser)
{
tree mem_initializer_id;
tree expression_list;
tree member;
/* Find out what is being initialized. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
pedwarn ("anachronistic old-style base class initializer");
mem_initializer_id = NULL_TREE;
}
else
mem_initializer_id = cp_parser_mem_initializer_id (parser);
member = expand_member_init (mem_initializer_id);
if (member && !DECL_P (member))
in_base_initializer = 1;
expression_list
= cp_parser_parenthesized_expression_list (parser, false,
/*cast_p=*/false,
/*non_constant_p=*/NULL);
if (expression_list == error_mark_node)
return error_mark_node;
if (!expression_list)
expression_list = void_type_node;
in_base_initializer = 0;
return member ? build_tree_list (member, expression_list) : error_mark_node;
}
/* Parse a mem-initializer-id.
mem-initializer-id:
:: [opt] nested-name-specifier [opt] class-name
identifier
Returns a TYPE indicating the class to be initializer for the first
production. Returns an IDENTIFIER_NODE indicating the data member
to be initialized for the second production. */
static tree
cp_parser_mem_initializer_id (cp_parser* parser)
{
bool global_scope_p;
bool nested_name_specifier_p;
bool template_p = false;
tree id;
/* `typename' is not allowed in this context ([temp.res]). */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_TYPENAME))
{
error ("keyword %<typename%> not allowed in this context (a qualified "
"member initializer is implicitly a type)");
cp_lexer_consume_token (parser->lexer);
}
/* Look for the optional `::' operator. */
global_scope_p
= (cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false)
!= NULL_TREE);
/* Look for the optional nested-name-specifier. The simplest way to
implement:
[temp.res]
The keyword `typename' is not permitted in a base-specifier or
mem-initializer; in these contexts a qualified name that
depends on a template-parameter is implicitly assumed to be a
type name.
is to assume that we have seen the `typename' keyword at this
point. */
nested_name_specifier_p
= (cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/true,
/*check_dependency_p=*/true,
/*type_p=*/true,
/*is_declaration=*/true)
!= NULL_TREE);
if (nested_name_specifier_p)
template_p = cp_parser_optional_template_keyword (parser);
/* If there is a `::' operator or a nested-name-specifier, then we
are definitely looking for a class-name. */
if (global_scope_p || nested_name_specifier_p)
return cp_parser_class_name (parser,
/*typename_keyword_p=*/true,
/*template_keyword_p=*/template_p,
none_type,
/*check_dependency_p=*/true,
/*class_head_p=*/false,
/*is_declaration=*/true);
/* Otherwise, we could also be looking for an ordinary identifier. */
cp_parser_parse_tentatively (parser);
/* Try a class-name. */
id = cp_parser_class_name (parser,
/*typename_keyword_p=*/true,
/*template_keyword_p=*/false,
none_type,
/*check_dependency_p=*/true,
/*class_head_p=*/false,
/*is_declaration=*/true);
/* If we found one, we're done. */
if (cp_parser_parse_definitely (parser))
return id;
/* Otherwise, look for an ordinary identifier. */
return cp_parser_identifier (parser);
}
/* Overloading [gram.over] */
/* Parse an operator-function-id.
operator-function-id:
operator operator
Returns an IDENTIFIER_NODE for the operator which is a
human-readable spelling of the identifier, e.g., `operator +'. */
static tree
cp_parser_operator_function_id (cp_parser* parser)
{
/* Look for the `operator' keyword. */
if (!cp_parser_require_keyword (parser, RID_OPERATOR, "`operator'"))
return error_mark_node;
/* And then the name of the operator itself. */
return cp_parser_operator (parser);
}
/* Parse an operator.
operator:
new delete new[] delete[] + - * / % ^ & | ~ ! = < >
+= -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= &&
|| ++ -- , ->* -> () []
GNU Extensions:
operator:
<? >? <?= >?=
Returns an IDENTIFIER_NODE for the operator which is a
human-readable spelling of the identifier, e.g., `operator +'. */
static tree
cp_parser_operator (cp_parser* parser)
{
tree id = NULL_TREE;
cp_token *token;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Figure out which operator we have. */
switch (token->type)
{
case CPP_KEYWORD:
{
enum tree_code op;
/* The keyword should be either `new' or `delete'. */
if (token->keyword == RID_NEW)
op = NEW_EXPR;
else if (token->keyword == RID_DELETE)
op = DELETE_EXPR;
else
break;
/* Consume the `new' or `delete' token. */
cp_lexer_consume_token (parser->lexer);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's a `[' token then this is the array variant of the
operator. */
if (token->type == CPP_OPEN_SQUARE)
{
/* Consume the `[' token. */
cp_lexer_consume_token (parser->lexer);
/* Look for the `]' token. */
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
id = ansi_opname (op == NEW_EXPR
? VEC_NEW_EXPR : VEC_DELETE_EXPR);
}
/* Otherwise, we have the non-array variant. */
else
id = ansi_opname (op);
return id;
}
case CPP_PLUS:
id = ansi_opname (PLUS_EXPR);
break;
case CPP_MINUS:
id = ansi_opname (MINUS_EXPR);
break;
case CPP_MULT:
id = ansi_opname (MULT_EXPR);
break;
case CPP_DIV:
id = ansi_opname (TRUNC_DIV_EXPR);
break;
case CPP_MOD:
id = ansi_opname (TRUNC_MOD_EXPR);
break;
case CPP_XOR:
id = ansi_opname (BIT_XOR_EXPR);
break;
case CPP_AND:
id = ansi_opname (BIT_AND_EXPR);
break;
case CPP_OR:
id = ansi_opname (BIT_IOR_EXPR);
break;
case CPP_COMPL:
id = ansi_opname (BIT_NOT_EXPR);
break;
case CPP_NOT:
id = ansi_opname (TRUTH_NOT_EXPR);
break;
case CPP_EQ:
id = ansi_assopname (NOP_EXPR);
break;
case CPP_LESS:
id = ansi_opname (LT_EXPR);
break;
case CPP_GREATER:
id = ansi_opname (GT_EXPR);
break;
case CPP_PLUS_EQ:
id = ansi_assopname (PLUS_EXPR);
break;
case CPP_MINUS_EQ:
id = ansi_assopname (MINUS_EXPR);
break;
case CPP_MULT_EQ:
id = ansi_assopname (MULT_EXPR);
break;
case CPP_DIV_EQ:
id = ansi_assopname (TRUNC_DIV_EXPR);
break;
case CPP_MOD_EQ:
id = ansi_assopname (TRUNC_MOD_EXPR);
break;
case CPP_XOR_EQ:
id = ansi_assopname (BIT_XOR_EXPR);
break;
case CPP_AND_EQ:
id = ansi_assopname (BIT_AND_EXPR);
break;
case CPP_OR_EQ:
id = ansi_assopname (BIT_IOR_EXPR);
break;
case CPP_LSHIFT:
id = ansi_opname (LSHIFT_EXPR);
break;
case CPP_RSHIFT:
id = ansi_opname (RSHIFT_EXPR);
break;
case CPP_LSHIFT_EQ:
id = ansi_assopname (LSHIFT_EXPR);
break;
case CPP_RSHIFT_EQ:
id = ansi_assopname (RSHIFT_EXPR);
break;
case CPP_EQ_EQ:
id = ansi_opname (EQ_EXPR);
break;
case CPP_NOT_EQ:
id = ansi_opname (NE_EXPR);
break;
case CPP_LESS_EQ:
id = ansi_opname (LE_EXPR);
break;
case CPP_GREATER_EQ:
id = ansi_opname (GE_EXPR);
break;
case CPP_AND_AND:
id = ansi_opname (TRUTH_ANDIF_EXPR);
break;
case CPP_OR_OR:
id = ansi_opname (TRUTH_ORIF_EXPR);
break;
case CPP_PLUS_PLUS:
id = ansi_opname (POSTINCREMENT_EXPR);
break;
case CPP_MINUS_MINUS:
id = ansi_opname (PREDECREMENT_EXPR);
break;
case CPP_COMMA:
id = ansi_opname (COMPOUND_EXPR);
break;
case CPP_DEREF_STAR:
id = ansi_opname (MEMBER_REF);
break;
case CPP_DEREF:
id = ansi_opname (COMPONENT_REF);
break;
case CPP_OPEN_PAREN:
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Look for the matching `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
return ansi_opname (CALL_EXPR);
case CPP_OPEN_SQUARE:
/* Consume the `['. */
cp_lexer_consume_token (parser->lexer);
/* Look for the matching `]'. */
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
return ansi_opname (ARRAY_REF);
default:
/* Anything else is an error. */
break;
}
/* If we have selected an identifier, we need to consume the
operator token. */
if (id)
cp_lexer_consume_token (parser->lexer);
/* Otherwise, no valid operator name was present. */
else
{
cp_parser_error (parser, "expected operator");
id = error_mark_node;
}
return id;
}
/* Parse a template-declaration.
template-declaration:
export [opt] template < template-parameter-list > declaration
If MEMBER_P is TRUE, this template-declaration occurs within a
class-specifier.
The grammar rule given by the standard isn't correct. What
is really meant is:
template-declaration:
export [opt] template-parameter-list-seq
decl-specifier-seq [opt] init-declarator [opt] ;
export [opt] template-parameter-list-seq
function-definition
template-parameter-list-seq:
template-parameter-list-seq [opt]
template < template-parameter-list > */
static void
cp_parser_template_declaration (cp_parser* parser, bool member_p)
{
/* Check for `export'. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_EXPORT))
{
/* Consume the `export' token. */
cp_lexer_consume_token (parser->lexer);
/* Warn that we do not support `export'. */
warning (0, "keyword %<export%> not implemented, and will be ignored");
}
cp_parser_template_declaration_after_export (parser, member_p);
}
/* Parse a template-parameter-list.
template-parameter-list:
template-parameter
template-parameter-list , template-parameter
Returns a TREE_LIST. Each node represents a template parameter.
The nodes are connected via their TREE_CHAINs. */
static tree
cp_parser_template_parameter_list (cp_parser* parser)
{
tree parameter_list = NULL_TREE;
begin_template_parm_list ();
while (true)
{
tree parameter;
cp_token *token;
bool is_non_type;
/* Parse the template-parameter. */
parameter = cp_parser_template_parameter (parser, &is_non_type);
/* Add it to the list. */
if (parameter != error_mark_node)
parameter_list = process_template_parm (parameter_list,
parameter,
is_non_type);
else
{
tree err_parm = build_tree_list (parameter, parameter);
TREE_VALUE (err_parm) = error_mark_node;
parameter_list = chainon (parameter_list, err_parm);
}
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's not a `,', we're done. */
if (token->type != CPP_COMMA)
break;
/* Otherwise, consume the `,' token. */
cp_lexer_consume_token (parser->lexer);
}
return end_template_parm_list (parameter_list);
}
/* Parse a template-parameter.
template-parameter:
type-parameter
parameter-declaration
If all goes well, returns a TREE_LIST. The TREE_VALUE represents
the parameter. The TREE_PURPOSE is the default value, if any.
Returns ERROR_MARK_NODE on failure. *IS_NON_TYPE is set to true
iff this parameter is a non-type parameter. */
static tree
cp_parser_template_parameter (cp_parser* parser, bool *is_non_type)
{
cp_token *token;
cp_parameter_declarator *parameter_declarator;
tree parm;
/* Assume it is a type parameter or a template parameter. */
*is_non_type = false;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it is `class' or `template', we have a type-parameter. */
if (token->keyword == RID_TEMPLATE)
return cp_parser_type_parameter (parser);
/* If it is `class' or `typename' we do not know yet whether it is a
type parameter or a non-type parameter. Consider:
template <typename T, typename T::X X> ...
or:
template <class C, class D*> ...
Here, the first parameter is a type parameter, and the second is
a non-type parameter. We can tell by looking at the token after
the identifier -- if it is a `,', `=', or `>' then we have a type
parameter. */
if (token->keyword == RID_TYPENAME || token->keyword == RID_CLASS)
{
/* Peek at the token after `class' or `typename'. */
token = cp_lexer_peek_nth_token (parser->lexer, 2);
/* If it's an identifier, skip it. */
if (token->type == CPP_NAME)
token = cp_lexer_peek_nth_token (parser->lexer, 3);
/* Now, see if the token looks like the end of a template
parameter. */
if (token->type == CPP_COMMA
|| token->type == CPP_EQ
|| token->type == CPP_GREATER)
return cp_parser_type_parameter (parser);
}
/* Otherwise, it is a non-type parameter.
[temp.param]
When parsing a default template-argument for a non-type
template-parameter, the first non-nested `>' is taken as the end
of the template parameter-list rather than a greater-than
operator. */
*is_non_type = true;
parameter_declarator
= cp_parser_parameter_declaration (parser, /*template_parm_p=*/true,
/*parenthesized_p=*/NULL);
parm = grokdeclarator (parameter_declarator->declarator,
¶meter_declarator->decl_specifiers,
PARM, /*initialized=*/0,
/*attrlist=*/NULL);
if (parm == error_mark_node)
return error_mark_node;
return build_tree_list (parameter_declarator->default_argument, parm);
}
/* Parse a type-parameter.
type-parameter:
class identifier [opt]
class identifier [opt] = type-id
typename identifier [opt]
typename identifier [opt] = type-id
template < template-parameter-list > class identifier [opt]
template < template-parameter-list > class identifier [opt]
= id-expression
Returns a TREE_LIST. The TREE_VALUE is itself a TREE_LIST. The
TREE_PURPOSE is the default-argument, if any. The TREE_VALUE is
the declaration of the parameter. */
static tree
cp_parser_type_parameter (cp_parser* parser)
{
cp_token *token;
tree parameter;
/* Look for a keyword to tell us what kind of parameter this is. */
token = cp_parser_require (parser, CPP_KEYWORD,
"`class', `typename', or `template'");
if (!token)
return error_mark_node;
switch (token->keyword)
{
case RID_CLASS:
case RID_TYPENAME:
{
tree identifier;
tree default_argument;
/* If the next token is an identifier, then it names the
parameter. */
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
identifier = cp_parser_identifier (parser);
else
identifier = NULL_TREE;
/* Create the parameter. */
parameter = finish_template_type_parm (class_type_node, identifier);
/* If the next token is an `=', we have a default argument. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EQ))
{
/* Consume the `=' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the default-argument. */
push_deferring_access_checks (dk_no_deferred);
default_argument = cp_parser_type_id (parser);
pop_deferring_access_checks ();
}
else
default_argument = NULL_TREE;
/* Create the combined representation of the parameter and the
default argument. */
parameter = build_tree_list (default_argument, parameter);
}
break;
case RID_TEMPLATE:
{
tree parameter_list;
tree identifier;
tree default_argument;
/* Look for the `<'. */
cp_parser_require (parser, CPP_LESS, "`<'");
/* Parse the template-parameter-list. */
parameter_list = cp_parser_template_parameter_list (parser);
/* Look for the `>'. */
cp_parser_require (parser, CPP_GREATER, "`>'");
/* Look for the `class' keyword. */
cp_parser_require_keyword (parser, RID_CLASS, "`class'");
/* If the next token is an `=', then there is a
default-argument. If the next token is a `>', we are at
the end of the parameter-list. If the next token is a `,',
then we are at the end of this parameter. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_EQ)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_GREATER)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
{
identifier = cp_parser_identifier (parser);
/* Treat invalid names as if the parameter were nameless. */
if (identifier == error_mark_node)
identifier = NULL_TREE;
}
else
identifier = NULL_TREE;
/* Create the template parameter. */
parameter = finish_template_template_parm (class_type_node,
identifier);
/* If the next token is an `=', then there is a
default-argument. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EQ))
{
bool is_template;
/* Consume the `='. */
cp_lexer_consume_token (parser->lexer);
/* Parse the id-expression. */
push_deferring_access_checks (dk_no_deferred);
default_argument
= cp_parser_id_expression (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
/*template_p=*/&is_template,
/*declarator_p=*/false,
/*optional_p=*/false);
if (TREE_CODE (default_argument) == TYPE_DECL)
/* If the id-expression was a template-id that refers to
a template-class, we already have the declaration here,
so no further lookup is needed. */
;
else
/* Look up the name. */
default_argument
= cp_parser_lookup_name (parser, default_argument,
none_type,
/*is_template=*/is_template,
/*is_namespace=*/false,
/*check_dependency=*/true,
/*ambiguous_decls=*/NULL);
/* See if the default argument is valid. */
default_argument
= check_template_template_default_arg (default_argument);
pop_deferring_access_checks ();
}
else
default_argument = NULL_TREE;
/* Create the combined representation of the parameter and the
default argument. */
parameter = build_tree_list (default_argument, parameter);
}
break;
default:
gcc_unreachable ();
break;
}
return parameter;
}
/* Parse a template-id.
template-id:
template-name < template-argument-list [opt] >
If TEMPLATE_KEYWORD_P is TRUE, then we have just seen the
`template' keyword. In this case, a TEMPLATE_ID_EXPR will be
returned. Otherwise, if the template-name names a function, or set
of functions, returns a TEMPLATE_ID_EXPR. If the template-name
names a class, returns a TYPE_DECL for the specialization.
If CHECK_DEPENDENCY_P is FALSE, names are looked up in
uninstantiated templates. */
static tree
cp_parser_template_id (cp_parser *parser,
bool template_keyword_p,
bool check_dependency_p,
bool is_declaration)
{
int i;
tree template;
tree arguments;
tree template_id;
cp_token_position start_of_id = 0;
deferred_access_check *chk;
VEC (deferred_access_check,gc) *access_check;
cp_token *next_token, *next_token_2;
bool is_identifier;
/* If the next token corresponds to a template-id, there is no need
to reparse it. */
next_token = cp_lexer_peek_token (parser->lexer);
if (next_token->type == CPP_TEMPLATE_ID)
{
struct tree_check *check_value;
/* Get the stored value. */
check_value = cp_lexer_consume_token (parser->lexer)->u.tree_check_value;
/* Perform any access checks that were deferred. */
access_check = check_value->checks;
if (access_check)
{
for (i = 0 ;
VEC_iterate (deferred_access_check, access_check, i, chk) ;
++i)
{
perform_or_defer_access_check (chk->binfo,
chk->decl,
chk->diag_decl);
}
}
/* Return the stored value. */
return check_value->value;
}
/* Avoid performing name lookup if there is no possibility of
finding a template-id. */
if ((next_token->type != CPP_NAME && next_token->keyword != RID_OPERATOR)
|| (next_token->type == CPP_NAME
&& !cp_parser_nth_token_starts_template_argument_list_p
(parser, 2)))
{
cp_parser_error (parser, "expected template-id");
return error_mark_node;
}
/* Remember where the template-id starts. */
if (cp_parser_uncommitted_to_tentative_parse_p (parser))
start_of_id = cp_lexer_token_position (parser->lexer, false);
push_deferring_access_checks (dk_deferred);
/* Parse the template-name. */
is_identifier = false;
template = cp_parser_template_name (parser, template_keyword_p,
check_dependency_p,
is_declaration,
&is_identifier);
if (template == error_mark_node || is_identifier)
{
pop_deferring_access_checks ();
return template;
}
/* If we find the sequence `[:' after a template-name, it's probably
a digraph-typo for `< ::'. Substitute the tokens and check if we can
parse correctly the argument list. */
next_token = cp_lexer_peek_token (parser->lexer);
next_token_2 = cp_lexer_peek_nth_token (parser->lexer, 2);
if (next_token->type == CPP_OPEN_SQUARE
&& next_token->flags & DIGRAPH
&& next_token_2->type == CPP_COLON
&& !(next_token_2->flags & PREV_WHITE))
{
cp_parser_parse_tentatively (parser);
/* Change `:' into `::'. */
next_token_2->type = CPP_SCOPE;
/* Consume the first token (CPP_OPEN_SQUARE - which we pretend it is
CPP_LESS. */
cp_lexer_consume_token (parser->lexer);
/* Parse the arguments. */
arguments = cp_parser_enclosed_template_argument_list (parser);
if (!cp_parser_parse_definitely (parser))
{
/* If we couldn't parse an argument list, then we revert our changes
and return simply an error. Maybe this is not a template-id
after all. */
next_token_2->type = CPP_COLON;
cp_parser_error (parser, "expected %<<%>");
pop_deferring_access_checks ();
return error_mark_node;
}
/* Otherwise, emit an error about the invalid digraph, but continue
parsing because we got our argument list. */
pedwarn ("%<<::%> cannot begin a template-argument list");
inform ("%<<:%> is an alternate spelling for %<[%>. Insert whitespace "
"between %<<%> and %<::%>");
if (!flag_permissive)
{
static bool hint;
if (!hint)
{
inform ("(if you use -fpermissive G++ will accept your code)");
hint = true;
}
}
}
else
{
/* Look for the `<' that starts the template-argument-list. */
if (!cp_parser_require (parser, CPP_LESS, "`<'"))
{
pop_deferring_access_checks ();
return error_mark_node;
}
/* Parse the arguments. */
arguments = cp_parser_enclosed_template_argument_list (parser);
}
/* Build a representation of the specialization. */
if (TREE_CODE (template) == IDENTIFIER_NODE)
template_id = build_min_nt (TEMPLATE_ID_EXPR, template, arguments);
else if (DECL_CLASS_TEMPLATE_P (template)
|| DECL_TEMPLATE_TEMPLATE_PARM_P (template))
{
bool entering_scope;
/* In "template <typename T> ... A<T>::", A<T> is the abstract A
template (rather than some instantiation thereof) only if
is not nested within some other construct. For example, in
"template <typename T> void f(T) { A<T>::", A<T> is just an
instantiation of A. */
entering_scope = (template_parm_scope_p ()
&& cp_lexer_next_token_is (parser->lexer,
CPP_SCOPE));
template_id
= finish_template_type (template, arguments, entering_scope);
}
else
{
/* If it's not a class-template or a template-template, it should be
a function-template. */
gcc_assert ((DECL_FUNCTION_TEMPLATE_P (template)
|| TREE_CODE (template) == OVERLOAD
|| BASELINK_P (template)));
template_id = lookup_template_function (template, arguments);
}
/* If parsing tentatively, replace the sequence of tokens that makes
up the template-id with a CPP_TEMPLATE_ID token. That way,
should we re-parse the token stream, we will not have to repeat
the effort required to do the parse, nor will we issue duplicate
error messages about problems during instantiation of the
template. */
if (start_of_id)
{
cp_token *token = cp_lexer_token_at (parser->lexer, start_of_id);
/* Reset the contents of the START_OF_ID token. */
token->type = CPP_TEMPLATE_ID;
/* Retrieve any deferred checks. Do not pop this access checks yet
so the memory will not be reclaimed during token replacing below. */
token->u.tree_check_value = GGC_CNEW (struct tree_check);
token->u.tree_check_value->value = template_id;
token->u.tree_check_value->checks = get_deferred_access_checks ();
token->keyword = RID_MAX;
/* Purge all subsequent tokens. */
cp_lexer_purge_tokens_after (parser->lexer, start_of_id);
/* ??? Can we actually assume that, if template_id ==
error_mark_node, we will have issued a diagnostic to the
user, as opposed to simply marking the tentative parse as
failed? */
if (cp_parser_error_occurred (parser) && template_id != error_mark_node)
error ("parse error in template argument list");
}
pop_deferring_access_checks ();
return template_id;
}
/* Parse a template-name.
template-name:
identifier
The standard should actually say:
template-name:
identifier
operator-function-id
A defect report has been filed about this issue.
A conversion-function-id cannot be a template name because they cannot
be part of a template-id. In fact, looking at this code:
a.operator K<int>()
the conversion-function-id is "operator K<int>", and K<int> is a type-id.
It is impossible to call a templated conversion-function-id with an
explicit argument list, since the only allowed template parameter is
the type to which it is converting.
If TEMPLATE_KEYWORD_P is true, then we have just seen the
`template' keyword, in a construction like:
T::template f<3>()
In that case `f' is taken to be a template-name, even though there
is no way of knowing for sure.
Returns the TEMPLATE_DECL for the template, or an OVERLOAD if the
name refers to a set of overloaded functions, at least one of which
is a template, or an IDENTIFIER_NODE with the name of the template,
if TEMPLATE_KEYWORD_P is true. If CHECK_DEPENDENCY_P is FALSE,
names are looked up inside uninstantiated templates. */
static tree
cp_parser_template_name (cp_parser* parser,
bool template_keyword_p,
bool check_dependency_p,
bool is_declaration,
bool *is_identifier)
{
tree identifier;
tree decl;
tree fns;
/* If the next token is `operator', then we have either an
operator-function-id or a conversion-function-id. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_OPERATOR))
{
/* We don't know whether we're looking at an
operator-function-id or a conversion-function-id. */
cp_parser_parse_tentatively (parser);
/* Try an operator-function-id. */
identifier = cp_parser_operator_function_id (parser);
/* If that didn't work, try a conversion-function-id. */
if (!cp_parser_parse_definitely (parser))
{
cp_parser_error (parser, "expected template-name");
return error_mark_node;
}
}
/* Look for the identifier. */
else
identifier = cp_parser_identifier (parser);
/* If we didn't find an identifier, we don't have a template-id. */
if (identifier == error_mark_node)
return error_mark_node;
/* If the name immediately followed the `template' keyword, then it
is a template-name. However, if the next token is not `<', then
we do not treat it as a template-name, since it is not being used
as part of a template-id. This enables us to handle constructs
like:
template <typename T> struct S { S(); };
template <typename T> S<T>::S();
correctly. We would treat `S' as a template -- if it were `S<T>'
-- but we do not if there is no `<'. */
if (processing_template_decl
&& cp_parser_nth_token_starts_template_argument_list_p (parser, 1))
{
/* In a declaration, in a dependent context, we pretend that the
"template" keyword was present in order to improve error
recovery. For example, given:
template <typename T> void f(T::X<int>);
we want to treat "X<int>" as a template-id. */
if (is_declaration
&& !template_keyword_p
&& parser->scope && TYPE_P (parser->scope)
&& check_dependency_p
&& dependent_type_p (parser->scope)
/* Do not do this for dtors (or ctors), since they never
need the template keyword before their name. */
&& !constructor_name_p (identifier, parser->scope))
{
cp_token_position start = 0;
/* Explain what went wrong. */
error ("non-template %qD used as template", identifier);
inform ("use %<%T::template %D%> to indicate that it is a template",
parser->scope, identifier);
/* If parsing tentatively, find the location of the "<" token. */
if (cp_parser_simulate_error (parser))
start = cp_lexer_token_position (parser->lexer, true);
/* Parse the template arguments so that we can issue error
messages about them. */
cp_lexer_consume_token (parser->lexer);
cp_parser_enclosed_template_argument_list (parser);
/* Skip tokens until we find a good place from which to
continue parsing. */
cp_parser_skip_to_closing_parenthesis (parser,
/*recovering=*/true,
/*or_comma=*/true,
/*consume_paren=*/false);
/* If parsing tentatively, permanently remove the
template argument list. That will prevent duplicate
error messages from being issued about the missing
"template" keyword. */
if (start)
cp_lexer_purge_tokens_after (parser->lexer, start);
if (is_identifier)
*is_identifier = true;
return identifier;
}
/* If the "template" keyword is present, then there is generally
no point in doing name-lookup, so we just return IDENTIFIER.
But, if the qualifying scope is non-dependent then we can
(and must) do name-lookup normally. */
if (template_keyword_p
&& (!parser->scope
|| (TYPE_P (parser->scope)
&& dependent_type_p (parser->scope))))
return identifier;
}
/* Look up the name. */
decl = cp_parser_lookup_name (parser, identifier,
none_type,
/*is_template=*/false,
/*is_namespace=*/false,
check_dependency_p,
/*ambiguous_decls=*/NULL);
decl = maybe_get_template_decl_from_type_decl (decl);
/* If DECL is a template, then the name was a template-name. */
if (TREE_CODE (decl) == TEMPLATE_DECL)
;
else
{
tree fn = NULL_TREE;
/* The standard does not explicitly indicate whether a name that
names a set of overloaded declarations, some of which are
templates, is a template-name. However, such a name should
be a template-name; otherwise, there is no way to form a
template-id for the overloaded templates. */
fns = BASELINK_P (decl) ? BASELINK_FUNCTIONS (decl) : decl;
if (TREE_CODE (fns) == OVERLOAD)
for (fn = fns; fn; fn = OVL_NEXT (fn))
if (TREE_CODE (OVL_CURRENT (fn)) == TEMPLATE_DECL)
break;
if (!fn)
{
/* The name does not name a template. */
cp_parser_error (parser, "expected template-name");
return error_mark_node;
}
}
/* If DECL is dependent, and refers to a function, then just return
its name; we will look it up again during template instantiation. */
if (DECL_FUNCTION_TEMPLATE_P (decl) || !DECL_P (decl))
{
tree scope = CP_DECL_CONTEXT (get_first_fn (decl));
if (TYPE_P (scope) && dependent_type_p (scope))
return identifier;
}
return decl;
}
/* Parse a template-argument-list.
template-argument-list:
template-argument
template-argument-list , template-argument
Returns a TREE_VEC containing the arguments. */
static tree
cp_parser_template_argument_list (cp_parser* parser)
{
tree fixed_args[10];
unsigned n_args = 0;
unsigned alloced = 10;
tree *arg_ary = fixed_args;
tree vec;
bool saved_in_template_argument_list_p;
bool saved_ice_p;
bool saved_non_ice_p;
saved_in_template_argument_list_p = parser->in_template_argument_list_p;
parser->in_template_argument_list_p = true;
/* Even if the template-id appears in an integral
constant-expression, the contents of the argument list do
not. */
saved_ice_p = parser->integral_constant_expression_p;
parser->integral_constant_expression_p = false;
saved_non_ice_p = parser->non_integral_constant_expression_p;
parser->non_integral_constant_expression_p = false;
/* Parse the arguments. */
do
{
tree argument;
if (n_args)
/* Consume the comma. */
cp_lexer_consume_token (parser->lexer);
/* Parse the template-argument. */
argument = cp_parser_template_argument (parser);
if (n_args == alloced)
{
alloced *= 2;
if (arg_ary == fixed_args)
{
arg_ary = XNEWVEC (tree, alloced);
memcpy (arg_ary, fixed_args, sizeof (tree) * n_args);
}
else
arg_ary = XRESIZEVEC (tree, arg_ary, alloced);
}
arg_ary[n_args++] = argument;
}
while (cp_lexer_next_token_is (parser->lexer, CPP_COMMA));
vec = make_tree_vec (n_args);
while (n_args--)
TREE_VEC_ELT (vec, n_args) = arg_ary[n_args];
if (arg_ary != fixed_args)
free (arg_ary);
parser->non_integral_constant_expression_p = saved_non_ice_p;
parser->integral_constant_expression_p = saved_ice_p;
parser->in_template_argument_list_p = saved_in_template_argument_list_p;
return vec;
}
/* Parse a template-argument.
template-argument:
assignment-expression
type-id
id-expression
The representation is that of an assignment-expression, type-id, or
id-expression -- except that the qualified id-expression is
evaluated, so that the value returned is either a DECL or an
OVERLOAD.
Although the standard says "assignment-expression", it forbids
throw-expressions or assignments in the template argument.
Therefore, we use "conditional-expression" instead. */
static tree
cp_parser_template_argument (cp_parser* parser)
{
tree argument;
bool template_p;
bool address_p;
bool maybe_type_id = false;
cp_token *token;
cp_id_kind idk;
/* There's really no way to know what we're looking at, so we just
try each alternative in order.
[temp.arg]
In a template-argument, an ambiguity between a type-id and an
expression is resolved to a type-id, regardless of the form of
the corresponding template-parameter.
Therefore, we try a type-id first. */
cp_parser_parse_tentatively (parser);
argument = cp_parser_type_id (parser);
/* If there was no error parsing the type-id but the next token is a '>>',
we probably found a typo for '> >'. But there are type-id which are
also valid expressions. For instance:
struct X { int operator >> (int); };
template <int V> struct Foo {};
Foo<X () >> 5> r;
Here 'X()' is a valid type-id of a function type, but the user just
wanted to write the expression "X() >> 5". Thus, we remember that we
found a valid type-id, but we still try to parse the argument as an
expression to see what happens. */
if (!cp_parser_error_occurred (parser)
&& cp_lexer_next_token_is (parser->lexer, CPP_RSHIFT))
{
maybe_type_id = true;
cp_parser_abort_tentative_parse (parser);
}
else
{
/* If the next token isn't a `,' or a `>', then this argument wasn't
really finished. This means that the argument is not a valid
type-id. */
if (!cp_parser_next_token_ends_template_argument_p (parser))
cp_parser_error (parser, "expected template-argument");
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
return argument;
}
/* We're still not sure what the argument will be. */
cp_parser_parse_tentatively (parser);
/* Try a template. */
argument = cp_parser_id_expression (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
&template_p,
/*declarator_p=*/false,
/*optional_p=*/false);
/* If the next token isn't a `,' or a `>', then this argument wasn't
really finished. */
if (!cp_parser_next_token_ends_template_argument_p (parser))
cp_parser_error (parser, "expected template-argument");
if (!cp_parser_error_occurred (parser))
{
/* Figure out what is being referred to. If the id-expression
was for a class template specialization, then we will have a
TYPE_DECL at this point. There is no need to do name lookup
at this point in that case. */
if (TREE_CODE (argument) != TYPE_DECL)
argument = cp_parser_lookup_name (parser, argument,
none_type,
/*is_template=*/template_p,
/*is_namespace=*/false,
/*check_dependency=*/true,
/*ambiguous_decls=*/NULL);
if (TREE_CODE (argument) != TEMPLATE_DECL
&& TREE_CODE (argument) != UNBOUND_CLASS_TEMPLATE)
cp_parser_error (parser, "expected template-name");
}
if (cp_parser_parse_definitely (parser))
return argument;
/* It must be a non-type argument. There permitted cases are given
in [temp.arg.nontype]:
-- an integral constant-expression of integral or enumeration
type; or
-- the name of a non-type template-parameter; or
-- the name of an object or function with external linkage...
-- the address of an object or function with external linkage...
-- a pointer to member... */
/* Look for a non-type template parameter. */
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
{
cp_parser_parse_tentatively (parser);
argument = cp_parser_primary_expression (parser,
/*adress_p=*/false,
/*cast_p=*/false,
/*template_arg_p=*/true,
&idk);
if (TREE_CODE (argument) != TEMPLATE_PARM_INDEX
|| !cp_parser_next_token_ends_template_argument_p (parser))
cp_parser_simulate_error (parser);
if (cp_parser_parse_definitely (parser))
return argument;
}
/* If the next token is "&", the argument must be the address of an
object or function with external linkage. */
address_p = cp_lexer_next_token_is (parser->lexer, CPP_AND);
if (address_p)
cp_lexer_consume_token (parser->lexer);
/* See if we might have an id-expression. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_NAME
|| token->keyword == RID_OPERATOR
|| token->type == CPP_SCOPE
|| token->type == CPP_TEMPLATE_ID
|| token->type == CPP_NESTED_NAME_SPECIFIER)
{
cp_parser_parse_tentatively (parser);
argument = cp_parser_primary_expression (parser,
address_p,
/*cast_p=*/false,
/*template_arg_p=*/true,
&idk);
if (cp_parser_error_occurred (parser)
|| !cp_parser_next_token_ends_template_argument_p (parser))
cp_parser_abort_tentative_parse (parser);
else
{
if (TREE_CODE (argument) == INDIRECT_REF)
{
gcc_assert (REFERENCE_REF_P (argument));
argument = TREE_OPERAND (argument, 0);
}
if (TREE_CODE (argument) == VAR_DECL)
{
/* A variable without external linkage might still be a
valid constant-expression, so no error is issued here
if the external-linkage check fails. */
if (!address_p && !DECL_EXTERNAL_LINKAGE_P (argument))
cp_parser_simulate_error (parser);
}
else if (is_overloaded_fn (argument))
/* All overloaded functions are allowed; if the external
linkage test does not pass, an error will be issued
later. */
;
else if (address_p
&& (TREE_CODE (argument) == OFFSET_REF
|| TREE_CODE (argument) == SCOPE_REF))
/* A pointer-to-member. */
;
else if (TREE_CODE (argument) == TEMPLATE_PARM_INDEX)
;
else
cp_parser_simulate_error (parser);
if (cp_parser_parse_definitely (parser))
{
if (address_p)
argument = build_x_unary_op (ADDR_EXPR, argument);
return argument;
}
}
}
/* If the argument started with "&", there are no other valid
alternatives at this point. */
if (address_p)
{
cp_parser_error (parser, "invalid non-type template argument");
return error_mark_node;
}
/* If the argument wasn't successfully parsed as a type-id followed
by '>>', the argument can only be a constant expression now.
Otherwise, we try parsing the constant-expression tentatively,
because the argument could really be a type-id. */
if (maybe_type_id)
cp_parser_parse_tentatively (parser);
argument = cp_parser_constant_expression (parser,
/*allow_non_constant_p=*/false,
/*non_constant_p=*/NULL);
argument = fold_non_dependent_expr (argument);
if (!maybe_type_id)
return argument;
if (!cp_parser_next_token_ends_template_argument_p (parser))
cp_parser_error (parser, "expected template-argument");
if (cp_parser_parse_definitely (parser))
return argument;
/* We did our best to parse the argument as a non type-id, but that
was the only alternative that matched (albeit with a '>' after
it). We can assume it's just a typo from the user, and a
diagnostic will then be issued. */
return cp_parser_type_id (parser);
}
/* Parse an explicit-instantiation.
explicit-instantiation:
template declaration
Although the standard says `declaration', what it really means is:
explicit-instantiation:
template decl-specifier-seq [opt] declarator [opt] ;
Things like `template int S<int>::i = 5, int S<double>::j;' are not
supposed to be allowed. A defect report has been filed about this
issue.
GNU Extension:
explicit-instantiation:
storage-class-specifier template
decl-specifier-seq [opt] declarator [opt] ;
function-specifier template
decl-specifier-seq [opt] declarator [opt] ; */
static void
cp_parser_explicit_instantiation (cp_parser* parser)
{
int declares_class_or_enum;
cp_decl_specifier_seq decl_specifiers;
tree extension_specifier = NULL_TREE;
/* Look for an (optional) storage-class-specifier or
function-specifier. */
if (cp_parser_allow_gnu_extensions_p (parser))
{
extension_specifier
= cp_parser_storage_class_specifier_opt (parser);
if (!extension_specifier)
extension_specifier
= cp_parser_function_specifier_opt (parser,
/*decl_specs=*/NULL);
}
/* Look for the `template' keyword. */
cp_parser_require_keyword (parser, RID_TEMPLATE, "`template'");
/* Let the front end know that we are processing an explicit
instantiation. */
begin_explicit_instantiation ();
/* [temp.explicit] says that we are supposed to ignore access
control while processing explicit instantiation directives. */
push_deferring_access_checks (dk_no_check);
/* Parse a decl-specifier-seq. */
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_OPTIONAL,
&decl_specifiers,
&declares_class_or_enum);
/* If there was exactly one decl-specifier, and it declared a class,
and there's no declarator, then we have an explicit type
instantiation. */
if (declares_class_or_enum && cp_parser_declares_only_class_p (parser))
{
tree type;
type = check_tag_decl (&decl_specifiers);
/* Turn access control back on for names used during
template instantiation. */
pop_deferring_access_checks ();
if (type)
do_type_instantiation (type, extension_specifier,
/*complain=*/tf_error);
}
else
{
cp_declarator *declarator;
tree decl;
/* Parse the declarator. */
declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
/*ctor_dtor_or_conv_p=*/NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
if (declares_class_or_enum & 2)
cp_parser_check_for_definition_in_return_type (declarator,
decl_specifiers.type);
if (declarator != cp_error_declarator)
{
decl = grokdeclarator (declarator, &decl_specifiers,
NORMAL, 0, &decl_specifiers.attributes);
/* Turn access control back on for names used during
template instantiation. */
pop_deferring_access_checks ();
/* Do the explicit instantiation. */
do_decl_instantiation (decl, extension_specifier);
}
else
{
pop_deferring_access_checks ();
/* Skip the body of the explicit instantiation. */
cp_parser_skip_to_end_of_statement (parser);
}
}
/* We're done with the instantiation. */
end_explicit_instantiation ();
cp_parser_consume_semicolon_at_end_of_statement (parser);
}
/* Parse an explicit-specialization.
explicit-specialization:
template < > declaration
Although the standard says `declaration', what it really means is:
explicit-specialization:
template <> decl-specifier [opt] init-declarator [opt] ;
template <> function-definition
template <> explicit-specialization
template <> template-declaration */
static void
cp_parser_explicit_specialization (cp_parser* parser)
{
bool need_lang_pop;
/* Look for the `template' keyword. */
cp_parser_require_keyword (parser, RID_TEMPLATE, "`template'");
/* Look for the `<'. */
cp_parser_require (parser, CPP_LESS, "`<'");
/* Look for the `>'. */
cp_parser_require (parser, CPP_GREATER, "`>'");
/* We have processed another parameter list. */
++parser->num_template_parameter_lists;
/* [temp]
A template ... explicit specialization ... shall not have C
linkage. */
if (current_lang_name == lang_name_c)
{
error ("template specialization with C linkage");
/* Give it C++ linkage to avoid confusing other parts of the
front end. */
push_lang_context (lang_name_cplusplus);
need_lang_pop = true;
}
else
need_lang_pop = false;
/* Let the front end know that we are beginning a specialization. */
if (!begin_specialization ())
{
end_specialization ();
cp_parser_skip_to_end_of_block_or_statement (parser);
return;
}
/* If the next keyword is `template', we need to figure out whether
or not we're looking a template-declaration. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_TEMPLATE))
{
if (cp_lexer_peek_nth_token (parser->lexer, 2)->type == CPP_LESS
&& cp_lexer_peek_nth_token (parser->lexer, 3)->type != CPP_GREATER)
cp_parser_template_declaration_after_export (parser,
/*member_p=*/false);
else
cp_parser_explicit_specialization (parser);
}
else
/* Parse the dependent declaration. */
cp_parser_single_declaration (parser,
/*checks=*/NULL,
/*member_p=*/false,
/*friend_p=*/NULL);
/* We're done with the specialization. */
end_specialization ();
/* For the erroneous case of a template with C linkage, we pushed an
implicit C++ linkage scope; exit that scope now. */
if (need_lang_pop)
pop_lang_context ();
/* We're done with this parameter list. */
--parser->num_template_parameter_lists;
}
/* Parse a type-specifier.
type-specifier:
simple-type-specifier
class-specifier
enum-specifier
elaborated-type-specifier
cv-qualifier
GNU Extension:
type-specifier:
__complex__
Returns a representation of the type-specifier. For a
class-specifier, enum-specifier, or elaborated-type-specifier, a
TREE_TYPE is returned; otherwise, a TYPE_DECL is returned.
The parser flags FLAGS is used to control type-specifier parsing.
If IS_DECLARATION is TRUE, then this type-specifier is appearing
in a decl-specifier-seq.
If DECLARES_CLASS_OR_ENUM is non-NULL, and the type-specifier is a
class-specifier, enum-specifier, or elaborated-type-specifier, then
*DECLARES_CLASS_OR_ENUM is set to a nonzero value. The value is 1
if a type is declared; 2 if it is defined. Otherwise, it is set to
zero.
If IS_CV_QUALIFIER is non-NULL, and the type-specifier is a
cv-qualifier, then IS_CV_QUALIFIER is set to TRUE. Otherwise, it
is set to FALSE. */
static tree
cp_parser_type_specifier (cp_parser* parser,
cp_parser_flags flags,
cp_decl_specifier_seq *decl_specs,
bool is_declaration,
int* declares_class_or_enum,
bool* is_cv_qualifier)
{
tree type_spec = NULL_TREE;
cp_token *token;
enum rid keyword;
cp_decl_spec ds = ds_last;
/* Assume this type-specifier does not declare a new type. */
if (declares_class_or_enum)
*declares_class_or_enum = 0;
/* And that it does not specify a cv-qualifier. */
if (is_cv_qualifier)
*is_cv_qualifier = false;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If we're looking at a keyword, we can use that to guide the
production we choose. */
keyword = token->keyword;
switch (keyword)
{
case RID_ENUM:
/* Look for the enum-specifier. */
type_spec = cp_parser_enum_specifier (parser);
/* If that worked, we're done. */
if (type_spec)
{
if (declares_class_or_enum)
*declares_class_or_enum = 2;
if (decl_specs)
cp_parser_set_decl_spec_type (decl_specs,
type_spec,
/*user_defined_p=*/true);
return type_spec;
}
else
goto elaborated_type_specifier;
/* Any of these indicate either a class-specifier, or an
elaborated-type-specifier. */
case RID_CLASS:
case RID_STRUCT:
case RID_UNION:
/* Parse tentatively so that we can back up if we don't find a
class-specifier. */
cp_parser_parse_tentatively (parser);
/* Look for the class-specifier. */
type_spec = cp_parser_class_specifier (parser);
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
{
if (declares_class_or_enum)
*declares_class_or_enum = 2;
if (decl_specs)
cp_parser_set_decl_spec_type (decl_specs,
type_spec,
/*user_defined_p=*/true);
return type_spec;
}
/* Fall through. */
elaborated_type_specifier:
/* We're declaring (not defining) a class or enum. */
if (declares_class_or_enum)
*declares_class_or_enum = 1;
/* Fall through. */
case RID_TYPENAME:
/* Look for an elaborated-type-specifier. */
type_spec
= (cp_parser_elaborated_type_specifier
(parser,
decl_specs && decl_specs->specs[(int) ds_friend],
is_declaration));
if (decl_specs)
cp_parser_set_decl_spec_type (decl_specs,
type_spec,
/*user_defined_p=*/true);
return type_spec;
case RID_CONST:
ds = ds_const;
if (is_cv_qualifier)
*is_cv_qualifier = true;
break;
case RID_VOLATILE:
ds = ds_volatile;
if (is_cv_qualifier)
*is_cv_qualifier = true;
break;
case RID_RESTRICT:
ds = ds_restrict;
if (is_cv_qualifier)
*is_cv_qualifier = true;
break;
case RID_COMPLEX:
/* The `__complex__' keyword is a GNU extension. */
ds = ds_complex;
break;
default:
break;
}
/* Handle simple keywords. */
if (ds != ds_last)
{
if (decl_specs)
{
++decl_specs->specs[(int)ds];
decl_specs->any_specifiers_p = true;
}
return cp_lexer_consume_token (parser->lexer)->u.value;
}
/* If we do not already have a type-specifier, assume we are looking
at a simple-type-specifier. */
type_spec = cp_parser_simple_type_specifier (parser,
decl_specs,
flags);
/* If we didn't find a type-specifier, and a type-specifier was not
optional in this context, issue an error message. */
if (!type_spec && !(flags & CP_PARSER_FLAGS_OPTIONAL))
{
cp_parser_error (parser, "expected type specifier");
return error_mark_node;
}
return type_spec;
}
/* Parse a simple-type-specifier.
simple-type-specifier:
:: [opt] nested-name-specifier [opt] type-name
:: [opt] nested-name-specifier template template-id
char
wchar_t
bool
short
int
long
signed
unsigned
float
double
void
GNU Extension:
simple-type-specifier:
__typeof__ unary-expression
__typeof__ ( type-id )
Returns the indicated TYPE_DECL. If DECL_SPECS is not NULL, it is
appropriately updated. */
static tree
cp_parser_simple_type_specifier (cp_parser* parser,
cp_decl_specifier_seq *decl_specs,
cp_parser_flags flags)
{
tree type = NULL_TREE;
cp_token *token;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If we're looking at a keyword, things are easy. */
switch (token->keyword)
{
case RID_CHAR:
if (decl_specs)
decl_specs->explicit_char_p = true;
type = char_type_node;
break;
case RID_WCHAR:
type = wchar_type_node;
break;
case RID_BOOL:
type = boolean_type_node;
break;
case RID_SHORT:
if (decl_specs)
++decl_specs->specs[(int) ds_short];
type = short_integer_type_node;
break;
case RID_INT:
if (decl_specs)
decl_specs->explicit_int_p = true;
type = integer_type_node;
break;
case RID_LONG:
if (decl_specs)
++decl_specs->specs[(int) ds_long];
type = long_integer_type_node;
break;
case RID_SIGNED:
if (decl_specs)
++decl_specs->specs[(int) ds_signed];
type = integer_type_node;
break;
case RID_UNSIGNED:
if (decl_specs)
++decl_specs->specs[(int) ds_unsigned];
type = unsigned_type_node;
break;
case RID_FLOAT:
type = float_type_node;
break;
case RID_DOUBLE:
type = double_type_node;
break;
case RID_VOID:
type = void_type_node;
break;
case RID_TYPEOF:
/* Consume the `typeof' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the operand to `typeof'. */
type = cp_parser_sizeof_operand (parser, RID_TYPEOF);
/* If it is not already a TYPE, take its type. */
if (!TYPE_P (type))
type = finish_typeof (type);
if (decl_specs)
cp_parser_set_decl_spec_type (decl_specs, type,
/*user_defined_p=*/true);
return type;
default:
break;
}
/* If the type-specifier was for a built-in type, we're done. */
if (type)
{
tree id;
/* Record the type. */
if (decl_specs
&& (token->keyword != RID_SIGNED
&& token->keyword != RID_UNSIGNED
&& token->keyword != RID_SHORT
&& token->keyword != RID_LONG))
cp_parser_set_decl_spec_type (decl_specs,
type,
/*user_defined=*/false);
if (decl_specs)
decl_specs->any_specifiers_p = true;
/* Consume the token. */
id = cp_lexer_consume_token (parser->lexer)->u.value;
/* There is no valid C++ program where a non-template type is
followed by a "<". That usually indicates that the user thought
that the type was a template. */
cp_parser_check_for_invalid_template_id (parser, type);
return TYPE_NAME (type);
}
/* The type-specifier must be a user-defined type. */
if (!(flags & CP_PARSER_FLAGS_NO_USER_DEFINED_TYPES))
{
bool qualified_p;
bool global_p;
/* Don't gobble tokens or issue error messages if this is an
optional type-specifier. */
if (flags & CP_PARSER_FLAGS_OPTIONAL)
cp_parser_parse_tentatively (parser);
/* Look for the optional `::' operator. */
global_p
= (cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false)
!= NULL_TREE);
/* Look for the nested-name specifier. */
qualified_p
= (cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/false)
!= NULL_TREE);
/* If we have seen a nested-name-specifier, and the next token
is `template', then we are using the template-id production. */
if (parser->scope
&& cp_parser_optional_template_keyword (parser))
{
/* Look for the template-id. */
type = cp_parser_template_id (parser,
/*template_keyword_p=*/true,
/*check_dependency_p=*/true,
/*is_declaration=*/false);
/* If the template-id did not name a type, we are out of
luck. */
if (TREE_CODE (type) != TYPE_DECL)
{
cp_parser_error (parser, "expected template-id for type");
type = NULL_TREE;
}
}
/* Otherwise, look for a type-name. */
else
type = cp_parser_type_name (parser);
/* Keep track of all name-lookups performed in class scopes. */
if (type
&& !global_p
&& !qualified_p
&& TREE_CODE (type) == TYPE_DECL
&& TREE_CODE (DECL_NAME (type)) == IDENTIFIER_NODE)
maybe_note_name_used_in_class (DECL_NAME (type), type);
/* If it didn't work out, we don't have a TYPE. */
if ((flags & CP_PARSER_FLAGS_OPTIONAL)
&& !cp_parser_parse_definitely (parser))
type = NULL_TREE;
if (type && decl_specs)
cp_parser_set_decl_spec_type (decl_specs, type,
/*user_defined=*/true);
}
/* If we didn't get a type-name, issue an error message. */
if (!type && !(flags & CP_PARSER_FLAGS_OPTIONAL))
{
cp_parser_error (parser, "expected type-name");
return error_mark_node;
}
/* There is no valid C++ program where a non-template type is
followed by a "<". That usually indicates that the user thought
that the type was a template. */
if (type && type != error_mark_node)
{
/* As a last-ditch effort, see if TYPE is an Objective-C type.
If it is, then the '<'...'>' enclose protocol names rather than
template arguments, and so everything is fine. */
/* APPLE LOCAL radar 4516785 */
if (c_dialect_objc () && !parser->scope
&& (objc_is_id (type) || objc_is_class_name (type)))
{
tree protos = cp_parser_objc_protocol_refs_opt (parser);
tree qual_type = objc_get_protocol_qualified_type (type, protos);
/* Clobber the "unqualified" type previously entered into
DECL_SPECS with the new, improved protocol-qualified version. */
if (decl_specs)
decl_specs->type = qual_type;
return qual_type;
}
cp_parser_check_for_invalid_template_id (parser, TREE_TYPE (type));
}
return type;
}
/* Parse a type-name.
type-name:
class-name
enum-name
typedef-name
enum-name:
identifier
typedef-name:
identifier
Returns a TYPE_DECL for the type. */
static tree
cp_parser_type_name (cp_parser* parser)
{
tree type_decl;
tree identifier;
/* We can't know yet whether it is a class-name or not. */
cp_parser_parse_tentatively (parser);
/* Try a class-name. */
type_decl = cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
none_type,
/*check_dependency_p=*/true,
/*class_head_p=*/false,
/*is_declaration=*/false);
/* If it's not a class-name, keep looking. */
if (!cp_parser_parse_definitely (parser))
{
/* It must be a typedef-name or an enum-name. */
identifier = cp_parser_identifier (parser);
if (identifier == error_mark_node)
return error_mark_node;
/* Look up the type-name. */
type_decl = cp_parser_lookup_name_simple (parser, identifier);
if (TREE_CODE (type_decl) != TYPE_DECL
&& (objc_is_id (identifier) || objc_is_class_name (identifier)))
{
/* See if this is an Objective-C type. */
/* APPLE LOCAL begin radar 5355344 */
tree protos;
if (cp_parser_objc_tentative_protocol_refs_opt (parser, &protos))
{
tree type = objc_get_protocol_qualified_type (identifier, protos);
if (type)
type_decl = TYPE_NAME (type);
}
/* APPLE LOCAL end radar 5355344 */
}
/* Issue an error if we did not find a type-name. */
/* APPLE LOCAL begin radar 5277239 */
if (TREE_CODE (type_decl) != TYPE_DECL
|| cp_objc_property_reference_prefix (parser, TREE_TYPE (type_decl)))
/* APPLE LOCAL end radar 5277239 */
{
if (!cp_parser_simulate_error (parser))
cp_parser_name_lookup_error (parser, identifier, type_decl,
"is not a type");
type_decl = error_mark_node;
}
/* Remember that the name was used in the definition of the
current class so that we can check later to see if the
meaning would have been different after the class was
entirely defined. */
else if (type_decl != error_mark_node
&& !parser->scope)
maybe_note_name_used_in_class (identifier, type_decl);
}
return type_decl;
}
/* Parse an elaborated-type-specifier. Note that the grammar given
here incorporates the resolution to DR68.
elaborated-type-specifier:
class-key :: [opt] nested-name-specifier [opt] identifier
class-key :: [opt] nested-name-specifier [opt] template [opt] template-id
enum :: [opt] nested-name-specifier [opt] identifier
typename :: [opt] nested-name-specifier identifier
typename :: [opt] nested-name-specifier template [opt]
template-id
GNU extension:
elaborated-type-specifier:
class-key attributes :: [opt] nested-name-specifier [opt] identifier
class-key attributes :: [opt] nested-name-specifier [opt]
template [opt] template-id
enum attributes :: [opt] nested-name-specifier [opt] identifier
If IS_FRIEND is TRUE, then this elaborated-type-specifier is being
declared `friend'. If IS_DECLARATION is TRUE, then this
elaborated-type-specifier appears in a decl-specifiers-seq, i.e.,
something is being declared.
Returns the TYPE specified. */
static tree
cp_parser_elaborated_type_specifier (cp_parser* parser,
bool is_friend,
bool is_declaration)
{
enum tag_types tag_type;
tree identifier;
tree type = NULL_TREE;
tree attributes = NULL_TREE;
/* See if we're looking at the `enum' keyword. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_ENUM))
{
/* Consume the `enum' token. */
cp_lexer_consume_token (parser->lexer);
/* Remember that it's an enumeration type. */
tag_type = enum_type;
/* Parse the attributes. */
attributes = cp_parser_attributes_opt (parser);
}
/* Or, it might be `typename'. */
else if (cp_lexer_next_token_is_keyword (parser->lexer,
RID_TYPENAME))
{
/* Consume the `typename' token. */
cp_lexer_consume_token (parser->lexer);
/* Remember that it's a `typename' type. */
tag_type = typename_type;
/* The `typename' keyword is only allowed in templates. */
if (!processing_template_decl)
pedwarn ("using %<typename%> outside of template");
}
/* Otherwise it must be a class-key. */
else
{
tag_type = cp_parser_class_key (parser);
if (tag_type == none_type)
return error_mark_node;
/* Parse the attributes. */
attributes = cp_parser_attributes_opt (parser);
}
/* Look for the `::' operator. */
cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false);
/* Look for the nested-name-specifier. */
if (tag_type == typename_type)
{
if (!cp_parser_nested_name_specifier (parser,
/*typename_keyword_p=*/true,
/*check_dependency_p=*/true,
/*type_p=*/true,
is_declaration))
return error_mark_node;
}
else
/* Even though `typename' is not present, the proposed resolution
to Core Issue 180 says that in `class A<T>::B', `B' should be
considered a type-name, even if `A<T>' is dependent. */
cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/true,
/*check_dependency_p=*/true,
/*type_p=*/true,
is_declaration);
/* For everything but enumeration types, consider a template-id.
For an enumeration type, consider only a plain identifier. */
if (tag_type != enum_type)
{
bool template_p = false;
tree decl;
/* Allow the `template' keyword. */
template_p = cp_parser_optional_template_keyword (parser);
/* If we didn't see `template', we don't know if there's a
template-id or not. */
if (!template_p)
cp_parser_parse_tentatively (parser);
/* Parse the template-id. */
decl = cp_parser_template_id (parser, template_p,
/*check_dependency_p=*/true,
is_declaration);
/* If we didn't find a template-id, look for an ordinary
identifier. */
if (!template_p && !cp_parser_parse_definitely (parser))
;
/* If DECL is a TEMPLATE_ID_EXPR, and the `typename' keyword is
in effect, then we must assume that, upon instantiation, the
template will correspond to a class. */
else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR
&& tag_type == typename_type)
type = make_typename_type (parser->scope, decl,
typename_type,
/*complain=*/tf_error);
else
type = TREE_TYPE (decl);
}
if (!type)
{
identifier = cp_parser_identifier (parser);
if (identifier == error_mark_node)
{
parser->scope = NULL_TREE;
return error_mark_node;
}
/* For a `typename', we needn't call xref_tag. */
if (tag_type == typename_type
&& TREE_CODE (parser->scope) != NAMESPACE_DECL)
return cp_parser_make_typename_type (parser, parser->scope,
identifier);
/* Look up a qualified name in the usual way. */
if (parser->scope)
{
tree decl;
/* LLVM LOCAL begin mainline */
tree ambiguous_decls;
/* LLVM LOCAL end mainline */
decl = cp_parser_lookup_name (parser, identifier,
tag_type,
/*is_template=*/false,
/*is_namespace=*/false,
/*check_dependency=*/true,
/* LLVM LOCAL begin mainline */
&ambiguous_decls);
/* LLVM LOCAL end mainline */
/* LLVM LOCAL begin mainline */
/* If the lookup was ambiguous, an error will already have been
issued. */
if (ambiguous_decls)
return error_mark_node;
/* LLVM LOCAL end mainline */
/* If we are parsing friend declaration, DECL may be a
TEMPLATE_DECL tree node here. However, we need to check
whether this TEMPLATE_DECL results in valid code. Consider
the following example:
namespace N {
template <class T> class C {};
}
class X {
template <class T> friend class N::C; // #1, valid code
};
template <class T> class Y {
friend class N::C; // #2, invalid code
};
For both case #1 and #2, we arrive at a TEMPLATE_DECL after
name lookup of `N::C'. We see that friend declaration must
be template for the code to be valid. Note that
processing_template_decl does not work here since it is
always 1 for the above two cases. */
decl = (cp_parser_maybe_treat_template_as_class
(decl, /*tag_name_p=*/is_friend
&& parser->num_template_parameter_lists));
if (TREE_CODE (decl) != TYPE_DECL)
{
cp_parser_diagnose_invalid_type_name (parser,
parser->scope,
identifier);
return error_mark_node;
}
if (TREE_CODE (TREE_TYPE (decl)) != TYPENAME_TYPE)
{
bool allow_template = (parser->num_template_parameter_lists
|| DECL_SELF_REFERENCE_P (decl));
type = check_elaborated_type_specifier (tag_type, decl,
allow_template);
if (type == error_mark_node)
return error_mark_node;
}
type = TREE_TYPE (decl);
}
else
{
/* An elaborated-type-specifier sometimes introduces a new type and
sometimes names an existing type. Normally, the rule is that it
introduces a new type only if there is not an existing type of
the same name already in scope. For example, given:
struct S {};
void f() { struct S s; }
the `struct S' in the body of `f' is the same `struct S' as in
the global scope; the existing definition is used. However, if
there were no global declaration, this would introduce a new
local class named `S'.
An exception to this rule applies to the following code:
namespace N { struct S; }
Here, the elaborated-type-specifier names a new type
unconditionally; even if there is already an `S' in the
containing scope this declaration names a new type.
This exception only applies if the elaborated-type-specifier
forms the complete declaration:
[class.name]
A declaration consisting solely of `class-key identifier ;' is
either a redeclaration of the name in the current scope or a
forward declaration of the identifier as a class name. It
introduces the name into the current scope.
We are in this situation precisely when the next token is a `;'.
An exception to the exception is that a `friend' declaration does
*not* name a new type; i.e., given:
struct S { friend struct T; };
`T' is not a new type in the scope of `S'.
Also, `new struct S' or `sizeof (struct S)' never results in the
definition of a new type; a new type can only be declared in a
declaration context. */
tag_scope ts;
bool template_p;
if (is_friend)
/* Friends have special name lookup rules. */
ts = ts_within_enclosing_non_class;
else if (is_declaration
&& cp_lexer_next_token_is (parser->lexer,
CPP_SEMICOLON))
/* This is a `class-key identifier ;' */
ts = ts_current;
else
ts = ts_global;
template_p =
(parser->num_template_parameter_lists
&& (cp_parser_next_token_starts_class_definition_p (parser)
|| cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)));
/* An unqualified name was used to reference this type, so
there were no qualifying templates. */
if (!cp_parser_check_template_parameters (parser,
/*num_templates=*/0))
return error_mark_node;
type = xref_tag (tag_type, identifier, ts, template_p);
}
}
if (type == error_mark_node)
return error_mark_node;
/* Allow attributes on forward declarations of classes. */
if (attributes)
{
if (TREE_CODE (type) == TYPENAME_TYPE)
warning (OPT_Wattributes,
"attributes ignored on uninstantiated type");
else if (tag_type != enum_type && CLASSTYPE_TEMPLATE_INSTANTIATION (type)
&& ! processing_explicit_instantiation)
warning (OPT_Wattributes,
"attributes ignored on template instantiation");
else if (is_declaration && cp_parser_declares_only_class_p (parser))
cplus_decl_attributes (&type, attributes, (int) ATTR_FLAG_TYPE_IN_PLACE);
else
warning (OPT_Wattributes,
"attributes ignored on elaborated-type-specifier that is not a forward declaration");
}
if (tag_type != enum_type)
cp_parser_check_class_key (tag_type, type);
/* A "<" cannot follow an elaborated type specifier. If that
happens, the user was probably trying to form a template-id. */
cp_parser_check_for_invalid_template_id (parser, type);
return type;
}
/* Parse an enum-specifier.
enum-specifier:
enum identifier [opt] { enumerator-list [opt] }
GNU Extensions:
enum attributes[opt] identifier [opt] { enumerator-list [opt] }
attributes[opt]
Returns an ENUM_TYPE representing the enumeration, or NULL_TREE
if the token stream isn't an enum-specifier after all. */
static tree
cp_parser_enum_specifier (cp_parser* parser)
{
tree identifier;
tree type;
tree attributes;
/* Parse tentatively so that we can back up if we don't find a
enum-specifier. */
cp_parser_parse_tentatively (parser);
/* Caller guarantees that the current token is 'enum', an identifier
possibly follows, and the token after that is an opening brace.
If we don't have an identifier, fabricate an anonymous name for
the enumeration being defined. */
cp_lexer_consume_token (parser->lexer);
attributes = cp_parser_attributes_opt (parser);
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
identifier = cp_parser_identifier (parser);
else
identifier = make_anon_name ();
/* Look for the `{' but don't consume it yet. */
if (!cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
cp_parser_simulate_error (parser);
if (!cp_parser_parse_definitely (parser))
return NULL_TREE;
/* Issue an error message if type-definitions are forbidden here. */
if (!cp_parser_check_type_definition (parser))
type = error_mark_node;
else
/* Create the new type. We do this before consuming the opening
brace so the enum will be recorded as being on the line of its
tag (or the 'enum' keyword, if there is no tag). */
type = start_enum (identifier);
/* Consume the opening brace. */
cp_lexer_consume_token (parser->lexer);
if (type == error_mark_node)
{
cp_parser_skip_to_end_of_block_or_statement (parser);
return error_mark_node;
}
/* If the next token is not '}', then there are some enumerators. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_BRACE))
cp_parser_enumerator_list (parser, type);
/* Consume the final '}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
/* Look for trailing attributes to apply to this enumeration, and
apply them if appropriate. */
if (cp_parser_allow_gnu_extensions_p (parser))
{
tree trailing_attr = cp_parser_attributes_opt (parser);
cplus_decl_attributes (&type,
trailing_attr,
(int) ATTR_FLAG_TYPE_IN_PLACE);
}
/* Finish up the enumeration. */
finish_enum (type);
return type;
}
/* Parse an enumerator-list. The enumerators all have the indicated
TYPE.
enumerator-list:
enumerator-definition
enumerator-list , enumerator-definition */
static void
cp_parser_enumerator_list (cp_parser* parser, tree type)
{
while (true)
{
/* Parse an enumerator-definition. */
cp_parser_enumerator_definition (parser, type);
/* If the next token is not a ',', we've reached the end of
the list. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Otherwise, consume the `,' and keep going. */
cp_lexer_consume_token (parser->lexer);
/* If the next token is a `}', there is a trailing comma. */
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE))
{
if (pedantic && !in_system_header)
pedwarn ("comma at end of enumerator list");
break;
}
}
}
/* Parse an enumerator-definition. The enumerator has the indicated
TYPE.
enumerator-definition:
enumerator
enumerator = constant-expression
enumerator:
identifier */
static void
cp_parser_enumerator_definition (cp_parser* parser, tree type)
{
tree identifier;
tree value;
/* Look for the identifier. */
identifier = cp_parser_identifier (parser);
if (identifier == error_mark_node)
return;
/* If the next token is an '=', then there is an explicit value. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EQ))
{
/* Consume the `=' token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the value. */
value = cp_parser_constant_expression (parser,
/*allow_non_constant_p=*/false,
NULL);
}
else
value = NULL_TREE;
/* Create the enumerator. */
build_enumerator (identifier, value, type);
}
/* Parse a namespace-name.
namespace-name:
original-namespace-name
namespace-alias
Returns the NAMESPACE_DECL for the namespace. */
static tree
cp_parser_namespace_name (cp_parser* parser)
{
tree identifier;
tree namespace_decl;
/* Get the name of the namespace. */
identifier = cp_parser_identifier (parser);
if (identifier == error_mark_node)
return error_mark_node;
/* Look up the identifier in the currently active scope. Look only
for namespaces, due to:
[basic.lookup.udir]
When looking up a namespace-name in a using-directive or alias
definition, only namespace names are considered.
And:
[basic.lookup.qual]
During the lookup of a name preceding the :: scope resolution
operator, object, function, and enumerator names are ignored.
(Note that cp_parser_class_or_namespace_name only calls this
function if the token after the name is the scope resolution
operator.) */
namespace_decl = cp_parser_lookup_name (parser, identifier,
none_type,
/*is_template=*/false,
/*is_namespace=*/true,
/*check_dependency=*/true,
/*ambiguous_decls=*/NULL);
/* If it's not a namespace, issue an error. */
if (namespace_decl == error_mark_node
|| TREE_CODE (namespace_decl) != NAMESPACE_DECL)
{
if (!cp_parser_uncommitted_to_tentative_parse_p (parser))
error ("%qD is not a namespace-name", identifier);
cp_parser_error (parser, "expected namespace-name");
namespace_decl = error_mark_node;
}
return namespace_decl;
}
/* Parse a namespace-definition.
namespace-definition:
named-namespace-definition
unnamed-namespace-definition
named-namespace-definition:
original-namespace-definition
extension-namespace-definition
original-namespace-definition:
namespace identifier { namespace-body }
extension-namespace-definition:
namespace original-namespace-name { namespace-body }
unnamed-namespace-definition:
namespace { namespace-body } */
static void
cp_parser_namespace_definition (cp_parser* parser)
{
tree identifier, attribs;
/* APPLE LOCAL visibility 5805832 */
bool visibility_pushed = false;
/* Look for the `namespace' keyword. */
cp_parser_require_keyword (parser, RID_NAMESPACE, "`namespace'");
/* Get the name of the namespace. We do not attempt to distinguish
between an original-namespace-definition and an
extension-namespace-definition at this point. The semantic
analysis routines are responsible for that. */
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
identifier = cp_parser_identifier (parser);
else
identifier = NULL_TREE;
/* Parse any specified attributes. */
attribs = cp_parser_attributes_opt (parser);
/* Look for the `{' to start the namespace. */
cp_parser_require (parser, CPP_OPEN_BRACE, "`{'");
/* Start the namespace. */
/* APPLE LOCAL visibility 5805832 */
visibility_pushed = push_namespace_with_attribs (identifier, attribs);
/* Parse the body of the namespace. */
cp_parser_namespace_body (parser);
/* APPLE LOCAL begin visibility 5805832 */
#ifdef HANDLE_PRAGMA_VISIBILITY
if (visibility_pushed)
pop_visibility ();
#endif
/* APPLE LOCAL end visibility 5805832 */
/* Finish the namespace. */
pop_namespace ();
/* Look for the final `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
}
/* Parse a namespace-body.
namespace-body:
declaration-seq [opt] */
static void
cp_parser_namespace_body (cp_parser* parser)
{
cp_parser_declaration_seq_opt (parser);
}
/* Parse a namespace-alias-definition.
namespace-alias-definition:
namespace identifier = qualified-namespace-specifier ; */
static void
cp_parser_namespace_alias_definition (cp_parser* parser)
{
tree identifier;
tree namespace_specifier;
/* Look for the `namespace' keyword. */
cp_parser_require_keyword (parser, RID_NAMESPACE, "`namespace'");
/* Look for the identifier. */
identifier = cp_parser_identifier (parser);
if (identifier == error_mark_node)
return;
/* Look for the `=' token. */
cp_parser_require (parser, CPP_EQ, "`='");
/* Look for the qualified-namespace-specifier. */
namespace_specifier
= cp_parser_qualified_namespace_specifier (parser);
/* Look for the `;' token. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
/* Register the alias in the symbol table. */
do_namespace_alias (identifier, namespace_specifier);
}
/* Parse a qualified-namespace-specifier.
qualified-namespace-specifier:
:: [opt] nested-name-specifier [opt] namespace-name
Returns a NAMESPACE_DECL corresponding to the specified
namespace. */
static tree
cp_parser_qualified_namespace_specifier (cp_parser* parser)
{
/* Look for the optional `::'. */
cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false);
/* Look for the optional nested-name-specifier. */
cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/true);
return cp_parser_namespace_name (parser);
}
/* Parse a using-declaration, or, if ACCESS_DECLARATION_P is true, an
access declaration.
using-declaration:
using typename [opt] :: [opt] nested-name-specifier unqualified-id ;
using :: unqualified-id ;
access-declaration:
qualified-id ;
*/
static bool
cp_parser_using_declaration (cp_parser* parser,
bool access_declaration_p)
{
cp_token *token;
bool typename_p = false;
bool global_scope_p;
tree decl;
tree identifier;
tree qscope;
if (access_declaration_p)
cp_parser_parse_tentatively (parser);
else
{
/* Look for the `using' keyword. */
cp_parser_require_keyword (parser, RID_USING, "`using'");
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* See if it's `typename'. */
if (token->keyword == RID_TYPENAME)
{
/* Remember that we've seen it. */
typename_p = true;
/* Consume the `typename' token. */
cp_lexer_consume_token (parser->lexer);
}
}
/* Look for the optional global scope qualification. */
global_scope_p
= (cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false)
!= NULL_TREE);
/* If we saw `typename', or didn't see `::', then there must be a
nested-name-specifier present. */
if (typename_p || !global_scope_p)
qscope = cp_parser_nested_name_specifier (parser, typename_p,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/true);
/* Otherwise, we could be in either of the two productions. In that
case, treat the nested-name-specifier as optional. */
else
qscope = cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/true);
if (!qscope)
qscope = global_namespace;
if (access_declaration_p && cp_parser_error_occurred (parser))
/* Something has already gone wrong; there's no need to parse
further. Since an error has occurred, the return value of
cp_parser_parse_definitely will be false, as required. */
return cp_parser_parse_definitely (parser);
/* Parse the unqualified-id. */
identifier = cp_parser_unqualified_id (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
/*declarator_p=*/true,
/*optional_p=*/false);
if (access_declaration_p)
{
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
cp_parser_simulate_error (parser);
if (!cp_parser_parse_definitely (parser))
return false;
}
/* The function we call to handle a using-declaration is different
depending on what scope we are in. */
if (qscope == error_mark_node || identifier == error_mark_node)
;
else if (TREE_CODE (identifier) != IDENTIFIER_NODE
&& TREE_CODE (identifier) != BIT_NOT_EXPR)
/* [namespace.udecl]
A using declaration shall not name a template-id. */
error ("a template-id may not appear in a using-declaration");
else
{
if (at_class_scope_p ())
{
/* Create the USING_DECL. */
decl = do_class_using_decl (parser->scope, identifier);
/* Add it to the list of members in this class. */
finish_member_declaration (decl);
}
else
{
decl = cp_parser_lookup_name_simple (parser, identifier);
if (decl == error_mark_node)
cp_parser_name_lookup_error (parser, identifier, decl, NULL);
else if (!at_namespace_scope_p ())
do_local_using_decl (decl, qscope, identifier);
else
do_toplevel_using_decl (decl, qscope, identifier);
}
}
/* Look for the final `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
return true;
}
/* Parse a using-directive.
using-directive:
using namespace :: [opt] nested-name-specifier [opt]
namespace-name ; */
static void
cp_parser_using_directive (cp_parser* parser)
{
tree namespace_decl;
tree attribs;
/* Look for the `using' keyword. */
cp_parser_require_keyword (parser, RID_USING, "`using'");
/* And the `namespace' keyword. */
cp_parser_require_keyword (parser, RID_NAMESPACE, "`namespace'");
/* Look for the optional `::' operator. */
cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false);
/* And the optional nested-name-specifier. */
cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/true);
/* Get the namespace being used. */
namespace_decl = cp_parser_namespace_name (parser);
/* And any specified attributes. */
attribs = cp_parser_attributes_opt (parser);
/* Update the symbol table. */
parse_using_directive (namespace_decl, attribs);
/* Look for the final `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
}
/* Parse an asm-definition.
asm-definition:
asm ( string-literal ) ;
APPLE LOCAL begin CW asm blocks
asm { asm-line [opt] }
asm asm-line
APPLE LOCAL end CW asm blocks
GNU Extension:
asm-definition:
asm volatile [opt] ( string-literal ) ;
asm volatile [opt] ( string-literal : asm-operand-list [opt] ) ;
asm volatile [opt] ( string-literal : asm-operand-list [opt]
: asm-operand-list [opt] ) ;
asm volatile [opt] ( string-literal : asm-operand-list [opt]
: asm-operand-list [opt]
: asm-operand-list [opt] ) ; */
static void
/* APPLE LOCAL CW asm blocks */
cp_parser_asm_definition (cp_parser* parser, bool statement_p ATTRIBUTE_UNUSED)
{
tree string;
tree outputs = NULL_TREE;
tree inputs = NULL_TREE;
tree clobbers = NULL_TREE;
/* APPLE LOCAL CW asm blocks */
tree uses = NULL_TREE;
tree asm_stmt;
bool volatile_p = false;
bool extended_p = false;
/* APPLE LOCAL begin CW asm blocks */
cp_token *nextup;
/* Detect when a leading `asm' is actually a spec of an asm function
rather than an asm statement or block. */
if (flag_iasm_blocks)
{
nextup = cp_lexer_peek_nth_token (parser->lexer, 2);
if (statement_p
&& nextup->u.value
&& IASM_SEE_OPCODE (TYPESPEC, nextup->u.value) == IDENTIFIER)
{
nextup->keyword = RID_MAX;
nextup->type = CPP_NAME;
}
if (!((nextup->type == CPP_OPEN_PAREN)
|| (nextup->keyword == RID_VOLATILE
&& cp_lexer_peek_nth_token (parser->lexer, 3)->type == CPP_OPEN_PAREN)
|| (nextup->type == CPP_OPEN_BRACE)
|| (nextup->type == CPP_ATSIGN)
|| (nextup->keyword == RID_ASM)
|| (nextup->type == CPP_DOT)
|| (nextup->type == CPP_SEMICOLON)
|| (nextup->flags & BOL)
|| (nextup->type == CPP_NAME
&& !iasm_typename_or_reserved (nextup->u.value))))
{
/* An asm function - we'll treat the `asm' as if it were a
storage class spec, which will eventually affect function
body parsing. */
cp_parser_simple_declaration (parser, true);
return;
}
}
/* APPLE LOCAL end CW asm blocks */
/* Look for the `asm' keyword. */
cp_parser_require_keyword (parser, RID_ASM, "`asm'");
/* See if the next token is `volatile'. */
if (cp_parser_allow_gnu_extensions_p (parser)
&& cp_lexer_next_token_is_keyword (parser->lexer, RID_VOLATILE))
{
/* Remember that we saw the `volatile' keyword. */
volatile_p = true;
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
}
/* APPLE LOCAL begin CW asm blocks */
/* A CW-style asm block is introduced by an open brace. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
{
if (flag_iasm_blocks)
cp_parser_iasm_compound_statement (parser);
else
error ("asm blocks not enabled, use `-fasm-blocks'");
return;
}
if (! volatile_p
&& (cp_lexer_next_token_is (parser->lexer, CPP_DOT)
|| cp_lexer_next_token_is (parser->lexer, CPP_ATSIGN)
|| cp_lexer_next_token_is (parser->lexer, CPP_NAME)
|| cp_lexer_next_token_is_keyword (parser->lexer, RID_ASM)
|| cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)
|| (cp_lexer_iasm_bol (parser->lexer)
&& ! cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))))
{
if (flag_iasm_blocks)
cp_parser_iasm_top_statement (parser);
else
error ("asm blocks not enabled, use `-fasm-blocks'");
return;
}
/* APPLE LOCAL end CW asm blocks */
/* Look for the opening `('. */
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return;
/* Look for the string. */
string = cp_parser_string_literal (parser, false, false);
if (string == error_mark_node)
{
cp_parser_skip_to_closing_parenthesis (parser, true, false,
/*consume_paren=*/true);
return;
}
/* If we're allowing GNU extensions, check for the extended assembly
syntax. Unfortunately, the `:' tokens need not be separated by
a space in C, and so, for compatibility, we tolerate that here
too. Doing that means that we have to treat the `::' operator as
two `:' tokens. */
if (cp_parser_allow_gnu_extensions_p (parser)
&& parser->in_function_body
&& (cp_lexer_next_token_is (parser->lexer, CPP_COLON)
|| cp_lexer_next_token_is (parser->lexer, CPP_SCOPE)))
{
bool inputs_p = false;
bool clobbers_p = false;
/* The extended syntax was used. */
extended_p = true;
/* Look for outputs. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COLON))
{
/* Consume the `:'. */
cp_lexer_consume_token (parser->lexer);
/* Parse the output-operands. */
if (cp_lexer_next_token_is_not (parser->lexer,
CPP_COLON)
&& cp_lexer_next_token_is_not (parser->lexer,
CPP_SCOPE)
&& cp_lexer_next_token_is_not (parser->lexer,
CPP_CLOSE_PAREN))
outputs = cp_parser_asm_operand_list (parser);
}
/* If the next token is `::', there are no outputs, and the
next token is the beginning of the inputs. */
else if (cp_lexer_next_token_is (parser->lexer, CPP_SCOPE))
/* The inputs are coming next. */
inputs_p = true;
/* Look for inputs. */
if (inputs_p
|| cp_lexer_next_token_is (parser->lexer, CPP_COLON))
{
/* Consume the `:' or `::'. */
cp_lexer_consume_token (parser->lexer);
/* Parse the output-operands. */
if (cp_lexer_next_token_is_not (parser->lexer,
CPP_COLON)
&& cp_lexer_next_token_is_not (parser->lexer,
CPP_CLOSE_PAREN))
inputs = cp_parser_asm_operand_list (parser);
}
else if (cp_lexer_next_token_is (parser->lexer, CPP_SCOPE))
/* The clobbers are coming next. */
clobbers_p = true;
/* Look for clobbers. */
if (clobbers_p
|| cp_lexer_next_token_is (parser->lexer, CPP_COLON))
{
/* Consume the `:' or `::'. */
cp_lexer_consume_token (parser->lexer);
/* Parse the clobbers. */
if (cp_lexer_next_token_is_not (parser->lexer,
CPP_CLOSE_PAREN))
clobbers = cp_parser_asm_clobber_list (parser);
}
}
/* Look for the closing `)'. */
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, true, false,
/*consume_paren=*/true);
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
/* Create the ASM_EXPR. */
if (parser->in_function_body)
{
asm_stmt = finish_asm_stmt (volatile_p, string, outputs,
/* APPLE LOCAL CW asm blocks */
inputs, clobbers, uses);
/* If the extended syntax was not used, mark the ASM_EXPR. */
if (!extended_p)
{
tree temp = asm_stmt;
if (TREE_CODE (temp) == CLEANUP_POINT_EXPR)
temp = TREE_OPERAND (temp, 0);
ASM_INPUT_P (temp) = 1;
}
}
else
cgraph_add_asm_node (string);
}
/* Declarators [gram.dcl.decl] */
/* Parse an init-declarator.
init-declarator:
declarator initializer [opt]
GNU Extension:
init-declarator:
declarator asm-specification [opt] attributes [opt] initializer [opt]
function-definition:
decl-specifier-seq [opt] declarator ctor-initializer [opt]
function-body
decl-specifier-seq [opt] declarator function-try-block
GNU Extension:
function-definition:
__extension__ function-definition
The DECL_SPECIFIERS apply to this declarator. Returns a
representation of the entity declared. If MEMBER_P is TRUE, then
this declarator appears in a class scope. The new DECL created by
this declarator is returned.
The CHECKS are access checks that should be performed once we know
what entity is being declared (and, therefore, what classes have
befriended it).
If FUNCTION_DEFINITION_ALLOWED_P then we handle the declarator and
for a function-definition here as well. If the declarator is a
declarator for a function-definition, *FUNCTION_DEFINITION_P will
be TRUE upon return. By that point, the function-definition will
have been completely parsed.
FUNCTION_DEFINITION_P may be NULL if FUNCTION_DEFINITION_ALLOWED_P
is FALSE. */
static tree
cp_parser_init_declarator (cp_parser* parser,
cp_decl_specifier_seq *decl_specifiers,
VEC (deferred_access_check,gc)* checks,
bool function_definition_allowed_p,
bool member_p,
int declares_class_or_enum,
bool* function_definition_p)
{
cp_token *token;
cp_declarator *declarator;
tree prefix_attributes;
tree attributes;
tree asm_specification;
tree initializer;
tree decl = NULL_TREE;
tree scope;
bool is_initialized;
/* Only valid if IS_INITIALIZED is true. In that case, CPP_EQ if
initialized with "= ..", CPP_OPEN_PAREN if initialized with
"(...)". */
enum cpp_ttype initialization_kind;
bool is_parenthesized_init = false;
bool is_non_constant_init;
int ctor_dtor_or_conv_p;
bool friend_p;
tree pushed_scope = NULL;
/* Gather the attributes that were provided with the
decl-specifiers. */
prefix_attributes = decl_specifiers->attributes;
/* Assume that this is not the declarator for a function
definition. */
if (function_definition_p)
*function_definition_p = false;
/* Defer access checks while parsing the declarator; we cannot know
what names are accessible until we know what is being
declared. */
resume_deferring_access_checks ();
/* Parse the declarator. */
declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
&ctor_dtor_or_conv_p,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
/* Gather up the deferred checks. */
stop_deferring_access_checks ();
/* If the DECLARATOR was erroneous, there's no need to go
further. */
if (declarator == cp_error_declarator)
return error_mark_node;
/* Check that the number of template-parameter-lists is OK. */
if (!cp_parser_check_declarator_template_parameters (parser, declarator))
return error_mark_node;
if (declares_class_or_enum & 2)
cp_parser_check_for_definition_in_return_type (declarator,
decl_specifiers->type);
/* Figure out what scope the entity declared by the DECLARATOR is
located in. `grokdeclarator' sometimes changes the scope, so
we compute it now. */
scope = get_scope_of_declarator (declarator);
/* If we're allowing GNU extensions, look for an asm-specification
and attributes. */
if (cp_parser_allow_gnu_extensions_p (parser))
{
/* Look for an asm-specification. */
asm_specification = cp_parser_asm_specification_opt (parser);
/* And attributes. */
attributes = cp_parser_attributes_opt (parser);
}
else
{
asm_specification = NULL_TREE;
attributes = NULL_TREE;
}
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Check to see if the token indicates the start of a
function-definition. */
if (cp_parser_token_starts_function_definition_p (token))
{
if (!function_definition_allowed_p)
{
/* If a function-definition should not appear here, issue an
error message. */
cp_parser_error (parser,
"a function-definition is not allowed here");
return error_mark_node;
}
else
{
/* Neither attributes nor an asm-specification are allowed
on a function-definition. */
if (asm_specification)
error ("an asm-specification is not allowed on a function-definition");
if (attributes)
error ("attributes are not allowed on a function-definition");
/* This is a function-definition. */
*function_definition_p = true;
/* Parse the function definition. */
if (member_p)
decl = cp_parser_save_member_function_body (parser,
decl_specifiers,
declarator,
prefix_attributes);
else
decl
= (cp_parser_function_definition_from_specifiers_and_declarator
(parser, decl_specifiers, prefix_attributes, declarator));
return decl;
}
}
/* [dcl.dcl]
Only in function declarations for constructors, destructors, and
type conversions can the decl-specifier-seq be omitted.
We explicitly postpone this check past the point where we handle
function-definitions because we tolerate function-definitions
that are missing their return types in some modes. */
if (!decl_specifiers->any_specifiers_p && ctor_dtor_or_conv_p <= 0)
{
cp_parser_error (parser,
"expected constructor, destructor, or type conversion");
return error_mark_node;
}
/* An `=' or an `(' indicates an initializer. */
if (token->type == CPP_EQ
|| token->type == CPP_OPEN_PAREN)
{
is_initialized = true;
initialization_kind = token->type;
}
else
{
/* If the init-declarator isn't initialized and isn't followed by a
`,' or `;', it's not a valid init-declarator. */
if (token->type != CPP_COMMA
&& token->type != CPP_SEMICOLON)
{
cp_parser_error (parser, "expected initializer");
return error_mark_node;
}
is_initialized = false;
initialization_kind = CPP_EOF;
}
/* Because start_decl has side-effects, we should only call it if we
know we're going ahead. By this point, we know that we cannot
possibly be looking at any other construct. */
cp_parser_commit_to_tentative_parse (parser);
/* If the decl specifiers were bad, issue an error now that we're
sure this was intended to be a declarator. Then continue
declaring the variable(s), as int, to try to cut down on further
errors. */
if (decl_specifiers->any_specifiers_p
&& decl_specifiers->type == error_mark_node)
{
cp_parser_error (parser, "invalid type in declaration");
decl_specifiers->type = integer_type_node;
}
/* Check to see whether or not this declaration is a friend. */
friend_p = cp_parser_friend_p (decl_specifiers);
/* Enter the newly declared entry in the symbol table. If we're
processing a declaration in a class-specifier, we wait until
after processing the initializer. */
if (!member_p)
{
if (parser->in_unbraced_linkage_specification_p)
decl_specifiers->storage_class = sc_extern;
decl = start_decl (declarator, decl_specifiers,
is_initialized, attributes, prefix_attributes,
&pushed_scope);
}
else if (scope)
/* Enter the SCOPE. That way unqualified names appearing in the
initializer will be looked up in SCOPE. */
pushed_scope = push_scope (scope);
/* Perform deferred access control checks, now that we know in which
SCOPE the declared entity resides. */
if (!member_p && decl)
{
tree saved_current_function_decl = NULL_TREE;
/* If the entity being declared is a function, pretend that we
are in its scope. If it is a `friend', it may have access to
things that would not otherwise be accessible. */
if (TREE_CODE (decl) == FUNCTION_DECL)
{
saved_current_function_decl = current_function_decl;
current_function_decl = decl;
}
/* Perform access checks for template parameters. */
cp_parser_perform_template_parameter_access_checks (checks);
/* Perform the access control checks for the declarator and the
the decl-specifiers. */
perform_deferred_access_checks ();
/* Restore the saved value. */
if (TREE_CODE (decl) == FUNCTION_DECL)
current_function_decl = saved_current_function_decl;
}
/* Parse the initializer. */
initializer = NULL_TREE;
is_parenthesized_init = false;
is_non_constant_init = true;
if (is_initialized)
{
if (function_declarator_p (declarator))
{
if (initialization_kind == CPP_EQ)
initializer = cp_parser_pure_specifier (parser);
else
{
/* If the declaration was erroneous, we don't really
know what the user intended, so just silently
consume the initializer. */
if (decl != error_mark_node)
error ("initializer provided for function");
cp_parser_skip_to_closing_parenthesis (parser,
/*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
}
}
else
initializer = cp_parser_initializer (parser,
&is_parenthesized_init,
&is_non_constant_init);
}
/* The old parser allows attributes to appear after a parenthesized
initializer. Mark Mitchell proposed removing this functionality
on the GCC mailing lists on 2002-08-13. This parser accepts the
attributes -- but ignores them. */
if (cp_parser_allow_gnu_extensions_p (parser) && is_parenthesized_init)
if (cp_parser_attributes_opt (parser))
warning (OPT_Wattributes,
"attributes after parenthesized initializer ignored");
/* For an in-class declaration, use `grokfield' to create the
declaration. */
if (member_p)
{
if (pushed_scope)
{
pop_scope (pushed_scope);
pushed_scope = false;
}
decl = grokfield (declarator, decl_specifiers,
initializer, !is_non_constant_init,
/*asmspec=*/NULL_TREE,
prefix_attributes);
if (decl && TREE_CODE (decl) == FUNCTION_DECL)
cp_parser_save_default_args (parser, decl);
}
/* Finish processing the declaration. But, skip friend
declarations. */
if (!friend_p && decl && decl != error_mark_node)
{
cp_finish_decl (decl,
initializer, !is_non_constant_init,
asm_specification,
/* If the initializer is in parentheses, then this is
a direct-initialization, which means that an
`explicit' constructor is OK. Otherwise, an
`explicit' constructor cannot be used. */
((is_parenthesized_init || !is_initialized)
? 0 : LOOKUP_ONLYCONVERTING));
}
if (!friend_p && pushed_scope)
pop_scope (pushed_scope);
return decl;
}
/* APPLE LOCAL begin blocks 6040305 (cc) */
static cp_cv_quals
cp_parser_cv_qualifier_or_attribute_seq_opt (cp_parser *parser, tree *attrs_p)
{
cp_cv_quals quals = TYPE_UNQUALIFIED;
cp_cv_quals q;
cp_token *token;
*attrs_p = NULL_TREE;
while (true)
{
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Handle attributes. */
if (token->keyword == RID_ATTRIBUTE)
{
/* Parse the attributes. */
*attrs_p = chainon (*attrs_p,
cp_parser_attributes_opt (parser));
continue;
}
q = cp_parser_cv_qualifier_seq_opt (parser);
if (q == TYPE_UNQUALIFIED)
break;
quals |= q;
}
return quals;
}
/* APPLE LOCAL end blocks 6040305 (cc) */
/* Parse a declarator.
declarator:
direct-declarator
ptr-operator declarator
abstract-declarator:
ptr-operator abstract-declarator [opt]
direct-abstract-declarator
GNU Extensions:
declarator:
attributes [opt] direct-declarator
attributes [opt] ptr-operator declarator
abstract-declarator:
attributes [opt] ptr-operator abstract-declarator [opt]
attributes [opt] direct-abstract-declarator
APPLE LOCAL begin blocks 6339747
block-declarator:
attributes [opt] ptr-operator block-declarator [opt]
attributes [opt] direct-block-declarator
APPLE LOCAL end blocks 6339747
If CTOR_DTOR_OR_CONV_P is not NULL, *CTOR_DTOR_OR_CONV_P is used to
detect constructor, destructor or conversion operators. It is set
to -1 if the declarator is a name, and +1 if it is a
function. Otherwise it is set to zero. Usually you just want to
test for >0, but internally the negative value is used.
(The reason for CTOR_DTOR_OR_CONV_P is that a declaration must have
a decl-specifier-seq unless it declares a constructor, destructor,
or conversion. It might seem that we could check this condition in
semantic analysis, rather than parsing, but that makes it difficult
to handle something like `f()'. We want to notice that there are
no decl-specifiers, and therefore realize that this is an
expression, not a declaration.)
If PARENTHESIZED_P is non-NULL, *PARENTHESIZED_P is set to true iff
the declarator is a direct-declarator of the form "(...)".
MEMBER_P is true iff this declarator is a member-declarator. */
static cp_declarator *
cp_parser_declarator (cp_parser* parser,
cp_parser_declarator_kind dcl_kind,
int* ctor_dtor_or_conv_p,
bool* parenthesized_p,
bool member_p)
{
cp_token *token;
cp_declarator *declarator;
enum tree_code code;
cp_cv_quals cv_quals;
tree class_type;
tree attributes = NULL_TREE;
/* Assume this is not a constructor, destructor, or type-conversion
operator. */
if (ctor_dtor_or_conv_p)
*ctor_dtor_or_conv_p = 0;
if (cp_parser_allow_gnu_extensions_p (parser))
attributes = cp_parser_attributes_opt (parser);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL begin blocks 6040305 (cc) */
if (flag_blocks && token->type == CPP_XOR)
{
cp_cv_quals quals;
cp_declarator *inner;
tree attrs;
cp_lexer_consume_token (parser->lexer);
/* cp_parse_declspecs (parser, quals_attrs, false, false, true); */
quals = cp_parser_cv_qualifier_or_attribute_seq_opt (parser, &attrs);
inner = cp_parser_declarator (parser, CP_PARSER_DECLARATOR_EITHER,
/*ctor_dtor_or_conv_p=*/NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
if (inner == cp_error_declarator)
return inner;
return make_block_pointer_declarator (attrs, quals, inner);
}
/* APPLE LOCAL end blocks 6040305 (cc) */
/* Check for the ptr-operator production. */
cp_parser_parse_tentatively (parser);
/* Parse the ptr-operator. */
code = cp_parser_ptr_operator (parser,
&class_type,
&cv_quals);
/* If that worked, then we have a ptr-operator. */
if (cp_parser_parse_definitely (parser))
{
/* If a ptr-operator was found, then this declarator was not
parenthesized. */
if (parenthesized_p)
*parenthesized_p = true;
/* The dependent declarator is optional if we are parsing an
abstract-declarator. */
if (dcl_kind != CP_PARSER_DECLARATOR_NAMED)
cp_parser_parse_tentatively (parser);
/* Parse the dependent declarator. */
declarator = cp_parser_declarator (parser, dcl_kind,
/*ctor_dtor_or_conv_p=*/NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
/* If we are parsing an abstract-declarator, we must handle the
case where the dependent declarator is absent. */
if (dcl_kind != CP_PARSER_DECLARATOR_NAMED
&& !cp_parser_parse_definitely (parser))
declarator = NULL;
/* Build the representation of the ptr-operator. */
if (class_type)
declarator = make_ptrmem_declarator (cv_quals,
class_type,
declarator);
else if (code == INDIRECT_REF)
declarator = make_pointer_declarator (cv_quals, declarator);
else
declarator = make_reference_declarator (cv_quals, declarator);
}
/* Everything else is a direct-declarator. */
else
{
if (parenthesized_p)
*parenthesized_p = cp_lexer_next_token_is (parser->lexer,
CPP_OPEN_PAREN);
declarator = cp_parser_direct_declarator (parser, dcl_kind,
ctor_dtor_or_conv_p,
member_p);
}
if (attributes && declarator && declarator != cp_error_declarator)
declarator->attributes = attributes;
return declarator;
}
/* Parse a direct-declarator or direct-abstract-declarator.
direct-declarator:
declarator-id
direct-declarator ( parameter-declaration-clause )
cv-qualifier-seq [opt]
exception-specification [opt]
direct-declarator [ constant-expression [opt] ]
( declarator )
direct-abstract-declarator:
direct-abstract-declarator [opt]
( parameter-declaration-clause )
cv-qualifier-seq [opt]
exception-specification [opt]
direct-abstract-declarator [opt] [ constant-expression [opt] ]
( abstract-declarator )
APPLE LOCAL begin blocks 6339747
GNU Extensions:
direct-block-declarator:
direct-block-declarator [opt]
( parameter-declaration-clause ) [opt]
exception-specification [opt]
direct-block-declarator [opt] [ constant-expression [opt] ]
( block-declarator )
APPLE LOCAL end blocks 6339747
Returns a representation of the declarator. DCL_KIND is
CP_PARSER_DECLARATOR_ABSTRACT, if we are parsing a
direct-abstract-declarator. It is CP_PARSER_DECLARATOR_NAMED, if
we are parsing a direct-declarator. It is
CP_PARSER_DECLARATOR_EITHER, if we can accept either - in the case
of ambiguity we prefer an abstract declarator, as per
[dcl.ambig.res]. CTOR_DTOR_OR_CONV_P and MEMBER_P are as for
cp_parser_declarator. */
static cp_declarator *
cp_parser_direct_declarator (cp_parser* parser,
cp_parser_declarator_kind dcl_kind,
int* ctor_dtor_or_conv_p,
bool member_p)
{
cp_token *token;
cp_declarator *declarator = NULL;
tree scope = NULL_TREE;
bool saved_default_arg_ok_p = parser->default_arg_ok_p;
bool saved_in_declarator_p = parser->in_declarator_p;
bool first = true;
tree pushed_scope = NULL_TREE;
while (true)
{
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_OPEN_PAREN)
{
/* This is either a parameter-declaration-clause, or a
parenthesized declarator. When we know we are parsing a
named declarator, it must be a parenthesized declarator
if FIRST is true. For instance, `(int)' is a
parameter-declaration-clause, with an omitted
direct-abstract-declarator. But `((*))', is a
parenthesized abstract declarator. Finally, when T is a
template parameter `(T)' is a
parameter-declaration-clause, and not a parenthesized
named declarator.
We first try and parse a parameter-declaration-clause,
and then try a nested declarator (if FIRST is true).
It is not an error for it not to be a
parameter-declaration-clause, even when FIRST is
false. Consider,
int i (int);
int i (3);
The first is the declaration of a function while the
second is a the definition of a variable, including its
initializer.
Having seen only the parenthesis, we cannot know which of
these two alternatives should be selected. Even more
complex are examples like:
int i (int (a));
int i (int (3));
The former is a function-declaration; the latter is a
variable initialization.
Thus again, we try a parameter-declaration-clause, and if
that fails, we back out and return. */
if (!first || dcl_kind != CP_PARSER_DECLARATOR_NAMED)
{
cp_parameter_declarator *params;
unsigned saved_num_template_parameter_lists;
/* In a member-declarator, the only valid interpretation
of a parenthesis is the start of a
parameter-declaration-clause. (It is invalid to
initialize a static data member with a parenthesized
initializer; only the "=" form of initialization is
permitted.) */
if (!member_p)
cp_parser_parse_tentatively (parser);
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
if (first)
{
/* If this is going to be an abstract declarator, we're
in a declarator and we can't have default args. */
parser->default_arg_ok_p = false;
parser->in_declarator_p = true;
}
/* Inside the function parameter list, surrounding
template-parameter-lists do not apply. */
saved_num_template_parameter_lists
= parser->num_template_parameter_lists;
parser->num_template_parameter_lists = 0;
/* Parse the parameter-declaration-clause. */
params = cp_parser_parameter_declaration_clause (parser);
parser->num_template_parameter_lists
= saved_num_template_parameter_lists;
/* If all went well, parse the cv-qualifier-seq and the
exception-specification. */
if (member_p || cp_parser_parse_definitely (parser))
{
cp_cv_quals cv_quals;
tree exception_specification;
if (ctor_dtor_or_conv_p)
*ctor_dtor_or_conv_p = *ctor_dtor_or_conv_p < 0;
first = false;
/* Consume the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* APPLE LOCAL begin blocks 6339747 */
if (dcl_kind != BLOCKDEF)
{
/* Parse the cv-qualifier-seq. */
cv_quals = cp_parser_cv_qualifier_seq_opt (parser);
}
else
cv_quals = TYPE_UNQUALIFIED;
/* APPLE LOCAL end blocks 6339747 */
/* And the exception-specification. */
exception_specification
= cp_parser_exception_specification_opt (parser);
/* Create the function-declarator. */
declarator = make_call_declarator (declarator,
params,
cv_quals,
exception_specification);
/* Any subsequent parameter lists are to do with
return type, so are not those of the declared
function. */
parser->default_arg_ok_p = false;
/* Repeat the main loop. */
continue;
}
}
/* If this is the first, we can try a parenthesized
declarator. */
if (first)
{
bool saved_in_type_id_in_expr_p;
parser->default_arg_ok_p = saved_default_arg_ok_p;
parser->in_declarator_p = saved_in_declarator_p;
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Parse the nested declarator. */
saved_in_type_id_in_expr_p = parser->in_type_id_in_expr_p;
parser->in_type_id_in_expr_p = true;
declarator
= cp_parser_declarator (parser, dcl_kind, ctor_dtor_or_conv_p,
/*parenthesized_p=*/NULL,
member_p);
parser->in_type_id_in_expr_p = saved_in_type_id_in_expr_p;
first = false;
/* Expect a `)'. */
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
declarator = cp_error_declarator;
if (declarator == cp_error_declarator)
break;
goto handle_declarator;
}
/* Otherwise, we must be done. */
else
break;
}
else if ((!first || dcl_kind != CP_PARSER_DECLARATOR_NAMED)
&& token->type == CPP_OPEN_SQUARE)
{
/* Parse an array-declarator. */
tree bounds;
if (ctor_dtor_or_conv_p)
*ctor_dtor_or_conv_p = 0;
first = false;
parser->default_arg_ok_p = false;
parser->in_declarator_p = true;
/* Consume the `['. */
cp_lexer_consume_token (parser->lexer);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If the next token is `]', then there is no
constant-expression. */
if (token->type != CPP_CLOSE_SQUARE)
{
bool non_constant_p;
bounds
= cp_parser_constant_expression (parser,
/*allow_non_constant=*/true,
&non_constant_p);
if (!non_constant_p)
bounds = fold_non_dependent_expr (bounds);
/* Normally, the array bound must be an integral constant
expression. However, as an extension, we allow VLAs
in function scopes. */
else if (!parser->in_function_body)
{
error ("array bound is not an integer constant");
bounds = error_mark_node;
}
}
else
bounds = NULL_TREE;
/* Look for the closing `]'. */
if (!cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'"))
{
declarator = cp_error_declarator;
break;
}
declarator = make_array_declarator (declarator, bounds);
}
/* APPLE LOCAL begin blocks 6339747 */
else if (first && (dcl_kind == CP_PARSER_DECLARATOR_NAMED
|| dcl_kind == CP_PARSER_DECLARATOR_EITHER))
/* APPLE LOCAL end blocks 6339747 */
{
tree qualifying_scope;
tree unqualified_name;
special_function_kind sfk;
bool abstract_ok;
/* Parse a declarator-id */
abstract_ok = (dcl_kind == CP_PARSER_DECLARATOR_EITHER);
if (abstract_ok)
cp_parser_parse_tentatively (parser);
unqualified_name
= cp_parser_declarator_id (parser, /*optional_p=*/abstract_ok);
qualifying_scope = parser->scope;
if (abstract_ok)
{
if (!cp_parser_parse_definitely (parser))
unqualified_name = error_mark_node;
else if (unqualified_name
&& (qualifying_scope
|| (TREE_CODE (unqualified_name)
!= IDENTIFIER_NODE)))
{
cp_parser_error (parser, "expected unqualified-id");
unqualified_name = error_mark_node;
}
}
if (!unqualified_name)
return NULL;
if (unqualified_name == error_mark_node)
{
declarator = cp_error_declarator;
break;
}
if (qualifying_scope && at_namespace_scope_p ()
&& TREE_CODE (qualifying_scope) == TYPENAME_TYPE)
{
/* In the declaration of a member of a template class
outside of the class itself, the SCOPE will sometimes
be a TYPENAME_TYPE. For example, given:
template <typename T>
int S<T>::R::i = 3;
the SCOPE will be a TYPENAME_TYPE for `S<T>::R'. In
this context, we must resolve S<T>::R to an ordinary
type, rather than a typename type.
The reason we normally avoid resolving TYPENAME_TYPEs
is that a specialization of `S' might render
`S<T>::R' not a type. However, if `S' is
specialized, then this `i' will not be used, so there
is no harm in resolving the types here. */
tree type;
/* Resolve the TYPENAME_TYPE. */
type = resolve_typename_type (qualifying_scope,
/*only_current_p=*/false);
/* If that failed, the declarator is invalid. */
if (type == error_mark_node)
error ("%<%T::%D%> is not a type",
TYPE_CONTEXT (qualifying_scope),
TYPE_IDENTIFIER (qualifying_scope));
qualifying_scope = type;
}
sfk = sfk_none;
if (unqualified_name)
{
tree class_type;
if (qualifying_scope
&& CLASS_TYPE_P (qualifying_scope))
class_type = qualifying_scope;
else
class_type = current_class_type;
if (TREE_CODE (unqualified_name) == TYPE_DECL)
{
tree name_type = TREE_TYPE (unqualified_name);
if (class_type && same_type_p (name_type, class_type))
{
if (qualifying_scope
&& CLASSTYPE_USE_TEMPLATE (name_type))
{
error ("invalid use of constructor as a template");
inform ("use %<%T::%D%> instead of %<%T::%D%> to "
"name the constructor in a qualified name",
class_type,
DECL_NAME (TYPE_TI_TEMPLATE (class_type)),
class_type, name_type);
declarator = cp_error_declarator;
break;
}
else
unqualified_name = constructor_name (class_type);
}
else
{
/* We do not attempt to print the declarator
here because we do not have enough
information about its original syntactic
form. */
cp_parser_error (parser, "invalid declarator");
declarator = cp_error_declarator;
break;
}
}
if (class_type)
{
if (TREE_CODE (unqualified_name) == BIT_NOT_EXPR)
sfk = sfk_destructor;
else if (IDENTIFIER_TYPENAME_P (unqualified_name))
sfk = sfk_conversion;
else if (/* There's no way to declare a constructor
for an anonymous type, even if the type
got a name for linkage purposes. */
!TYPE_WAS_ANONYMOUS (class_type)
&& constructor_name_p (unqualified_name,
class_type))
{
unqualified_name = constructor_name (class_type);
sfk = sfk_constructor;
}
if (ctor_dtor_or_conv_p && sfk != sfk_none)
*ctor_dtor_or_conv_p = -1;
}
}
declarator = make_id_declarator (qualifying_scope,
unqualified_name,
sfk);
declarator->id_loc = token->location;
handle_declarator:;
scope = get_scope_of_declarator (declarator);
if (scope)
/* Any names that appear after the declarator-id for a
member are looked up in the containing scope. */
pushed_scope = push_scope (scope);
parser->in_declarator_p = true;
if ((ctor_dtor_or_conv_p && *ctor_dtor_or_conv_p)
|| (declarator && declarator->kind == cdk_id))
/* Default args are only allowed on function
declarations. */
parser->default_arg_ok_p = saved_default_arg_ok_p;
else
parser->default_arg_ok_p = false;
first = false;
}
/* We're done. */
else
break;
}
/* For an abstract declarator, we might wind up with nothing at this
point. That's an error; the declarator is not optional. */
/* APPLE LOCAL blocks 6339747 */
if (!declarator && dcl_kind != CP_PARSER_DECLARATOR_BLOCK)
cp_parser_error (parser, "expected declarator");
/* If we entered a scope, we must exit it now. */
if (pushed_scope)
pop_scope (pushed_scope);
parser->default_arg_ok_p = saved_default_arg_ok_p;
parser->in_declarator_p = saved_in_declarator_p;
return declarator;
}
/* Parse a ptr-operator.
ptr-operator:
* cv-qualifier-seq [opt]
&
:: [opt] nested-name-specifier * cv-qualifier-seq [opt]
GNU Extension:
ptr-operator:
& cv-qualifier-seq [opt]
APPLE LOCAL blocks 6040305 (cc)
^
Returns INDIRECT_REF if a pointer, or pointer-to-member, was used.
Returns ADDR_EXPR if a reference was used. In the case of a
pointer-to-member, *TYPE is filled in with the TYPE containing the
member. *CV_QUALS is filled in with the cv-qualifier-seq, or
TYPE_UNQUALIFIED, if there are no cv-qualifiers. Returns
ERROR_MARK if an error occurred. */
static enum tree_code
cp_parser_ptr_operator (cp_parser* parser,
tree* type,
cp_cv_quals *cv_quals)
{
enum tree_code code = ERROR_MARK;
cp_token *token;
/* Assume that it's not a pointer-to-member. */
*type = NULL_TREE;
/* And that there are no cv-qualifiers. */
*cv_quals = TYPE_UNQUALIFIED;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's a `*' or `&' we have a pointer or reference. */
if (token->type == CPP_MULT || token->type == CPP_AND)
{
/* Remember which ptr-operator we were processing. */
code = (token->type == CPP_AND ? ADDR_EXPR : INDIRECT_REF);
/* Consume the `*' or `&'. */
cp_lexer_consume_token (parser->lexer);
/* A `*' can be followed by a cv-qualifier-seq, and so can a
`&', if we are allowing GNU extensions. (The only qualifier
that can legally appear after `&' is `restrict', but that is
enforced during semantic analysis. */
if (code == INDIRECT_REF
|| cp_parser_allow_gnu_extensions_p (parser))
*cv_quals = cp_parser_cv_qualifier_seq_opt (parser);
}
else
{
/* Try the pointer-to-member case. */
cp_parser_parse_tentatively (parser);
/* Look for the optional `::' operator. */
cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false);
/* Look for the nested-name specifier. */
cp_parser_nested_name_specifier (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/true,
/*type_p=*/false,
/*is_declaration=*/false);
/* If we found it, and the next token is a `*', then we are
indeed looking at a pointer-to-member operator. */
if (!cp_parser_error_occurred (parser)
&& cp_parser_require (parser, CPP_MULT, "`*'"))
{
/* Indicate that the `*' operator was used. */
code = INDIRECT_REF;
if (TREE_CODE (parser->scope) == NAMESPACE_DECL)
error ("%qD is a namespace", parser->scope);
else
{
/* The type of which the member is a member is given by the
current SCOPE. */
*type = parser->scope;
/* The next name will not be qualified. */
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
/* Look for the optional cv-qualifier-seq. */
*cv_quals = cp_parser_cv_qualifier_seq_opt (parser);
}
}
/* If that didn't work we don't have a ptr-operator. */
if (!cp_parser_parse_definitely (parser))
cp_parser_error (parser, "expected ptr-operator");
}
return code;
}
/* Parse an (optional) cv-qualifier-seq.
cv-qualifier-seq:
cv-qualifier cv-qualifier-seq [opt]
cv-qualifier:
const
volatile
GNU Extension:
cv-qualifier:
__restrict__
Returns a bitmask representing the cv-qualifiers. */
static cp_cv_quals
cp_parser_cv_qualifier_seq_opt (cp_parser* parser)
{
cp_cv_quals cv_quals = TYPE_UNQUALIFIED;
while (true)
{
cp_token *token;
cp_cv_quals cv_qualifier;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* See if it's a cv-qualifier. */
switch (token->keyword)
{
case RID_CONST:
cv_qualifier = TYPE_QUAL_CONST;
break;
case RID_VOLATILE:
cv_qualifier = TYPE_QUAL_VOLATILE;
break;
case RID_RESTRICT:
cv_qualifier = TYPE_QUAL_RESTRICT;
break;
default:
cv_qualifier = TYPE_UNQUALIFIED;
break;
}
if (!cv_qualifier)
break;
if (cv_quals & cv_qualifier)
{
error ("duplicate cv-qualifier");
cp_lexer_purge_token (parser->lexer);
}
else
{
cp_lexer_consume_token (parser->lexer);
cv_quals |= cv_qualifier;
}
}
return cv_quals;
}
/* Parse a declarator-id.
declarator-id:
id-expression
:: [opt] nested-name-specifier [opt] type-name
In the `id-expression' case, the value returned is as for
cp_parser_id_expression if the id-expression was an unqualified-id.
If the id-expression was a qualified-id, then a SCOPE_REF is
returned. The first operand is the scope (either a NAMESPACE_DECL
or TREE_TYPE), but the second is still just a representation of an
unqualified-id. */
static tree
cp_parser_declarator_id (cp_parser* parser, bool optional_p)
{
tree id;
/* The expression must be an id-expression. Assume that qualified
names are the names of types so that:
template <class T>
int S<T>::R::i = 3;
will work; we must treat `S<T>::R' as the name of a type.
Similarly, assume that qualified names are templates, where
required, so that:
template <class T>
int S<T>::R<T>::i = 3;
will work, too. */
id = cp_parser_id_expression (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/false,
/*template_p=*/NULL,
/*declarator_p=*/true,
optional_p);
if (id && BASELINK_P (id))
id = BASELINK_FUNCTIONS (id);
return id;
}
/* Parse a type-id.
type-id:
type-specifier-seq abstract-declarator [opt]
Returns the TYPE specified. */
static tree
cp_parser_type_id (cp_parser* parser)
{
cp_decl_specifier_seq type_specifier_seq;
cp_declarator *abstract_declarator;
/* Parse the type-specifier-seq. */
cp_parser_type_specifier_seq (parser, /*is_condition=*/false,
&type_specifier_seq);
if (type_specifier_seq.type == error_mark_node)
return error_mark_node;
/* There might or might not be an abstract declarator. */
cp_parser_parse_tentatively (parser);
/* Look for the declarator. */
abstract_declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_ABSTRACT, NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
/* Check to see if there really was a declarator. */
if (!cp_parser_parse_definitely (parser))
abstract_declarator = NULL;
return groktypename (&type_specifier_seq, abstract_declarator);
}
/* Parse a type-specifier-seq.
type-specifier-seq:
type-specifier type-specifier-seq [opt]
GNU extension:
type-specifier-seq:
attributes type-specifier-seq [opt]
If IS_CONDITION is true, we are at the start of a "condition",
e.g., we've just seen "if (".
Sets *TYPE_SPECIFIER_SEQ to represent the sequence. */
static void
cp_parser_type_specifier_seq (cp_parser* parser,
bool is_condition,
cp_decl_specifier_seq *type_specifier_seq)
{
bool seen_type_specifier = false;
cp_parser_flags flags = CP_PARSER_FLAGS_OPTIONAL;
/* Clear the TYPE_SPECIFIER_SEQ. */
clear_decl_specs (type_specifier_seq);
/* Parse the type-specifiers and attributes. */
while (true)
{
tree type_specifier;
bool is_cv_qualifier;
/* Check for attributes first. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_ATTRIBUTE))
{
type_specifier_seq->attributes =
chainon (type_specifier_seq->attributes,
cp_parser_attributes_opt (parser));
continue;
}
/* Look for the type-specifier. */
type_specifier = cp_parser_type_specifier (parser,
flags,
type_specifier_seq,
/*is_declaration=*/false,
NULL,
&is_cv_qualifier);
if (!type_specifier)
{
/* If the first type-specifier could not be found, this is not a
type-specifier-seq at all. */
if (!seen_type_specifier)
{
cp_parser_error (parser, "expected type-specifier");
type_specifier_seq->type = error_mark_node;
return;
}
/* If subsequent type-specifiers could not be found, the
type-specifier-seq is complete. */
break;
}
seen_type_specifier = true;
/* The standard says that a condition can be:
type-specifier-seq declarator = assignment-expression
However, given:
struct S {};
if (int S = ...)
we should treat the "S" as a declarator, not as a
type-specifier. The standard doesn't say that explicitly for
type-specifier-seq, but it does say that for
decl-specifier-seq in an ordinary declaration. Perhaps it
would be clearer just to allow a decl-specifier-seq here, and
then add a semantic restriction that if any decl-specifiers
that are not type-specifiers appear, the program is invalid. */
if (is_condition && !is_cv_qualifier)
flags |= CP_PARSER_FLAGS_NO_USER_DEFINED_TYPES;
}
cp_parser_check_decl_spec (type_specifier_seq);
}
/* Parse a parameter-declaration-clause.
parameter-declaration-clause:
parameter-declaration-list [opt] ... [opt]
parameter-declaration-list , ...
Returns a representation for the parameter declarations. A return
value of NULL indicates a parameter-declaration-clause consisting
only of an ellipsis. */
static cp_parameter_declarator *
cp_parser_parameter_declaration_clause (cp_parser* parser)
{
cp_parameter_declarator *parameters;
cp_token *token;
bool ellipsis_p;
bool is_error;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Check for trivial parameter-declaration-clauses. */
if (token->type == CPP_ELLIPSIS)
{
/* Consume the `...' token. */
cp_lexer_consume_token (parser->lexer);
return NULL;
}
else if (token->type == CPP_CLOSE_PAREN)
/* There are no parameters. */
{
#ifndef NO_IMPLICIT_EXTERN_C
if (in_system_header && current_class_type == NULL
&& current_lang_name == lang_name_c)
return NULL;
else
#endif
return no_parameters;
}
/* Check for `(void)', too, which is a special case. */
else if (token->keyword == RID_VOID
&& (cp_lexer_peek_nth_token (parser->lexer, 2)->type
== CPP_CLOSE_PAREN))
{
/* Consume the `void' token. */
cp_lexer_consume_token (parser->lexer);
/* There are no parameters. */
return no_parameters;
}
/* Parse the parameter-declaration-list. */
parameters = cp_parser_parameter_declaration_list (parser, &is_error);
/* If a parse error occurred while parsing the
parameter-declaration-list, then the entire
parameter-declaration-clause is erroneous. */
if (is_error)
return NULL;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's a `,', the clause should terminate with an ellipsis. */
if (token->type == CPP_COMMA)
{
/* Consume the `,'. */
cp_lexer_consume_token (parser->lexer);
/* Expect an ellipsis. */
ellipsis_p
= (cp_parser_require (parser, CPP_ELLIPSIS, "`...'") != NULL);
}
/* It might also be `...' if the optional trailing `,' was
omitted. */
else if (token->type == CPP_ELLIPSIS)
{
/* Consume the `...' token. */
cp_lexer_consume_token (parser->lexer);
/* And remember that we saw it. */
ellipsis_p = true;
}
else
ellipsis_p = false;
/* Finish the parameter list. */
if (parameters && ellipsis_p)
parameters->ellipsis_p = true;
return parameters;
}
/* Parse a parameter-declaration-list.
parameter-declaration-list:
parameter-declaration
parameter-declaration-list , parameter-declaration
Returns a representation of the parameter-declaration-list, as for
cp_parser_parameter_declaration_clause. However, the
`void_list_node' is never appended to the list. Upon return,
*IS_ERROR will be true iff an error occurred. */
static cp_parameter_declarator *
cp_parser_parameter_declaration_list (cp_parser* parser, bool *is_error)
{
cp_parameter_declarator *parameters = NULL;
cp_parameter_declarator **tail = ¶meters;
bool saved_in_unbraced_linkage_specification_p;
/* Assume all will go well. */
*is_error = false;
/* The special considerations that apply to a function within an
unbraced linkage specifications do not apply to the parameters
to the function. */
saved_in_unbraced_linkage_specification_p
= parser->in_unbraced_linkage_specification_p;
parser->in_unbraced_linkage_specification_p = false;
/* Look for more parameters. */
while (true)
{
cp_parameter_declarator *parameter;
bool parenthesized_p;
/* Parse the parameter. */
parameter
= cp_parser_parameter_declaration (parser,
/*template_parm_p=*/false,
&parenthesized_p);
/* If a parse error occurred parsing the parameter declaration,
then the entire parameter-declaration-list is erroneous. */
if (!parameter)
{
*is_error = true;
parameters = NULL;
break;
}
/* Add the new parameter to the list. */
*tail = parameter;
tail = ¶meter->next;
/* Peek at the next token. */
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_PAREN)
|| cp_lexer_next_token_is (parser->lexer, CPP_ELLIPSIS)
/* These are for Objective-C++ */
|| cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)
|| cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
/* The parameter-declaration-list is complete. */
break;
else if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
{
cp_token *token;
/* Peek at the next token. */
token = cp_lexer_peek_nth_token (parser->lexer, 2);
/* If it's an ellipsis, then the list is complete. */
if (token->type == CPP_ELLIPSIS)
break;
/* Otherwise, there must be more parameters. Consume the
`,'. */
cp_lexer_consume_token (parser->lexer);
/* When parsing something like:
int i(float f, double d)
we can tell after seeing the declaration for "f" that we
are not looking at an initialization of a variable "i",
but rather at the declaration of a function "i".
Due to the fact that the parsing of template arguments
(as specified to a template-id) requires backtracking we
cannot use this technique when inside a template argument
list. */
if (!parser->in_template_argument_list_p
&& !parser->in_type_id_in_expr_p
&& cp_parser_uncommitted_to_tentative_parse_p (parser)
/* However, a parameter-declaration of the form
"foat(f)" (which is a valid declaration of a
parameter "f") can also be interpreted as an
expression (the conversion of "f" to "float"). */
&& !parenthesized_p)
cp_parser_commit_to_tentative_parse (parser);
}
else
{
cp_parser_error (parser, "expected %<,%> or %<...%>");
if (!cp_parser_uncommitted_to_tentative_parse_p (parser))
cp_parser_skip_to_closing_parenthesis (parser,
/*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/false);
break;
}
}
parser->in_unbraced_linkage_specification_p
= saved_in_unbraced_linkage_specification_p;
return parameters;
}
/* Parse a parameter declaration.
parameter-declaration:
decl-specifier-seq declarator
decl-specifier-seq declarator = assignment-expression
decl-specifier-seq abstract-declarator [opt]
decl-specifier-seq abstract-declarator [opt] = assignment-expression
If TEMPLATE_PARM_P is TRUE, then this parameter-declaration
declares a template parameter. (In that case, a non-nested `>'
token encountered during the parsing of the assignment-expression
is not interpreted as a greater-than operator.)
Returns a representation of the parameter, or NULL if an error
occurs. If PARENTHESIZED_P is non-NULL, *PARENTHESIZED_P is set to
true iff the declarator is of the form "(p)". */
static cp_parameter_declarator *
cp_parser_parameter_declaration (cp_parser *parser,
bool template_parm_p,
bool *parenthesized_p)
{
int declares_class_or_enum;
bool greater_than_is_operator_p;
cp_decl_specifier_seq decl_specifiers;
cp_declarator *declarator;
tree default_argument;
cp_token *token;
const char *saved_message;
/* In a template parameter, `>' is not an operator.
[temp.param]
When parsing a default template-argument for a non-type
template-parameter, the first non-nested `>' is taken as the end
of the template parameter-list rather than a greater-than
operator. */
greater_than_is_operator_p = !template_parm_p;
/* Type definitions may not appear in parameter types. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in parameter types";
/* Parse the declaration-specifiers. */
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_NONE,
&decl_specifiers,
&declares_class_or_enum);
/* If an error occurred, there's no reason to attempt to parse the
rest of the declaration. */
if (cp_parser_error_occurred (parser))
{
parser->type_definition_forbidden_message = saved_message;
return NULL;
}
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If the next token is a `)', `,', `=', `>', or `...', then there
is no declarator. */
if (token->type == CPP_CLOSE_PAREN
|| token->type == CPP_COMMA
|| token->type == CPP_EQ
|| token->type == CPP_ELLIPSIS
|| token->type == CPP_GREATER)
{
declarator = NULL;
if (parenthesized_p)
*parenthesized_p = false;
}
/* Otherwise, there should be a declarator. */
else
{
bool saved_default_arg_ok_p = parser->default_arg_ok_p;
parser->default_arg_ok_p = false;
/* After seeing a decl-specifier-seq, if the next token is not a
"(", there is no possibility that the code is a valid
expression. Therefore, if parsing tentatively, we commit at
this point. */
if (!parser->in_template_argument_list_p
/* In an expression context, having seen:
(int((char ...
we cannot be sure whether we are looking at a
function-type (taking a "char" as a parameter) or a cast
of some object of type "char" to "int". */
&& !parser->in_type_id_in_expr_p
&& cp_parser_uncommitted_to_tentative_parse_p (parser)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_PAREN))
cp_parser_commit_to_tentative_parse (parser);
/* Parse the declarator. */
declarator = cp_parser_declarator (parser,
CP_PARSER_DECLARATOR_EITHER,
/*ctor_dtor_or_conv_p=*/NULL,
parenthesized_p,
/*member_p=*/false);
parser->default_arg_ok_p = saved_default_arg_ok_p;
/* After the declarator, allow more attributes. */
decl_specifiers.attributes
= chainon (decl_specifiers.attributes,
cp_parser_attributes_opt (parser));
}
/* The restriction on defining new types applies only to the type
of the parameter, not to the default argument. */
parser->type_definition_forbidden_message = saved_message;
/* If the next token is `=', then process a default argument. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EQ))
{
bool saved_greater_than_is_operator_p;
/* Consume the `='. */
cp_lexer_consume_token (parser->lexer);
/* If we are defining a class, then the tokens that make up the
default argument must be saved and processed later. */
if (!template_parm_p && at_class_scope_p ()
&& TYPE_BEING_DEFINED (current_class_type))
{
unsigned depth = 0;
cp_token *first_token;
cp_token *token;
/* Add tokens until we have processed the entire default
argument. We add the range [first_token, token). */
first_token = cp_lexer_peek_token (parser->lexer);
while (true)
{
bool done = false;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* What we do depends on what token we have. */
switch (token->type)
{
/* In valid code, a default argument must be
immediately followed by a `,' `)', or `...'. */
case CPP_COMMA:
case CPP_CLOSE_PAREN:
case CPP_ELLIPSIS:
/* If we run into a non-nested `;', `}', or `]',
then the code is invalid -- but the default
argument is certainly over. */
case CPP_SEMICOLON:
case CPP_CLOSE_BRACE:
case CPP_CLOSE_SQUARE:
if (depth == 0)
done = true;
/* Update DEPTH, if necessary. */
else if (token->type == CPP_CLOSE_PAREN
|| token->type == CPP_CLOSE_BRACE
|| token->type == CPP_CLOSE_SQUARE)
--depth;
break;
case CPP_OPEN_PAREN:
case CPP_OPEN_SQUARE:
case CPP_OPEN_BRACE:
++depth;
break;
case CPP_GREATER:
/* If we see a non-nested `>', and `>' is not an
operator, then it marks the end of the default
argument. */
if (!depth && !greater_than_is_operator_p)
done = true;
break;
/* If we run out of tokens, issue an error message. */
case CPP_EOF:
case CPP_PRAGMA_EOL:
error ("file ends in default argument");
done = true;
break;
case CPP_NAME:
case CPP_SCOPE:
/* In these cases, we should look for template-ids.
For example, if the default argument is
`X<int, double>()', we need to do name lookup to
figure out whether or not `X' is a template; if
so, the `,' does not end the default argument.
That is not yet done. */
break;
default:
break;
}
/* If we've reached the end, stop. */
if (done)
break;
/* Add the token to the token block. */
token = cp_lexer_consume_token (parser->lexer);
}
/* Create a DEFAULT_ARG to represented the unparsed default
argument. */
default_argument = make_node (DEFAULT_ARG);
DEFARG_TOKENS (default_argument)
= cp_token_cache_new (first_token, token);
DEFARG_INSTANTIATIONS (default_argument) = NULL;
}
/* Outside of a class definition, we can just parse the
assignment-expression. */
else
{
bool saved_local_variables_forbidden_p;
/* Make sure that PARSER->GREATER_THAN_IS_OPERATOR_P is
set correctly. */
saved_greater_than_is_operator_p
= parser->greater_than_is_operator_p;
parser->greater_than_is_operator_p = greater_than_is_operator_p;
/* Local variable names (and the `this' keyword) may not
appear in a default argument. */
saved_local_variables_forbidden_p
= parser->local_variables_forbidden_p;
parser->local_variables_forbidden_p = true;
/* The default argument expression may cause implicitly
defined member functions to be synthesized, which will
result in garbage collection. We must treat this
situation as if we were within the body of function so as
to avoid collecting live data on the stack. */
++function_depth;
/* Parse the assignment-expression. */
if (template_parm_p)
push_deferring_access_checks (dk_no_deferred);
default_argument
= cp_parser_assignment_expression (parser, /*cast_p=*/false);
if (template_parm_p)
pop_deferring_access_checks ();
/* Restore saved state. */
--function_depth;
parser->greater_than_is_operator_p
= saved_greater_than_is_operator_p;
parser->local_variables_forbidden_p
= saved_local_variables_forbidden_p;
}
if (!parser->default_arg_ok_p)
{
if (!flag_pedantic_errors)
warning (0, "deprecated use of default argument for parameter of non-function");
else
{
error ("default arguments are only permitted for function parameters");
default_argument = NULL_TREE;
}
}
}
else
default_argument = NULL_TREE;
return make_parameter_declarator (&decl_specifiers,
declarator,
default_argument);
}
/* Parse a function-body.
function-body:
compound_statement */
static void
cp_parser_function_body (cp_parser *parser)
{
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, false, false);
}
/* Parse a ctor-initializer-opt followed by a function-body. Return
true if a ctor-initializer was present. */
static bool
cp_parser_ctor_initializer_opt_and_function_body (cp_parser *parser)
{
tree body;
bool ctor_initializer_p;
/* Begin the function body. */
body = begin_function_body ();
/* Parse the optional ctor-initializer. */
ctor_initializer_p = cp_parser_ctor_initializer_opt (parser);
/* Parse the function-body. */
cp_parser_function_body (parser);
/* Finish the function body. */
finish_function_body (body);
return ctor_initializer_p;
}
/* Parse an initializer.
initializer:
= initializer-clause
( expression-list )
Returns an expression representing the initializer. If no
initializer is present, NULL_TREE is returned.
*IS_PARENTHESIZED_INIT is set to TRUE if the `( expression-list )'
production is used, and zero otherwise. *IS_PARENTHESIZED_INIT is
set to FALSE if there is no initializer present. If there is an
initializer, and it is not a constant-expression, *NON_CONSTANT_P
is set to true; otherwise it is set to false. */
static tree
cp_parser_initializer (cp_parser* parser, bool* is_parenthesized_init,
bool* non_constant_p)
{
cp_token *token;
tree init;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Let our caller know whether or not this initializer was
parenthesized. */
*is_parenthesized_init = (token->type == CPP_OPEN_PAREN);
/* Assume that the initializer is constant. */
*non_constant_p = false;
if (token->type == CPP_EQ)
{
/* Consume the `='. */
cp_lexer_consume_token (parser->lexer);
/* Parse the initializer-clause. */
init = cp_parser_initializer_clause (parser, non_constant_p);
}
else if (token->type == CPP_OPEN_PAREN)
init = cp_parser_parenthesized_expression_list (parser, false,
/*cast_p=*/false,
non_constant_p);
else
{
/* Anything else is an error. */
cp_parser_error (parser, "expected initializer");
init = error_mark_node;
}
return init;
}
/* Parse an initializer-clause.
initializer-clause:
assignment-expression
{ initializer-list , [opt] }
{ }
Returns an expression representing the initializer.
If the `assignment-expression' production is used the value
returned is simply a representation for the expression.
Otherwise, a CONSTRUCTOR is returned. The CONSTRUCTOR_ELTS will be
the elements of the initializer-list (or NULL, if the last
production is used). The TREE_TYPE for the CONSTRUCTOR will be
NULL_TREE. There is no way to detect whether or not the optional
trailing `,' was provided. NON_CONSTANT_P is as for
cp_parser_initializer. */
static tree
cp_parser_initializer_clause (cp_parser* parser, bool* non_constant_p)
{
tree initializer;
/* Assume the expression is constant. */
*non_constant_p = false;
/* If it is not a `{', then we are looking at an
assignment-expression. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_BRACE))
{
initializer
= cp_parser_constant_expression (parser,
/*allow_non_constant_p=*/true,
non_constant_p);
if (!*non_constant_p)
initializer = fold_non_dependent_expr (initializer);
}
else
{
/* Consume the `{' token. */
cp_lexer_consume_token (parser->lexer);
/* Create a CONSTRUCTOR to represent the braced-initializer. */
initializer = make_node (CONSTRUCTOR);
/* If it's not a `}', then there is a non-trivial initializer. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_BRACE))
{
/* Parse the initializer list. */
CONSTRUCTOR_ELTS (initializer)
= cp_parser_initializer_list (parser, non_constant_p);
/* A trailing `,' token is allowed. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
cp_lexer_consume_token (parser->lexer);
}
/* Now, there should be a trailing `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
}
return initializer;
}
/* Parse an initializer-list.
initializer-list:
initializer-clause
initializer-list , initializer-clause
GNU Extension:
initializer-list:
identifier : initializer-clause
initializer-list, identifier : initializer-clause
Returns a VEC of constructor_elt. The VALUE of each elt is an expression
for the initializer. If the INDEX of the elt is non-NULL, it is the
IDENTIFIER_NODE naming the field to initialize. NON_CONSTANT_P is
as for cp_parser_initializer. */
static VEC(constructor_elt,gc) *
cp_parser_initializer_list (cp_parser* parser, bool* non_constant_p)
{
VEC(constructor_elt,gc) *v = NULL;
/* Assume all of the expressions are constant. */
*non_constant_p = false;
/* Parse the rest of the list. */
while (true)
{
cp_token *token;
tree identifier;
tree initializer;
bool clause_non_constant_p;
/* If the next token is an identifier and the following one is a
colon, we are looking at the GNU designated-initializer
syntax. */
if (cp_parser_allow_gnu_extensions_p (parser)
&& cp_lexer_next_token_is (parser->lexer, CPP_NAME)
&& cp_lexer_peek_nth_token (parser->lexer, 2)->type == CPP_COLON)
{
/* Warn the user that they are using an extension. */
if (pedantic)
pedwarn ("ISO C++ does not allow designated initializers");
/* Consume the identifier. */
identifier = cp_lexer_consume_token (parser->lexer)->u.value;
/* Consume the `:'. */
cp_lexer_consume_token (parser->lexer);
}
else
identifier = NULL_TREE;
/* Parse the initializer. */
initializer = cp_parser_initializer_clause (parser,
&clause_non_constant_p);
/* If any clause is non-constant, so is the entire initializer. */
if (clause_non_constant_p)
*non_constant_p = true;
/* Add it to the vector. */
CONSTRUCTOR_APPEND_ELT(v, identifier, initializer);
/* If the next token is not a comma, we have reached the end of
the list. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Peek at the next token. */
token = cp_lexer_peek_nth_token (parser->lexer, 2);
/* If the next token is a `}', then we're still done. An
initializer-clause can have a trailing `,' after the
initializer-list and before the closing `}'. */
if (token->type == CPP_CLOSE_BRACE)
break;
/* Consume the `,' token. */
cp_lexer_consume_token (parser->lexer);
}
return v;
}
/* Classes [gram.class] */
/* Parse a class-name.
class-name:
identifier
template-id
TYPENAME_KEYWORD_P is true iff the `typename' keyword has been used
to indicate that names looked up in dependent types should be
assumed to be types. TEMPLATE_KEYWORD_P is true iff the `template'
keyword has been used to indicate that the name that appears next
is a template. TAG_TYPE indicates the explicit tag given before
the type name, if any. If CHECK_DEPENDENCY_P is FALSE, names are
looked up in dependent scopes. If CLASS_HEAD_P is TRUE, this class
is the class being defined in a class-head.
Returns the TYPE_DECL representing the class. */
static tree
cp_parser_class_name (cp_parser *parser,
bool typename_keyword_p,
bool template_keyword_p,
enum tag_types tag_type,
bool check_dependency_p,
bool class_head_p,
bool is_declaration)
{
tree decl;
tree scope;
bool typename_p;
cp_token *token;
/* All class-names start with an identifier. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type != CPP_NAME && token->type != CPP_TEMPLATE_ID)
{
cp_parser_error (parser, "expected class-name");
return error_mark_node;
}
/* PARSER->SCOPE can be cleared when parsing the template-arguments
to a template-id, so we save it here. */
scope = parser->scope;
if (scope == error_mark_node)
return error_mark_node;
/* Any name names a type if we're following the `typename' keyword
in a qualified name where the enclosing scope is type-dependent. */
typename_p = (typename_keyword_p && scope && TYPE_P (scope)
&& dependent_type_p (scope));
/* Handle the common case (an identifier, but not a template-id)
efficiently. */
if (token->type == CPP_NAME
&& !cp_parser_nth_token_starts_template_argument_list_p (parser, 2))
{
cp_token *identifier_token;
tree identifier;
bool ambiguous_p;
/* Look for the identifier. */
identifier_token = cp_lexer_peek_token (parser->lexer);
ambiguous_p = identifier_token->ambiguous_p;
identifier = cp_parser_identifier (parser);
/* If the next token isn't an identifier, we are certainly not
looking at a class-name. */
if (identifier == error_mark_node)
decl = error_mark_node;
/* If we know this is a type-name, there's no need to look it
up. */
else if (typename_p)
decl = identifier;
else
{
tree ambiguous_decls;
/* If we already know that this lookup is ambiguous, then
we've already issued an error message; there's no reason
to check again. */
if (ambiguous_p)
{
cp_parser_simulate_error (parser);
return error_mark_node;
}
/* If the next token is a `::', then the name must be a type
name.
[basic.lookup.qual]
During the lookup for a name preceding the :: scope
resolution operator, object, function, and enumerator
names are ignored. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SCOPE))
tag_type = typename_type;
/* Look up the name. */
decl = cp_parser_lookup_name (parser, identifier,
tag_type,
/*is_template=*/false,
/*is_namespace=*/false,
check_dependency_p,
&ambiguous_decls);
if (ambiguous_decls)
{
error ("reference to %qD is ambiguous", identifier);
print_candidates (ambiguous_decls);
if (cp_parser_parsing_tentatively (parser))
{
identifier_token->ambiguous_p = true;
cp_parser_simulate_error (parser);
}
return error_mark_node;
}
}
}
else
{
/* Try a template-id. */
decl = cp_parser_template_id (parser, template_keyword_p,
check_dependency_p,
is_declaration);
if (decl == error_mark_node)
return error_mark_node;
}
decl = cp_parser_maybe_treat_template_as_class (decl, class_head_p);
/* If this is a typename, create a TYPENAME_TYPE. */
if (typename_p && decl != error_mark_node)
{
decl = make_typename_type (scope, decl, typename_type,
/*complain=*/tf_error);
if (decl != error_mark_node)
decl = TYPE_NAME (decl);
}
/* Check to see that it is really the name of a class. */
if (TREE_CODE (decl) == TEMPLATE_ID_EXPR
&& TREE_CODE (TREE_OPERAND (decl, 0)) == IDENTIFIER_NODE
&& cp_lexer_next_token_is (parser->lexer, CPP_SCOPE))
/* Situations like this:
template <typename T> struct A {
typename T::template X<int>::I i;
};
are problematic. Is `T::template X<int>' a class-name? The
standard does not seem to be definitive, but there is no other
valid interpretation of the following `::'. Therefore, those
names are considered class-names. */
{
decl = make_typename_type (scope, decl, tag_type, tf_error);
if (decl != error_mark_node)
decl = TYPE_NAME (decl);
}
else if (TREE_CODE (decl) != TYPE_DECL
|| TREE_TYPE (decl) == error_mark_node
/* APPLE LOCAL begin radar 5277239 */
|| !IS_AGGR_TYPE (TREE_TYPE (decl))
|| cp_objc_property_reference_prefix (parser, TREE_TYPE (decl)))
/* APPLE LOCAL end radar 5277239 */
decl = error_mark_node;
if (decl == error_mark_node)
cp_parser_error (parser, "expected class-name");
return decl;
}
/* Parse a class-specifier.
class-specifier:
class-head { member-specification [opt] }
Returns the TREE_TYPE representing the class. */
static tree
cp_parser_class_specifier (cp_parser* parser)
{
cp_token *token;
tree type;
tree attributes = NULL_TREE;
int has_trailing_semicolon;
bool nested_name_specifier_p;
unsigned saved_num_template_parameter_lists;
bool saved_in_function_body;
tree old_scope = NULL_TREE;
tree scope = NULL_TREE;
tree bases;
push_deferring_access_checks (dk_no_deferred);
/* Parse the class-head. */
type = cp_parser_class_head (parser,
&nested_name_specifier_p,
&attributes,
&bases);
/* If the class-head was a semantic disaster, skip the entire body
of the class. */
if (!type)
{
cp_parser_skip_to_end_of_block_or_statement (parser);
pop_deferring_access_checks ();
return error_mark_node;
}
/* Look for the `{'. */
if (!cp_parser_require (parser, CPP_OPEN_BRACE, "`{'"))
{
pop_deferring_access_checks ();
return error_mark_node;
}
/* Process the base classes. If they're invalid, skip the
entire class body. */
if (!xref_basetypes (type, bases))
{
cp_parser_skip_to_closing_brace (parser);
/* Consuming the closing brace yields better error messages
later on. */
cp_lexer_consume_token (parser->lexer);
pop_deferring_access_checks ();
return error_mark_node;
}
/* Issue an error message if type-definitions are forbidden here. */
cp_parser_check_type_definition (parser);
/* Remember that we are defining one more class. */
++parser->num_classes_being_defined;
/* Inside the class, surrounding template-parameter-lists do not
apply. */
saved_num_template_parameter_lists
= parser->num_template_parameter_lists;
parser->num_template_parameter_lists = 0;
/* We are not in a function body. */
saved_in_function_body = parser->in_function_body;
parser->in_function_body = false;
/* Start the class. */
if (nested_name_specifier_p)
{
scope = CP_DECL_CONTEXT (TYPE_MAIN_DECL (type));
old_scope = push_inner_scope (scope);
}
type = begin_class_definition (type, attributes);
if (type == error_mark_node)
/* If the type is erroneous, skip the entire body of the class. */
cp_parser_skip_to_closing_brace (parser);
else
/* Parse the member-specification. */
cp_parser_member_specification_opt (parser);
/* Look for the trailing `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
/* We get better error messages by noticing a common problem: a
missing trailing `;'. */
token = cp_lexer_peek_token (parser->lexer);
has_trailing_semicolon = (token->type == CPP_SEMICOLON);
/* Look for trailing attributes to apply to this class. */
if (cp_parser_allow_gnu_extensions_p (parser))
attributes = cp_parser_attributes_opt (parser);
if (type != error_mark_node)
type = finish_struct (type, attributes);
if (nested_name_specifier_p)
pop_inner_scope (old_scope, scope);
/* If this class is not itself within the scope of another class,
then we need to parse the bodies of all of the queued function
definitions. Note that the queued functions defined in a class
are not always processed immediately following the
class-specifier for that class. Consider:
struct A {
struct B { void f() { sizeof (A); } };
};
If `f' were processed before the processing of `A' were
completed, there would be no way to compute the size of `A'.
Note that the nesting we are interested in here is lexical --
not the semantic nesting given by TYPE_CONTEXT. In particular,
for:
struct A { struct B; };
struct A::B { void f() { } };
there is no need to delay the parsing of `A::B::f'. */
if (--parser->num_classes_being_defined == 0)
{
tree queue_entry;
tree fn;
tree class_type = NULL_TREE;
tree pushed_scope = NULL_TREE;
/* In a first pass, parse default arguments to the functions.
Then, in a second pass, parse the bodies of the functions.
This two-phased approach handles cases like:
struct S {
void f() { g(); }
void g(int i = 3);
};
*/
for (TREE_PURPOSE (parser->unparsed_functions_queues)
= nreverse (TREE_PURPOSE (parser->unparsed_functions_queues));
(queue_entry = TREE_PURPOSE (parser->unparsed_functions_queues));
TREE_PURPOSE (parser->unparsed_functions_queues)
= TREE_CHAIN (TREE_PURPOSE (parser->unparsed_functions_queues)))
{
fn = TREE_VALUE (queue_entry);
/* If there are default arguments that have not yet been processed,
take care of them now. */
if (class_type != TREE_PURPOSE (queue_entry))
{
if (pushed_scope)
pop_scope (pushed_scope);
class_type = TREE_PURPOSE (queue_entry);
pushed_scope = push_scope (class_type);
}
/* Make sure that any template parameters are in scope. */
maybe_begin_member_template_processing (fn);
/* Parse the default argument expressions. */
cp_parser_late_parsing_default_args (parser, fn);
/* Remove any template parameters from the symbol table. */
maybe_end_member_template_processing ();
}
if (pushed_scope)
pop_scope (pushed_scope);
/* Now parse the body of the functions. */
for (TREE_VALUE (parser->unparsed_functions_queues)
= nreverse (TREE_VALUE (parser->unparsed_functions_queues));
(queue_entry = TREE_VALUE (parser->unparsed_functions_queues));
TREE_VALUE (parser->unparsed_functions_queues)
= TREE_CHAIN (TREE_VALUE (parser->unparsed_functions_queues)))
{
/* Figure out which function we need to process. */
fn = TREE_VALUE (queue_entry);
/* Parse the function. */
cp_parser_late_parsing_for_member (parser, fn);
}
}
/* Put back any saved access checks. */
pop_deferring_access_checks ();
/* Restore saved state. */
parser->in_function_body = saved_in_function_body;
parser->num_template_parameter_lists
= saved_num_template_parameter_lists;
return type;
}
/* Parse a class-head.
class-head:
class-key identifier [opt] base-clause [opt]
class-key nested-name-specifier identifier base-clause [opt]
class-key nested-name-specifier [opt] template-id
base-clause [opt]
GNU Extensions:
class-key attributes identifier [opt] base-clause [opt]
class-key attributes nested-name-specifier identifier base-clause [opt]
class-key attributes nested-name-specifier [opt] template-id
base-clause [opt]
Returns the TYPE of the indicated class. Sets
*NESTED_NAME_SPECIFIER_P to TRUE iff one of the productions
involving a nested-name-specifier was used, and FALSE otherwise.
Returns error_mark_node if this is not a class-head.
Returns NULL_TREE if the class-head is syntactically valid, but
semantically invalid in a way that means we should skip the entire
body of the class. */
static tree
cp_parser_class_head (cp_parser* parser,
bool* nested_name_specifier_p,
tree *attributes_p,
tree *bases)
{
tree nested_name_specifier;
enum tag_types class_key;
tree id = NULL_TREE;
tree type = NULL_TREE;
tree attributes;
bool template_id_p = false;
bool qualified_p = false;
bool invalid_nested_name_p = false;
bool invalid_explicit_specialization_p = false;
tree pushed_scope = NULL_TREE;
unsigned num_templates;
/* Assume no nested-name-specifier will be present. */
*nested_name_specifier_p = false;
/* Assume no template parameter lists will be used in defining the
type. */
num_templates = 0;
/* Look for the class-key. */
class_key = cp_parser_class_key (parser);
if (class_key == none_type)
return error_mark_node;
/* Parse the attributes. */
attributes = cp_parser_attributes_opt (parser);
/* If the next token is `::', that is invalid -- but sometimes
people do try to write:
struct ::S {};
Handle this gracefully by accepting the extra qualifier, and then
issuing an error about it later if this really is a
class-head. If it turns out just to be an elaborated type
specifier, remain silent. */
if (cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false))
qualified_p = true;
push_deferring_access_checks (dk_no_check);
/* Determine the name of the class. Begin by looking for an
optional nested-name-specifier. */
nested_name_specifier
= cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/false,
/*type_p=*/false,
/*is_declaration=*/false);
/* If there was a nested-name-specifier, then there *must* be an
identifier. */
if (nested_name_specifier)
{
/* Although the grammar says `identifier', it really means
`class-name' or `template-name'. You are only allowed to
define a class that has already been declared with this
syntax.
The proposed resolution for Core Issue 180 says that wherever
you see `class T::X' you should treat `X' as a type-name.
It is OK to define an inaccessible class; for example:
class A { class B; };
class A::B {};
We do not know if we will see a class-name, or a
template-name. We look for a class-name first, in case the
class-name is a template-id; if we looked for the
template-name first we would stop after the template-name. */
cp_parser_parse_tentatively (parser);
type = cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
class_type,
/*check_dependency_p=*/false,
/*class_head_p=*/true,
/*is_declaration=*/false);
/* If that didn't work, ignore the nested-name-specifier. */
if (!cp_parser_parse_definitely (parser))
{
invalid_nested_name_p = true;
id = cp_parser_identifier (parser);
if (id == error_mark_node)
id = NULL_TREE;
}
/* If we could not find a corresponding TYPE, treat this
declaration like an unqualified declaration. */
if (type == error_mark_node)
nested_name_specifier = NULL_TREE;
/* Otherwise, count the number of templates used in TYPE and its
containing scopes. */
else
{
tree scope;
for (scope = TREE_TYPE (type);
scope && TREE_CODE (scope) != NAMESPACE_DECL;
scope = (TYPE_P (scope)
? TYPE_CONTEXT (scope)
: DECL_CONTEXT (scope)))
if (TYPE_P (scope)
&& CLASS_TYPE_P (scope)
&& CLASSTYPE_TEMPLATE_INFO (scope)
&& PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope))
&& !CLASSTYPE_TEMPLATE_SPECIALIZATION (scope))
++num_templates;
}
}
/* Otherwise, the identifier is optional. */
else
{
/* We don't know whether what comes next is a template-id,
an identifier, or nothing at all. */
cp_parser_parse_tentatively (parser);
/* Check for a template-id. */
id = cp_parser_template_id (parser,
/*template_keyword_p=*/false,
/*check_dependency_p=*/true,
/*is_declaration=*/true);
/* If that didn't work, it could still be an identifier. */
if (!cp_parser_parse_definitely (parser))
{
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
id = cp_parser_identifier (parser);
else
id = NULL_TREE;
}
else
{
template_id_p = true;
++num_templates;
}
}
pop_deferring_access_checks ();
if (id)
cp_parser_check_for_invalid_template_id (parser, id);
/* If it's not a `:' or a `{' then we can't really be looking at a
class-head, since a class-head only appears as part of a
class-specifier. We have to detect this situation before calling
xref_tag, since that has irreversible side-effects. */
if (!cp_parser_next_token_starts_class_definition_p (parser))
{
cp_parser_error (parser, "expected %<{%> or %<:%>");
return error_mark_node;
}
/* At this point, we're going ahead with the class-specifier, even
if some other problem occurs. */
cp_parser_commit_to_tentative_parse (parser);
/* Issue the error about the overly-qualified name now. */
if (qualified_p)
cp_parser_error (parser,
"global qualification of class name is invalid");
else if (invalid_nested_name_p)
cp_parser_error (parser,
"qualified name does not name a class");
else if (nested_name_specifier)
{
tree scope;
/* Reject typedef-names in class heads. */
if (!DECL_IMPLICIT_TYPEDEF_P (type))
{
error ("invalid class name in declaration of %qD", type);
type = NULL_TREE;
goto done;
}
/* Figure out in what scope the declaration is being placed. */
scope = current_scope ();
/* If that scope does not contain the scope in which the
class was originally declared, the program is invalid. */
if (scope && !is_ancestor (scope, nested_name_specifier))
{
error ("declaration of %qD in %qD which does not enclose %qD",
type, scope, nested_name_specifier);
type = NULL_TREE;
goto done;
}
/* [dcl.meaning]
A declarator-id shall not be qualified exception of the
definition of a ... nested class outside of its class
... [or] a the definition or explicit instantiation of a
class member of a namespace outside of its namespace. */
if (scope == nested_name_specifier)
{
pedwarn ("extra qualification ignored");
nested_name_specifier = NULL_TREE;
num_templates = 0;
}
}
/* An explicit-specialization must be preceded by "template <>". If
it is not, try to recover gracefully. */
if (at_namespace_scope_p ()
&& parser->num_template_parameter_lists == 0
&& template_id_p)
{
error ("an explicit specialization must be preceded by %<template <>%>");
invalid_explicit_specialization_p = true;
/* Take the same action that would have been taken by
cp_parser_explicit_specialization. */
++parser->num_template_parameter_lists;
begin_specialization ();
}
/* There must be no "return" statements between this point and the
end of this function; set "type "to the correct return value and
use "goto done;" to return. */
/* Make sure that the right number of template parameters were
present. */
if (!cp_parser_check_template_parameters (parser, num_templates))
{
/* If something went wrong, there is no point in even trying to
process the class-definition. */
type = NULL_TREE;
goto done;
}
/* Look up the type. */
if (template_id_p)
{
type = TREE_TYPE (id);
type = maybe_process_partial_specialization (type);
if (nested_name_specifier)
pushed_scope = push_scope (nested_name_specifier);
}
else if (nested_name_specifier)
{
tree class_type;
/* Given:
template <typename T> struct S { struct T };
template <typename T> struct S<T>::T { };
we will get a TYPENAME_TYPE when processing the definition of
`S::T'. We need to resolve it to the actual type before we
try to define it. */
if (TREE_CODE (TREE_TYPE (type)) == TYPENAME_TYPE)
{
class_type = resolve_typename_type (TREE_TYPE (type),
/*only_current_p=*/false);
if (class_type != error_mark_node)
type = TYPE_NAME (class_type);
else
{
cp_parser_error (parser, "could not resolve typename type");
type = error_mark_node;
}
}
maybe_process_partial_specialization (TREE_TYPE (type));
class_type = current_class_type;
/* Enter the scope indicated by the nested-name-specifier. */
pushed_scope = push_scope (nested_name_specifier);
/* Get the canonical version of this type. */
type = TYPE_MAIN_DECL (TREE_TYPE (type));
if (PROCESSING_REAL_TEMPLATE_DECL_P ()
&& !CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (type)))
{
type = push_template_decl (type);
if (type == error_mark_node)
{
type = NULL_TREE;
goto done;
}
}
type = TREE_TYPE (type);
*nested_name_specifier_p = true;
}
else /* The name is not a nested name. */
{
/* If the class was unnamed, create a dummy name. */
if (!id)
id = make_anon_name ();
type = xref_tag (class_key, id, /*tag_scope=*/ts_current,
parser->num_template_parameter_lists);
}
/* Indicate whether this class was declared as a `class' or as a
`struct'. */
if (TREE_CODE (type) == RECORD_TYPE)
CLASSTYPE_DECLARED_CLASS (type) = (class_key == class_type);
cp_parser_check_class_key (class_key, type);
/* If this type was already complete, and we see another definition,
that's an error. */
if (type != error_mark_node && COMPLETE_TYPE_P (type))
{
error ("redefinition of %q#T", type);
error ("previous definition of %q+#T", type);
type = NULL_TREE;
goto done;
}
else if (type == error_mark_node)
type = NULL_TREE;
/* We will have entered the scope containing the class; the names of
base classes should be looked up in that context. For example:
struct A { struct B {}; struct C; };
struct A::C : B {};
is valid. */
*bases = NULL_TREE;
/* Get the list of base-classes, if there is one. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COLON))
*bases = cp_parser_base_clause (parser);
done:
/* Leave the scope given by the nested-name-specifier. We will
enter the class scope itself while processing the members. */
if (pushed_scope)
pop_scope (pushed_scope);
if (invalid_explicit_specialization_p)
{
end_specialization ();
--parser->num_template_parameter_lists;
}
*attributes_p = attributes;
return type;
}
/* Parse a class-key.
class-key:
class
struct
union
Returns the kind of class-key specified, or none_type to indicate
error. */
static enum tag_types
cp_parser_class_key (cp_parser* parser)
{
cp_token *token;
enum tag_types tag_type;
/* Look for the class-key. */
token = cp_parser_require (parser, CPP_KEYWORD, "class-key");
if (!token)
return none_type;
/* Check to see if the TOKEN is a class-key. */
tag_type = cp_parser_token_is_class_key (token);
if (!tag_type)
cp_parser_error (parser, "expected class-key");
return tag_type;
}
/* Parse an (optional) member-specification.
member-specification:
member-declaration member-specification [opt]
access-specifier : member-specification [opt] */
static void
cp_parser_member_specification_opt (cp_parser* parser)
{
while (true)
{
cp_token *token;
enum rid keyword;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's a `}', or EOF then we've seen all the members. */
if (token->type == CPP_CLOSE_BRACE
|| token->type == CPP_EOF
|| token->type == CPP_PRAGMA_EOL)
break;
/* See if this token is a keyword. */
keyword = token->keyword;
switch (keyword)
{
case RID_PUBLIC:
case RID_PROTECTED:
case RID_PRIVATE:
/* Consume the access-specifier. */
cp_lexer_consume_token (parser->lexer);
/* Remember which access-specifier is active. */
current_access_specifier = token->u.value;
/* Look for the `:'. */
cp_parser_require (parser, CPP_COLON, "`:'");
break;
default:
/* Accept #pragmas at class scope. */
if (token->type == CPP_PRAGMA)
{
cp_parser_pragma (parser, pragma_external);
break;
}
/* Otherwise, the next construction must be a
member-declaration. */
cp_parser_member_declaration (parser);
}
}
}
/* Parse a member-declaration.
member-declaration:
decl-specifier-seq [opt] member-declarator-list [opt] ;
function-definition ; [opt]
:: [opt] nested-name-specifier template [opt] unqualified-id ;
using-declaration
template-declaration
member-declarator-list:
member-declarator
member-declarator-list , member-declarator
member-declarator:
declarator pure-specifier [opt]
declarator constant-initializer [opt]
identifier [opt] : constant-expression
GNU Extensions:
member-declaration:
__extension__ member-declaration
member-declarator:
declarator attributes [opt] pure-specifier [opt]
declarator attributes [opt] constant-initializer [opt]
identifier [opt] attributes [opt] : constant-expression */
static void
cp_parser_member_declaration (cp_parser* parser)
{
cp_decl_specifier_seq decl_specifiers;
tree prefix_attributes;
tree decl;
int declares_class_or_enum;
bool friend_p;
cp_token *token;
int saved_pedantic;
/* Check for the `__extension__' keyword. */
if (cp_parser_extension_opt (parser, &saved_pedantic))
{
/* Recurse. */
cp_parser_member_declaration (parser);
/* Restore the old value of the PEDANTIC flag. */
pedantic = saved_pedantic;
return;
}
/* Check for a template-declaration. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_TEMPLATE))
{
/* An explicit specialization here is an error condition, and we
expect the specialization handler to detect and report this. */
if (cp_lexer_peek_nth_token (parser->lexer, 2)->type == CPP_LESS
&& cp_lexer_peek_nth_token (parser->lexer, 3)->type == CPP_GREATER)
cp_parser_explicit_specialization (parser);
else
cp_parser_template_declaration (parser, /*member_p=*/true);
return;
}
/* Check for a using-declaration. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_USING))
{
/* Parse the using-declaration. */
cp_parser_using_declaration (parser,
/*access_declaration_p=*/false);
return;
}
/* Check for @defs. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_AT_DEFS))
{
tree ivar, member;
tree ivar_chains = cp_parser_objc_defs_expression (parser);
ivar = ivar_chains;
while (ivar)
{
member = ivar;
ivar = TREE_CHAIN (member);
TREE_CHAIN (member) = NULL_TREE;
finish_member_declaration (member);
}
/* APPLE LOCAL begin C* warnings to easy porting to new abi */
if (flag_objc_abi == 3
|| (flag_objc2_check && flag_objc_abi == 1))
warning (0, "@defs will not be supported in future");
/* APPLE LOCAL radar 4705250 */
else if (flag_objc_abi == 2 && flag_objc_atdefs != 1)
error ("@defs will not be supported in future");
/* APPLE LOCAL end C* warnings to easy porting to new abi */
return;
}
if (cp_parser_using_declaration (parser, /*access_declaration=*/true))
return;
/* Parse the decl-specifier-seq. */
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_OPTIONAL,
&decl_specifiers,
&declares_class_or_enum);
prefix_attributes = decl_specifiers.attributes;
decl_specifiers.attributes = NULL_TREE;
/* Check for an invalid type-name. */
if (!decl_specifiers.type
&& cp_parser_parse_and_diagnose_invalid_type_name (parser))
return;
/* If there is no declarator, then the decl-specifier-seq should
specify a type. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
{
/* If there was no decl-specifier-seq, and the next token is a
`;', then we have something like:
struct S { ; };
[class.mem]
Each member-declaration shall declare at least one member
name of the class. */
if (!decl_specifiers.any_specifiers_p)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
if (pedantic && !token->in_system_header)
pedwarn ("%Hextra %<;%>", &token->location);
}
else
{
tree type;
/* See if this declaration is a friend. */
friend_p = cp_parser_friend_p (&decl_specifiers);
/* If there were decl-specifiers, check to see if there was
a class-declaration. */
type = check_tag_decl (&decl_specifiers);
/* Nested classes have already been added to the class, but
a `friend' needs to be explicitly registered. */
if (friend_p)
{
/* If the `friend' keyword was present, the friend must
be introduced with a class-key. */
if (!declares_class_or_enum)
error ("a class-key must be used when declaring a friend");
/* In this case:
template <typename T> struct A {
friend struct A<T>::B;
};
A<T>::B will be represented by a TYPENAME_TYPE, and
therefore not recognized by check_tag_decl. */
if (!type
&& decl_specifiers.type
&& TYPE_P (decl_specifiers.type))
type = decl_specifiers.type;
if (!type || !TYPE_P (type))
error ("friend declaration does not name a class or "
"function");
else
make_friend_class (current_class_type, type,
/*complain=*/true);
}
/* If there is no TYPE, an error message will already have
been issued. */
else if (!type || type == error_mark_node)
;
/* An anonymous aggregate has to be handled specially; such
a declaration really declares a data member (with a
particular type), as opposed to a nested class. */
else if (ANON_AGGR_TYPE_P (type))
{
/* Remove constructors and such from TYPE, now that we
know it is an anonymous aggregate. */
fixup_anonymous_aggr (type);
/* And make the corresponding data member. */
decl = build_decl (FIELD_DECL, NULL_TREE, type);
/* Add it to the class. */
finish_member_declaration (decl);
}
else
cp_parser_check_access_in_redeclaration (TYPE_NAME (type));
}
}
else
{
/* See if these declarations will be friends. */
friend_p = cp_parser_friend_p (&decl_specifiers);
/* Keep going until we hit the `;' at the end of the
declaration. */
while (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
{
tree attributes = NULL_TREE;
tree first_attribute;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Check for a bitfield declaration. */
if (token->type == CPP_COLON
|| (token->type == CPP_NAME
&& cp_lexer_peek_nth_token (parser->lexer, 2)->type
== CPP_COLON))
{
tree identifier;
tree width;
/* Get the name of the bitfield. Note that we cannot just
check TOKEN here because it may have been invalidated by
the call to cp_lexer_peek_nth_token above. */
if (cp_lexer_peek_token (parser->lexer)->type != CPP_COLON)
identifier = cp_parser_identifier (parser);
else
identifier = NULL_TREE;
/* Consume the `:' token. */
cp_lexer_consume_token (parser->lexer);
/* Get the width of the bitfield. */
width
= cp_parser_constant_expression (parser,
/*allow_non_constant=*/false,
NULL);
/* Look for attributes that apply to the bitfield. */
attributes = cp_parser_attributes_opt (parser);
/* Remember which attributes are prefix attributes and
which are not. */
first_attribute = attributes;
/* Combine the attributes. */
attributes = chainon (prefix_attributes, attributes);
/* Create the bitfield declaration. */
decl = grokbitfield (identifier
? make_id_declarator (NULL_TREE,
identifier,
sfk_none)
: NULL,
&decl_specifiers,
width);
/* Apply the attributes. */
cplus_decl_attributes (&decl, attributes, /*flags=*/0);
}
else
{
cp_declarator *declarator;
tree initializer;
tree asm_specification;
int ctor_dtor_or_conv_p;
/* Parse the declarator. */
declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
&ctor_dtor_or_conv_p,
/*parenthesized_p=*/NULL,
/*member_p=*/true);
/* If something went wrong parsing the declarator, make sure
that we at least consume some tokens. */
if (declarator == cp_error_declarator)
{
/* Skip to the end of the statement. */
cp_parser_skip_to_end_of_statement (parser);
/* If the next token is not a semicolon, that is
probably because we just skipped over the body of
a function. So, we consume a semicolon if
present, but do not issue an error message if it
is not present. */
if (cp_lexer_next_token_is (parser->lexer,
CPP_SEMICOLON))
cp_lexer_consume_token (parser->lexer);
return;
}
if (declares_class_or_enum & 2)
cp_parser_check_for_definition_in_return_type
(declarator, decl_specifiers.type);
/* Look for an asm-specification. */
asm_specification = cp_parser_asm_specification_opt (parser);
/* Look for attributes that apply to the declaration. */
attributes = cp_parser_attributes_opt (parser);
/* Remember which attributes are prefix attributes and
which are not. */
first_attribute = attributes;
/* Combine the attributes. */
attributes = chainon (prefix_attributes, attributes);
/* If it's an `=', then we have a constant-initializer or a
pure-specifier. It is not correct to parse the
initializer before registering the member declaration
since the member declaration should be in scope while
its initializer is processed. However, the rest of the
front end does not yet provide an interface that allows
us to handle this correctly. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EQ))
{
/* In [class.mem]:
A pure-specifier shall be used only in the declaration of
a virtual function.
A member-declarator can contain a constant-initializer
only if it declares a static member of integral or
enumeration type.
Therefore, if the DECLARATOR is for a function, we look
for a pure-specifier; otherwise, we look for a
constant-initializer. When we call `grokfield', it will
perform more stringent semantics checks. */
if (function_declarator_p (declarator))
initializer = cp_parser_pure_specifier (parser);
else
/* Parse the initializer. */
initializer = cp_parser_constant_initializer (parser);
}
/* Otherwise, there is no initializer. */
else
initializer = NULL_TREE;
/* See if we are probably looking at a function
definition. We are certainly not looking at a
member-declarator. Calling `grokfield' has
side-effects, so we must not do it unless we are sure
that we are looking at a member-declarator. */
if (cp_parser_token_starts_function_definition_p
(cp_lexer_peek_token (parser->lexer)))
{
/* The grammar does not allow a pure-specifier to be
used when a member function is defined. (It is
possible that this fact is an oversight in the
standard, since a pure function may be defined
outside of the class-specifier. */
if (initializer)
error ("pure-specifier on function-definition");
decl = cp_parser_save_member_function_body (parser,
&decl_specifiers,
declarator,
attributes);
/* If the member was not a friend, declare it here. */
if (!friend_p)
finish_member_declaration (decl);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If the next token is a semicolon, consume it. */
if (token->type == CPP_SEMICOLON)
cp_lexer_consume_token (parser->lexer);
return;
}
else
/* Create the declaration. */
decl = grokfield (declarator, &decl_specifiers,
initializer, /*init_const_expr_p=*/true,
asm_specification,
attributes);
}
/* Reset PREFIX_ATTRIBUTES. */
while (attributes && TREE_CHAIN (attributes) != first_attribute)
attributes = TREE_CHAIN (attributes);
if (attributes)
TREE_CHAIN (attributes) = NULL_TREE;
/* If there is any qualification still in effect, clear it
now; we will be starting fresh with the next declarator. */
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
/* If it's a `,', then there are more declarators. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
cp_lexer_consume_token (parser->lexer);
/* If the next token isn't a `;', then we have a parse error. */
else if (cp_lexer_next_token_is_not (parser->lexer,
CPP_SEMICOLON))
{
cp_parser_error (parser, "expected %<;%>");
/* Skip tokens until we find a `;'. */
cp_parser_skip_to_end_of_statement (parser);
break;
}
if (decl)
{
/* Add DECL to the list of members. */
if (!friend_p)
finish_member_declaration (decl);
if (TREE_CODE (decl) == FUNCTION_DECL)
cp_parser_save_default_args (parser, decl);
}
}
}
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
}
/* Parse a pure-specifier.
pure-specifier:
= 0
Returns INTEGER_ZERO_NODE if a pure specifier is found.
Otherwise, ERROR_MARK_NODE is returned. */
static tree
cp_parser_pure_specifier (cp_parser* parser)
{
cp_token *token;
/* Look for the `=' token. */
if (!cp_parser_require (parser, CPP_EQ, "`='"))
return error_mark_node;
/* Look for the `0' token. */
token = cp_lexer_consume_token (parser->lexer);
/* c_lex_with_flags marks a single digit '0' with PURE_ZERO. */
if (token->type != CPP_NUMBER || !(token->flags & PURE_ZERO))
{
cp_parser_error (parser,
"invalid pure specifier (only `= 0' is allowed)");
cp_parser_skip_to_end_of_statement (parser);
return error_mark_node;
}
if (PROCESSING_REAL_TEMPLATE_DECL_P ())
{
error ("templates may not be %<virtual%>");
return error_mark_node;
}
return integer_zero_node;
}
/* Parse a constant-initializer.
constant-initializer:
= constant-expression
Returns a representation of the constant-expression. */
static tree
cp_parser_constant_initializer (cp_parser* parser)
{
/* Look for the `=' token. */
if (!cp_parser_require (parser, CPP_EQ, "`='"))
return error_mark_node;
/* It is invalid to write:
struct S { static const int i = { 7 }; };
*/
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_BRACE))
{
cp_parser_error (parser,
"a brace-enclosed initializer is not allowed here");
/* Consume the opening brace. */
cp_lexer_consume_token (parser->lexer);
/* Skip the initializer. */
cp_parser_skip_to_closing_brace (parser);
/* Look for the trailing `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
return error_mark_node;
}
return cp_parser_constant_expression (parser,
/*allow_non_constant=*/false,
NULL);
}
/* Derived classes [gram.class.derived] */
/* Parse a base-clause.
base-clause:
: base-specifier-list
base-specifier-list:
base-specifier
base-specifier-list , base-specifier
Returns a TREE_LIST representing the base-classes, in the order in
which they were declared. The representation of each node is as
described by cp_parser_base_specifier.
In the case that no bases are specified, this function will return
NULL_TREE, not ERROR_MARK_NODE. */
static tree
cp_parser_base_clause (cp_parser* parser)
{
tree bases = NULL_TREE;
/* Look for the `:' that begins the list. */
cp_parser_require (parser, CPP_COLON, "`:'");
/* Scan the base-specifier-list. */
while (true)
{
cp_token *token;
tree base;
/* Look for the base-specifier. */
base = cp_parser_base_specifier (parser);
/* Add BASE to the front of the list. */
if (base != error_mark_node)
{
TREE_CHAIN (base) = bases;
bases = base;
}
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's not a comma, then the list is complete. */
if (token->type != CPP_COMMA)
break;
/* Consume the `,'. */
cp_lexer_consume_token (parser->lexer);
}
/* PARSER->SCOPE may still be non-NULL at this point, if the last
base class had a qualified name. However, the next name that
appears is certainly not qualified. */
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
return nreverse (bases);
}
/* Parse a base-specifier.
base-specifier:
:: [opt] nested-name-specifier [opt] class-name
virtual access-specifier [opt] :: [opt] nested-name-specifier
[opt] class-name
access-specifier virtual [opt] :: [opt] nested-name-specifier
[opt] class-name
Returns a TREE_LIST. The TREE_PURPOSE will be one of
ACCESS_{DEFAULT,PUBLIC,PROTECTED,PRIVATE}_[VIRTUAL]_NODE to
indicate the specifiers provided. The TREE_VALUE will be a TYPE
(or the ERROR_MARK_NODE) indicating the type that was specified. */
static tree
cp_parser_base_specifier (cp_parser* parser)
{
cp_token *token;
bool done = false;
bool virtual_p = false;
bool duplicate_virtual_error_issued_p = false;
bool duplicate_access_error_issued_p = false;
bool class_scope_p, template_p;
tree access = access_default_node;
tree type;
/* Process the optional `virtual' and `access-specifier'. */
while (!done)
{
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Process `virtual'. */
switch (token->keyword)
{
case RID_VIRTUAL:
/* If `virtual' appears more than once, issue an error. */
if (virtual_p && !duplicate_virtual_error_issued_p)
{
cp_parser_error (parser,
"%<virtual%> specified more than once in base-specified");
duplicate_virtual_error_issued_p = true;
}
virtual_p = true;
/* Consume the `virtual' token. */
cp_lexer_consume_token (parser->lexer);
break;
case RID_PUBLIC:
case RID_PROTECTED:
case RID_PRIVATE:
/* If more than one access specifier appears, issue an
error. */
if (access != access_default_node
&& !duplicate_access_error_issued_p)
{
cp_parser_error (parser,
"more than one access specifier in base-specified");
duplicate_access_error_issued_p = true;
}
access = ridpointers[(int) token->keyword];
/* Consume the access-specifier. */
cp_lexer_consume_token (parser->lexer);
break;
default:
done = true;
break;
}
}
/* It is not uncommon to see programs mechanically, erroneously, use
the 'typename' keyword to denote (dependent) qualified types
as base classes. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_TYPENAME))
{
if (!processing_template_decl)
error ("keyword %<typename%> not allowed outside of templates");
else
error ("keyword %<typename%> not allowed in this context "
"(the base class is implicitly a type)");
cp_lexer_consume_token (parser->lexer);
}
/* Look for the optional `::' operator. */
cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false);
/* Look for the nested-name-specifier. The simplest way to
implement:
[temp.res]
The keyword `typename' is not permitted in a base-specifier or
mem-initializer; in these contexts a qualified name that
depends on a template-parameter is implicitly assumed to be a
type name.
is to pretend that we have seen the `typename' keyword at this
point. */
cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/true,
/*check_dependency_p=*/true,
typename_type,
/*is_declaration=*/true);
/* If the base class is given by a qualified name, assume that names
we see are type names or templates, as appropriate. */
class_scope_p = (parser->scope && TYPE_P (parser->scope));
template_p = class_scope_p && cp_parser_optional_template_keyword (parser);
/* Finally, look for the class-name. */
type = cp_parser_class_name (parser,
class_scope_p,
template_p,
typename_type,
/*check_dependency_p=*/true,
/*class_head_p=*/false,
/*is_declaration=*/true);
if (type == error_mark_node)
return error_mark_node;
return finish_base_specifier (TREE_TYPE (type), access, virtual_p);
}
/* Exception handling [gram.exception] */
/* Parse an (optional) exception-specification.
exception-specification:
throw ( type-id-list [opt] )
Returns a TREE_LIST representing the exception-specification. The
TREE_VALUE of each node is a type. */
static tree
cp_parser_exception_specification_opt (cp_parser* parser)
{
cp_token *token;
tree type_id_list;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's not `throw', then there's no exception-specification. */
if (!cp_parser_is_keyword (token, RID_THROW))
return NULL_TREE;
/* Consume the `throw'. */
cp_lexer_consume_token (parser->lexer);
/* Look for the `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's not a `)', then there is a type-id-list. */
if (token->type != CPP_CLOSE_PAREN)
{
const char *saved_message;
/* Types may not be defined in an exception-specification. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in an exception-specification";
/* Parse the type-id-list. */
type_id_list = cp_parser_type_id_list (parser);
/* Restore the saved message. */
parser->type_definition_forbidden_message = saved_message;
}
else
type_id_list = empty_except_spec;
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
return type_id_list;
}
/* Parse an (optional) type-id-list.
type-id-list:
type-id
type-id-list , type-id
Returns a TREE_LIST. The TREE_VALUE of each node is a TYPE,
in the order that the types were presented. */
static tree
cp_parser_type_id_list (cp_parser* parser)
{
tree types = NULL_TREE;
while (true)
{
cp_token *token;
tree type;
/* Get the next type-id. */
type = cp_parser_type_id (parser);
/* Add it to the list. */
types = add_exception_specifier (types, type, /*complain=*/1);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it is not a `,', we are done. */
if (token->type != CPP_COMMA)
break;
/* Consume the `,'. */
cp_lexer_consume_token (parser->lexer);
}
return nreverse (types);
}
/* Parse a try-block.
try-block:
try compound-statement handler-seq */
static tree
cp_parser_try_block (cp_parser* parser)
{
tree try_block;
cp_parser_require_keyword (parser, RID_TRY, "`try'");
try_block = begin_try_block ();
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, true, false);
finish_try_block (try_block);
cp_parser_handler_seq (parser);
finish_handler_sequence (try_block);
return try_block;
}
/* Parse a function-try-block.
function-try-block:
try ctor-initializer [opt] function-body handler-seq */
static bool
cp_parser_function_try_block (cp_parser* parser)
{
tree compound_stmt;
tree try_block;
bool ctor_initializer_p;
/* Look for the `try' keyword. */
if (!cp_parser_require_keyword (parser, RID_TRY, "`try'"))
return false;
/* Let the rest of the front-end know where we are. */
try_block = begin_function_try_block (&compound_stmt);
/* Parse the function-body. */
ctor_initializer_p
= cp_parser_ctor_initializer_opt_and_function_body (parser);
/* We're done with the `try' part. */
finish_function_try_block (try_block);
/* Parse the handlers. */
cp_parser_handler_seq (parser);
/* We're done with the handlers. */
finish_function_handler_sequence (try_block, compound_stmt);
return ctor_initializer_p;
}
/* Parse a handler-seq.
handler-seq:
handler handler-seq [opt] */
static void
cp_parser_handler_seq (cp_parser* parser)
{
while (true)
{
cp_token *token;
/* Parse the handler. */
cp_parser_handler (parser);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's not `catch' then there are no more handlers. */
if (!cp_parser_is_keyword (token, RID_CATCH))
break;
}
}
/* Parse a handler.
handler:
catch ( exception-declaration ) compound-statement */
static void
cp_parser_handler (cp_parser* parser)
{
tree handler;
tree declaration;
cp_parser_require_keyword (parser, RID_CATCH, "`catch'");
handler = begin_handler ();
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
declaration = cp_parser_exception_declaration (parser);
finish_handler_parms (declaration, handler);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, false, false);
finish_handler (handler);
}
/* Parse an exception-declaration.
exception-declaration:
type-specifier-seq declarator
type-specifier-seq abstract-declarator
type-specifier-seq
...
Returns a VAR_DECL for the declaration, or NULL_TREE if the
ellipsis variant is used. */
static tree
cp_parser_exception_declaration (cp_parser* parser)
{
cp_decl_specifier_seq type_specifiers;
cp_declarator *declarator;
const char *saved_message;
/* If it's an ellipsis, it's easy to handle. */
if (cp_lexer_next_token_is (parser->lexer, CPP_ELLIPSIS))
{
/* Consume the `...' token. */
cp_lexer_consume_token (parser->lexer);
return NULL_TREE;
}
/* Types may not be defined in exception-declarations. */
saved_message = parser->type_definition_forbidden_message;
parser->type_definition_forbidden_message
= "types may not be defined in exception-declarations";
/* Parse the type-specifier-seq. */
cp_parser_type_specifier_seq (parser, /*is_condition=*/false,
&type_specifiers);
/* If it's a `)', then there is no declarator. */
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_PAREN))
declarator = NULL;
else
declarator = cp_parser_declarator (parser, CP_PARSER_DECLARATOR_EITHER,
/*ctor_dtor_or_conv_p=*/NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
/* Restore the saved message. */
parser->type_definition_forbidden_message = saved_message;
if (!type_specifiers.any_specifiers_p)
return error_mark_node;
return grokdeclarator (declarator, &type_specifiers, CATCHPARM, 1, NULL);
}
/* Parse a throw-expression.
throw-expression:
throw assignment-expression [opt]
Returns a THROW_EXPR representing the throw-expression. */
static tree
cp_parser_throw_expression (cp_parser* parser)
{
tree expression;
cp_token* token;
cp_parser_require_keyword (parser, RID_THROW, "`throw'");
token = cp_lexer_peek_token (parser->lexer);
/* Figure out whether or not there is an assignment-expression
following the "throw" keyword. */
if (token->type == CPP_COMMA
|| token->type == CPP_SEMICOLON
|| token->type == CPP_CLOSE_PAREN
|| token->type == CPP_CLOSE_SQUARE
|| token->type == CPP_CLOSE_BRACE
|| token->type == CPP_COLON)
expression = NULL_TREE;
else
expression = cp_parser_assignment_expression (parser,
/*cast_p=*/false);
return build_throw (expression);
}
/* GNU Extensions */
/* Parse an (optional) asm-specification.
asm-specification:
asm ( string-literal )
If the asm-specification is present, returns a STRING_CST
corresponding to the string-literal. Otherwise, returns
NULL_TREE. */
static tree
cp_parser_asm_specification_opt (cp_parser* parser)
{
cp_token *token;
tree asm_specification;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If the next token isn't the `asm' keyword, then there's no
asm-specification. */
if (!cp_parser_is_keyword (token, RID_ASM))
return NULL_TREE;
/* Consume the `asm' token. */
cp_lexer_consume_token (parser->lexer);
/* Look for the `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Look for the string-literal. */
asm_specification = cp_parser_string_literal (parser, false, false);
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`('");
return asm_specification;
}
/* Parse an asm-operand-list.
asm-operand-list:
asm-operand
asm-operand-list , asm-operand
asm-operand:
string-literal ( expression )
[ string-literal ] string-literal ( expression )
Returns a TREE_LIST representing the operands. The TREE_VALUE of
each node is the expression. The TREE_PURPOSE is itself a
TREE_LIST whose TREE_PURPOSE is a STRING_CST for the bracketed
string-literal (or NULL_TREE if not present) and whose TREE_VALUE
is a STRING_CST for the string literal before the parenthesis. */
static tree
cp_parser_asm_operand_list (cp_parser* parser)
{
tree asm_operands = NULL_TREE;
while (true)
{
tree string_literal;
tree expression;
tree name;
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_SQUARE))
{
/* Consume the `[' token. */
cp_lexer_consume_token (parser->lexer);
/* Read the operand name. */
name = cp_parser_identifier (parser);
if (name != error_mark_node)
name = build_string (IDENTIFIER_LENGTH (name),
IDENTIFIER_POINTER (name));
/* Look for the closing `]'. */
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
}
else
name = NULL_TREE;
/* Look for the string-literal. */
string_literal = cp_parser_string_literal (parser, false, false);
/* Look for the `('. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Parse the expression. */
expression = cp_parser_expression (parser, /*cast_p=*/false);
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Add this operand to the list. */
asm_operands = tree_cons (build_tree_list (name, string_literal),
expression,
asm_operands);
/* If the next token is not a `,', there are no more
operands. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Consume the `,'. */
cp_lexer_consume_token (parser->lexer);
}
return nreverse (asm_operands);
}
/* Parse an asm-clobber-list.
asm-clobber-list:
string-literal
asm-clobber-list , string-literal
Returns a TREE_LIST, indicating the clobbers in the order that they
appeared. The TREE_VALUE of each node is a STRING_CST. */
static tree
cp_parser_asm_clobber_list (cp_parser* parser)
{
tree clobbers = NULL_TREE;
while (true)
{
tree string_literal;
/* Look for the string literal. */
string_literal = cp_parser_string_literal (parser, false, false);
/* Add it to the list. */
clobbers = tree_cons (NULL_TREE, string_literal, clobbers);
/* If the next token is not a `,', then the list is
complete. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
/* Consume the `,' token. */
cp_lexer_consume_token (parser->lexer);
}
return clobbers;
}
/* Parse an (optional) series of attributes.
attributes:
attributes attribute
attribute:
__attribute__ (( attribute-list [opt] ))
The return value is as for cp_parser_attribute_list. */
static tree
cp_parser_attributes_opt (cp_parser* parser)
{
tree attributes = NULL_TREE;
while (true)
{
cp_token *token;
tree attribute_list;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's not `__attribute__', then we're done. */
if (token->keyword != RID_ATTRIBUTE)
break;
/* Consume the `__attribute__' keyword. */
cp_lexer_consume_token (parser->lexer);
/* Look for the two `(' tokens. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type != CPP_CLOSE_PAREN)
/* Parse the attribute-list. */
attribute_list = cp_parser_attribute_list (parser);
else
/* If the next token is a `)', then there is no attribute
list. */
attribute_list = NULL;
/* Look for the two `)' tokens. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Add these new attributes to the list. */
attributes = chainon (attributes, attribute_list);
}
return attributes;
}
/* Parse an attribute-list.
attribute-list:
attribute
attribute-list , attribute
attribute:
identifier
identifier ( identifier )
identifier ( identifier , expression-list )
identifier ( expression-list )
Returns a TREE_LIST, or NULL_TREE on error. Each node corresponds
to an attribute. The TREE_PURPOSE of each node is the identifier
indicating which attribute is in use. The TREE_VALUE represents
the arguments, if any. */
static tree
cp_parser_attribute_list (cp_parser* parser)
{
tree attribute_list = NULL_TREE;
bool save_translate_strings_p = parser->translate_strings_p;
parser->translate_strings_p = false;
while (true)
{
cp_token *token;
tree identifier;
tree attribute;
/* Look for the identifier. We also allow keywords here; for
example `__attribute__ ((const))' is legal. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_NAME
|| token->type == CPP_KEYWORD)
{
tree arguments = NULL_TREE;
/* Consume the token. */
token = cp_lexer_consume_token (parser->lexer);
/* Save away the identifier that indicates which attribute
this is. */
identifier = token->u.value;
attribute = build_tree_list (identifier, NULL_TREE);
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If it's an `(', then parse the attribute arguments. */
if (token->type == CPP_OPEN_PAREN)
{
arguments = cp_parser_parenthesized_expression_list
(parser, true, /*cast_p=*/false,
/*non_constant_p=*/NULL);
/* Save the arguments away. */
TREE_VALUE (attribute) = arguments;
}
if (arguments != error_mark_node)
{
/* Add this attribute to the list. */
TREE_CHAIN (attribute) = attribute_list;
attribute_list = attribute;
}
token = cp_lexer_peek_token (parser->lexer);
}
/* Now, look for more attributes. If the next token isn't a
`,', we're done. */
if (token->type != CPP_COMMA)
break;
/* Consume the comma and keep going. */
cp_lexer_consume_token (parser->lexer);
}
parser->translate_strings_p = save_translate_strings_p;
/* We built up the list in reverse order. */
return nreverse (attribute_list);
}
/* Parse an optional `__extension__' keyword. Returns TRUE if it is
present, and FALSE otherwise. *SAVED_PEDANTIC is set to the
current value of the PEDANTIC flag, regardless of whether or not
the `__extension__' keyword is present. The caller is responsible
for restoring the value of the PEDANTIC flag. */
static bool
cp_parser_extension_opt (cp_parser* parser, int* saved_pedantic)
{
/* Save the old value of the PEDANTIC flag. */
*saved_pedantic = pedantic;
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_EXTENSION))
{
/* Consume the `__extension__' token. */
cp_lexer_consume_token (parser->lexer);
/* We're not being pedantic while the `__extension__' keyword is
in effect. */
pedantic = 0;
return true;
}
return false;
}
/* Parse a label declaration.
label-declaration:
__label__ label-declarator-seq ;
label-declarator-seq:
identifier , label-declarator-seq
identifier */
static void
cp_parser_label_declaration (cp_parser* parser)
{
/* Look for the `__label__' keyword. */
cp_parser_require_keyword (parser, RID_LABEL, "`__label__'");
while (true)
{
tree identifier;
/* Look for an identifier. */
identifier = cp_parser_identifier (parser);
/* If we failed, stop. */
if (identifier == error_mark_node)
break;
/* Declare it as a label. */
finish_label_decl (identifier);
/* If the next token is a `;', stop. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
break;
/* Look for the `,' separating the label declarations. */
cp_parser_require (parser, CPP_COMMA, "`,'");
}
/* Look for the final `;'. */
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
}
/* Support Functions */
/* Looks up NAME in the current scope, as given by PARSER->SCOPE.
NAME should have one of the representations used for an
id-expression. If NAME is the ERROR_MARK_NODE, the ERROR_MARK_NODE
is returned. If PARSER->SCOPE is a dependent type, then a
SCOPE_REF is returned.
If NAME is a TEMPLATE_ID_EXPR, then it will be immediately
returned; the name was already resolved when the TEMPLATE_ID_EXPR
was formed. Abstractly, such entities should not be passed to this
function, because they do not need to be looked up, but it is
simpler to check for this special case here, rather than at the
call-sites.
In cases not explicitly covered above, this function returns a
DECL, OVERLOAD, or baselink representing the result of the lookup.
If there was no entity with the indicated NAME, the ERROR_MARK_NODE
is returned.
If TAG_TYPE is not NONE_TYPE, it indicates an explicit type keyword
(e.g., "struct") that was used. In that case bindings that do not
refer to types are ignored.
If IS_TEMPLATE is TRUE, bindings that do not refer to templates are
ignored.
If IS_NAMESPACE is TRUE, bindings that do not refer to namespaces
are ignored.
If CHECK_DEPENDENCY is TRUE, names are not looked up in dependent
types.
If AMBIGUOUS_DECLS is non-NULL, *AMBIGUOUS_DECLS is set to a
TREE_LIST of candidates if name-lookup results in an ambiguity, and
NULL_TREE otherwise. */
static tree
cp_parser_lookup_name (cp_parser *parser, tree name,
enum tag_types tag_type,
bool is_template,
bool is_namespace,
bool check_dependency,
tree *ambiguous_decls)
{
int flags = 0;
tree decl;
tree object_type = parser->context->object_type;
if (!cp_parser_uncommitted_to_tentative_parse_p (parser))
flags |= LOOKUP_COMPLAIN;
/* Assume that the lookup will be unambiguous. */
if (ambiguous_decls)
*ambiguous_decls = NULL_TREE;
/* Now that we have looked up the name, the OBJECT_TYPE (if any) is
no longer valid. Note that if we are parsing tentatively, and
the parse fails, OBJECT_TYPE will be automatically restored. */
parser->context->object_type = NULL_TREE;
if (name == error_mark_node)
return error_mark_node;
/* A template-id has already been resolved; there is no lookup to
do. */
if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
return name;
if (BASELINK_P (name))
{
gcc_assert (TREE_CODE (BASELINK_FUNCTIONS (name))
== TEMPLATE_ID_EXPR);
return name;
}
/* A BIT_NOT_EXPR is used to represent a destructor. By this point,
it should already have been checked to make sure that the name
used matches the type being destroyed. */
if (TREE_CODE (name) == BIT_NOT_EXPR)
{
tree type;
/* Figure out to which type this destructor applies. */
if (parser->scope)
type = parser->scope;
else if (object_type)
type = object_type;
else
type = current_class_type;
/* If that's not a class type, there is no destructor. */
if (!type || !CLASS_TYPE_P (type))
return error_mark_node;
if (CLASSTYPE_LAZY_DESTRUCTOR (type))
lazily_declare_fn (sfk_destructor, type);
if (!CLASSTYPE_DESTRUCTORS (type))
return error_mark_node;
/* If it was a class type, return the destructor. */
return CLASSTYPE_DESTRUCTORS (type);
}
/* By this point, the NAME should be an ordinary identifier. If
the id-expression was a qualified name, the qualifying scope is
stored in PARSER->SCOPE at this point. */
gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
/* Perform the lookup. */
if (parser->scope)
{
bool dependent_p;
if (parser->scope == error_mark_node)
return error_mark_node;
/* If the SCOPE is dependent, the lookup must be deferred until
the template is instantiated -- unless we are explicitly
looking up names in uninstantiated templates. Even then, we
cannot look up the name if the scope is not a class type; it
might, for example, be a template type parameter. */
dependent_p = (TYPE_P (parser->scope)
&& !(parser->in_declarator_p
&& currently_open_class (parser->scope))
&& dependent_type_p (parser->scope));
if ((check_dependency || !CLASS_TYPE_P (parser->scope))
&& dependent_p)
{
if (tag_type)
{
tree type;
/* The resolution to Core Issue 180 says that `struct
A::B' should be considered a type-name, even if `A'
is dependent. */
type = make_typename_type (parser->scope, name, tag_type,
/*complain=*/tf_error);
decl = TYPE_NAME (type);
}
else if (is_template
&& (cp_parser_next_token_ends_template_argument_p (parser)
|| cp_lexer_next_token_is (parser->lexer,
CPP_CLOSE_PAREN)))
decl = make_unbound_class_template (parser->scope,
name, NULL_TREE,
/*complain=*/tf_error);
else
decl = build_qualified_name (/*type=*/NULL_TREE,
parser->scope, name,
is_template);
}
else
{
tree pushed_scope = NULL_TREE;
/* If PARSER->SCOPE is a dependent type, then it must be a
class type, and we must not be checking dependencies;
otherwise, we would have processed this lookup above. So
that PARSER->SCOPE is not considered a dependent base by
lookup_member, we must enter the scope here. */
if (dependent_p)
pushed_scope = push_scope (parser->scope);
/* If the PARSER->SCOPE is a template specialization, it
may be instantiated during name lookup. In that case,
errors may be issued. Even if we rollback the current
tentative parse, those errors are valid. */
decl = lookup_qualified_name (parser->scope, name,
tag_type != none_type,
/*complain=*/true);
if (pushed_scope)
pop_scope (pushed_scope);
}
parser->qualifying_scope = parser->scope;
parser->object_scope = NULL_TREE;
}
else if (object_type)
{
tree object_decl = NULL_TREE;
/* Look up the name in the scope of the OBJECT_TYPE, unless the
OBJECT_TYPE is not a class. */
if (CLASS_TYPE_P (object_type))
/* If the OBJECT_TYPE is a template specialization, it may
be instantiated during name lookup. In that case, errors
may be issued. Even if we rollback the current tentative
parse, those errors are valid. */
object_decl = lookup_member (object_type,
name,
/*protect=*/0,
tag_type != none_type);
/* Look it up in the enclosing context, too. */
decl = lookup_name_real (name, tag_type != none_type,
/*nonclass=*/0,
/*block_p=*/true, is_namespace, flags);
parser->object_scope = object_type;
parser->qualifying_scope = NULL_TREE;
if (object_decl)
decl = object_decl;
}
else
{
decl = lookup_name_real (name, tag_type != none_type,
/*nonclass=*/0,
/*block_p=*/true, is_namespace, flags);
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
}
/* If the lookup failed, let our caller know. */
if (!decl || decl == error_mark_node)
return error_mark_node;
/* If it's a TREE_LIST, the result of the lookup was ambiguous. */
if (TREE_CODE (decl) == TREE_LIST)
{
if (ambiguous_decls)
*ambiguous_decls = decl;
/* The error message we have to print is too complicated for
cp_parser_error, so we incorporate its actions directly. */
if (!cp_parser_simulate_error (parser))
{
error ("reference to %qD is ambiguous", name);
print_candidates (decl);
}
return error_mark_node;
}
gcc_assert (DECL_P (decl)
|| TREE_CODE (decl) == OVERLOAD
|| TREE_CODE (decl) == SCOPE_REF
|| TREE_CODE (decl) == UNBOUND_CLASS_TEMPLATE
|| BASELINK_P (decl));
/* If we have resolved the name of a member declaration, check to
see if the declaration is accessible. When the name resolves to
set of overloaded functions, accessibility is checked when
overload resolution is done.
During an explicit instantiation, access is not checked at all,
as per [temp.explicit]. */
if (DECL_P (decl))
check_accessibility_of_qualified_id (decl, object_type, parser->scope);
return decl;
}
/* Like cp_parser_lookup_name, but for use in the typical case where
CHECK_ACCESS is TRUE, IS_TYPE is FALSE, IS_TEMPLATE is FALSE,
IS_NAMESPACE is FALSE, and CHECK_DEPENDENCY is TRUE. */
static tree
cp_parser_lookup_name_simple (cp_parser* parser, tree name)
{
return cp_parser_lookup_name (parser, name,
none_type,
/*is_template=*/false,
/*is_namespace=*/false,
/*check_dependency=*/true,
/*ambiguous_decls=*/NULL);
}
/* If DECL is a TEMPLATE_DECL that can be treated like a TYPE_DECL in
the current context, return the TYPE_DECL. If TAG_NAME_P is
true, the DECL indicates the class being defined in a class-head,
or declared in an elaborated-type-specifier.
Otherwise, return DECL. */
static tree
cp_parser_maybe_treat_template_as_class (tree decl, bool tag_name_p)
{
/* If the TEMPLATE_DECL is being declared as part of a class-head,
the translation from TEMPLATE_DECL to TYPE_DECL occurs:
struct A {
template <typename T> struct B;
};
template <typename T> struct A::B {};
Similarly, in an elaborated-type-specifier:
namespace N { struct X{}; }
struct A {
template <typename T> friend struct N::X;
};
However, if the DECL refers to a class type, and we are in
the scope of the class, then the name lookup automatically
finds the TYPE_DECL created by build_self_reference rather
than a TEMPLATE_DECL. For example, in:
template <class T> struct S {
S s;
};
there is no need to handle such case. */
if (DECL_CLASS_TEMPLATE_P (decl) && tag_name_p)
return DECL_TEMPLATE_RESULT (decl);
return decl;
}
/* If too many, or too few, template-parameter lists apply to the
declarator, issue an error message. Returns TRUE if all went well,
and FALSE otherwise. */
static bool
cp_parser_check_declarator_template_parameters (cp_parser* parser,
cp_declarator *declarator)
{
unsigned num_templates;
/* We haven't seen any classes that involve template parameters yet. */
num_templates = 0;
switch (declarator->kind)
{
case cdk_id:
if (declarator->u.id.qualifying_scope)
{
tree scope;
tree member;
scope = declarator->u.id.qualifying_scope;
member = declarator->u.id.unqualified_name;
while (scope && CLASS_TYPE_P (scope))
{
/* You're supposed to have one `template <...>'
for every template class, but you don't need one
for a full specialization. For example:
template <class T> struct S{};
template <> struct S<int> { void f(); };
void S<int>::f () {}
is correct; there shouldn't be a `template <>' for
the definition of `S<int>::f'. */
if (!CLASSTYPE_TEMPLATE_INFO (scope))
/* If SCOPE does not have template information of any
kind, then it is not a template, nor is it nested
within a template. */
break;
if (explicit_class_specialization_p (scope))
break;
if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope)))
++num_templates;
scope = TYPE_CONTEXT (scope);
}
}
else if (TREE_CODE (declarator->u.id.unqualified_name)
== TEMPLATE_ID_EXPR)
/* If the DECLARATOR has the form `X<y>' then it uses one
additional level of template parameters. */
++num_templates;
return cp_parser_check_template_parameters (parser,
num_templates);
case cdk_function:
case cdk_array:
case cdk_pointer:
case cdk_reference:
case cdk_ptrmem:
/* APPLE LOCAL blocks 6040305 */
case cdk_block_pointer:
return (cp_parser_check_declarator_template_parameters
(parser, declarator->declarator));
case cdk_error:
return true;
default:
gcc_unreachable ();
}
return false;
}
/* NUM_TEMPLATES were used in the current declaration. If that is
invalid, return FALSE and issue an error messages. Otherwise,
return TRUE. */
static bool
cp_parser_check_template_parameters (cp_parser* parser,
unsigned num_templates)
{
/* If there are more template classes than parameter lists, we have
something like:
template <class T> void S<T>::R<T>::f (); */
if (parser->num_template_parameter_lists < num_templates)
{
error ("too few template-parameter-lists");
return false;
}
/* If there are the same number of template classes and parameter
lists, that's OK. */
if (parser->num_template_parameter_lists == num_templates)
return true;
/* If there are more, but only one more, then we are referring to a
member template. That's OK too. */
if (parser->num_template_parameter_lists == num_templates + 1)
return true;
/* Otherwise, there are too many template parameter lists. We have
something like:
template <class T> template <class U> void S::f(); */
error ("too many template-parameter-lists");
return false;
}
/* Parse an optional `::' token indicating that the following name is
from the global namespace. If so, PARSER->SCOPE is set to the
GLOBAL_NAMESPACE. Otherwise, PARSER->SCOPE is set to NULL_TREE,
unless CURRENT_SCOPE_VALID_P is TRUE, in which case it is left alone.
Returns the new value of PARSER->SCOPE, if the `::' token is
present, and NULL_TREE otherwise. */
static tree
cp_parser_global_scope_opt (cp_parser* parser, bool current_scope_valid_p)
{
cp_token *token;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If we're looking at a `::' token then we're starting from the
global namespace, not our current location. */
if (token->type == CPP_SCOPE)
{
/* Consume the `::' token. */
cp_lexer_consume_token (parser->lexer);
/* Set the SCOPE so that we know where to start the lookup. */
parser->scope = global_namespace;
parser->qualifying_scope = global_namespace;
parser->object_scope = NULL_TREE;
return parser->scope;
}
else if (!current_scope_valid_p)
{
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
}
return NULL_TREE;
}
/* Returns TRUE if the upcoming token sequence is the start of a
constructor declarator. If FRIEND_P is true, the declarator is
preceded by the `friend' specifier. */
static bool
cp_parser_constructor_declarator_p (cp_parser *parser, bool friend_p)
{
bool constructor_p;
tree type_decl = NULL_TREE;
bool nested_name_p;
cp_token *next_token;
/* The common case is that this is not a constructor declarator, so
try to avoid doing lots of work if at all possible. It's not
valid declare a constructor at function scope. */
if (parser->in_function_body)
return false;
/* And only certain tokens can begin a constructor declarator. */
next_token = cp_lexer_peek_token (parser->lexer);
if (next_token->type != CPP_NAME
&& next_token->type != CPP_SCOPE
&& next_token->type != CPP_NESTED_NAME_SPECIFIER
&& next_token->type != CPP_TEMPLATE_ID)
return false;
/* Parse tentatively; we are going to roll back all of the tokens
consumed here. */
cp_parser_parse_tentatively (parser);
/* Assume that we are looking at a constructor declarator. */
constructor_p = true;
/* Look for the optional `::' operator. */
cp_parser_global_scope_opt (parser,
/*current_scope_valid_p=*/false);
/* Look for the nested-name-specifier. */
nested_name_p
= (cp_parser_nested_name_specifier_opt (parser,
/*typename_keyword_p=*/false,
/*check_dependency_p=*/false,
/*type_p=*/false,
/*is_declaration=*/false)
!= NULL_TREE);
/* Outside of a class-specifier, there must be a
nested-name-specifier. */
if (!nested_name_p &&
(!at_class_scope_p () || !TYPE_BEING_DEFINED (current_class_type)
|| friend_p))
constructor_p = false;
/* If we still think that this might be a constructor-declarator,
look for a class-name. */
if (constructor_p)
{
/* If we have:
template <typename T> struct S { S(); };
template <typename T> S<T>::S ();
we must recognize that the nested `S' names a class.
Similarly, for:
template <typename T> S<T>::S<T> ();
we must recognize that the nested `S' names a template. */
type_decl = cp_parser_class_name (parser,
/*typename_keyword_p=*/false,
/*template_keyword_p=*/false,
none_type,
/*check_dependency_p=*/false,
/*class_head_p=*/false,
/*is_declaration=*/false);
/* If there was no class-name, then this is not a constructor. */
constructor_p = !cp_parser_error_occurred (parser);
}
/* If we're still considering a constructor, we have to see a `(',
to begin the parameter-declaration-clause, followed by either a
`)', an `...', or a decl-specifier. We need to check for a
type-specifier to avoid being fooled into thinking that:
S::S (f) (int);
is a constructor. (It is actually a function named `f' that
takes one parameter (of type `int') and returns a value of type
`S::S'. */
if (constructor_p
&& cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
{
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_PAREN)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_ELLIPSIS)
/* A parameter declaration begins with a decl-specifier,
which is either the "attribute" keyword, a storage class
specifier, or (usually) a type-specifier. */
&& !cp_lexer_next_token_is_decl_specifier_keyword (parser->lexer))
{
tree type;
tree pushed_scope = NULL_TREE;
unsigned saved_num_template_parameter_lists;
/* Names appearing in the type-specifier should be looked up
in the scope of the class. */
if (current_class_type)
type = NULL_TREE;
else
{
type = TREE_TYPE (type_decl);
if (TREE_CODE (type) == TYPENAME_TYPE)
{
type = resolve_typename_type (type,
/*only_current_p=*/false);
if (type == error_mark_node)
{
cp_parser_abort_tentative_parse (parser);
return false;
}
}
pushed_scope = push_scope (type);
}
/* Inside the constructor parameter list, surrounding
template-parameter-lists do not apply. */
saved_num_template_parameter_lists
= parser->num_template_parameter_lists;
parser->num_template_parameter_lists = 0;
/* Look for the type-specifier. */
cp_parser_type_specifier (parser,
CP_PARSER_FLAGS_NONE,
/*decl_specs=*/NULL,
/*is_declarator=*/true,
/*declares_class_or_enum=*/NULL,
/*is_cv_qualifier=*/NULL);
parser->num_template_parameter_lists
= saved_num_template_parameter_lists;
/* Leave the scope of the class. */
if (pushed_scope)
pop_scope (pushed_scope);
constructor_p = !cp_parser_error_occurred (parser);
}
}
else
constructor_p = false;
/* We did not really want to consume any tokens. */
cp_parser_abort_tentative_parse (parser);
return constructor_p;
}
/* Parse the definition of the function given by the DECL_SPECIFIERS,
ATTRIBUTES, and DECLARATOR. The access checks have been deferred;
they must be performed once we are in the scope of the function.
Returns the function defined. */
static tree
cp_parser_function_definition_from_specifiers_and_declarator
(cp_parser* parser,
cp_decl_specifier_seq *decl_specifiers,
tree attributes,
const cp_declarator *declarator)
{
tree fn;
bool success_p;
/* Begin the function-definition. */
success_p = start_function (decl_specifiers, declarator, attributes);
/* The things we're about to see are not directly qualified by any
template headers we've seen thus far. */
reset_specialization ();
/* If there were names looked up in the decl-specifier-seq that we
did not check, check them now. We must wait until we are in the
scope of the function to perform the checks, since the function
might be a friend. */
perform_deferred_access_checks ();
if (!success_p)
{
/* Skip the entire function. */
cp_parser_skip_to_end_of_block_or_statement (parser);
fn = error_mark_node;
}
/* APPLE LOCAL begin mainline 2006-12-02 5128086 */ \
else if (DECL_INITIAL (current_function_decl) != error_mark_node)
{
/* Seen already, skip it. An error message has already been output. */
cp_parser_skip_to_end_of_block_or_statement (parser);
fn = current_function_decl;
current_function_decl = NULL_TREE;
/* If this is a function from a class, pop the nested class. */
if (current_class_name)
pop_nested_class ();
}
/* APPLE LOCAL end mainline 2006-12-02 5128086 */ \
else
fn = cp_parser_function_definition_after_declarator (parser,
/*inline_p=*/false);
return fn;
}
/* Parse the part of a function-definition that follows the
declarator. INLINE_P is TRUE iff this function is an inline
function defined with a class-specifier.
Returns the function defined. */
static tree
cp_parser_function_definition_after_declarator (cp_parser* parser,
bool inline_p)
{
tree fn;
bool ctor_initializer_p = false;
bool saved_in_unbraced_linkage_specification_p;
bool saved_in_function_body;
unsigned saved_num_template_parameter_lists;
saved_in_function_body = parser->in_function_body;
parser->in_function_body = true;
/* If the next token is `return', then the code may be trying to
make use of the "named return value" extension that G++ used to
support. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_RETURN))
{
/* Consume the `return' keyword. */
cp_lexer_consume_token (parser->lexer);
/* Look for the identifier that indicates what value is to be
returned. */
cp_parser_identifier (parser);
/* Issue an error message. */
error ("named return values are no longer supported");
/* Skip tokens until we reach the start of the function body. */
while (true)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_OPEN_BRACE
|| token->type == CPP_EOF
|| token->type == CPP_PRAGMA_EOL)
break;
cp_lexer_consume_token (parser->lexer);
}
}
/* The `extern' in `extern "C" void f () { ... }' does not apply to
anything declared inside `f'. */
saved_in_unbraced_linkage_specification_p
= parser->in_unbraced_linkage_specification_p;
parser->in_unbraced_linkage_specification_p = false;
/* Inside the function, surrounding template-parameter-lists do not
apply. */
saved_num_template_parameter_lists
= parser->num_template_parameter_lists;
parser->num_template_parameter_lists = 0;
/* If the next token is `try', then we are looking at a
function-try-block. */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_TRY))
ctor_initializer_p = cp_parser_function_try_block (parser);
/* A function-try-block includes the function-body, so we only do
this next part if we're not processing a function-try-block. */
else
ctor_initializer_p
= cp_parser_ctor_initializer_opt_and_function_body (parser);
/* Finish the function. */
fn = finish_function ((ctor_initializer_p ? 1 : 0) |
(inline_p ? 2 : 0));
/* Generate code for it, if necessary. */
expand_or_defer_fn (fn);
/* Restore the saved values. */
parser->in_unbraced_linkage_specification_p
= saved_in_unbraced_linkage_specification_p;
parser->num_template_parameter_lists
= saved_num_template_parameter_lists;
parser->in_function_body = saved_in_function_body;
return fn;
}
/* Parse a template-declaration, assuming that the `export' (and
`extern') keywords, if present, has already been scanned. MEMBER_P
is as for cp_parser_template_declaration. */
static void
cp_parser_template_declaration_after_export (cp_parser* parser, bool member_p)
{
tree decl = NULL_TREE;
VEC (deferred_access_check,gc) *checks;
tree parameter_list;
bool friend_p = false;
bool need_lang_pop;
/* Look for the `template' keyword. */
if (!cp_parser_require_keyword (parser, RID_TEMPLATE, "`template'"))
return;
/* And the `<'. */
if (!cp_parser_require (parser, CPP_LESS, "`<'"))
return;
if (at_class_scope_p () && current_function_decl)
{
/* 14.5.2.2 [temp.mem]
A local class shall not have member templates. */
error ("invalid declaration of member template in local class");
cp_parser_skip_to_end_of_block_or_statement (parser);
return;
}
/* [temp]
A template ... shall not have C linkage. */
if (current_lang_name == lang_name_c)
{
error ("template with C linkage");
/* Give it C++ linkage to avoid confusing other parts of the
front end. */
push_lang_context (lang_name_cplusplus);
need_lang_pop = true;
}
else
need_lang_pop = false;
/* We cannot perform access checks on the template parameter
declarations until we know what is being declared, just as we
cannot check the decl-specifier list. */
push_deferring_access_checks (dk_deferred);
/* If the next token is `>', then we have an invalid
specialization. Rather than complain about an invalid template
parameter, issue an error message here. */
if (cp_lexer_next_token_is (parser->lexer, CPP_GREATER))
{
cp_parser_error (parser, "invalid explicit specialization");
begin_specialization ();
parameter_list = NULL_TREE;
}
else
/* Parse the template parameters. */
parameter_list = cp_parser_template_parameter_list (parser);
/* Get the deferred access checks from the parameter list. These
will be checked once we know what is being declared, as for a
member template the checks must be performed in the scope of the
class containing the member. */
checks = get_deferred_access_checks ();
/* Look for the `>'. */
cp_parser_skip_to_end_of_template_parameter_list (parser);
/* We just processed one more parameter list. */
++parser->num_template_parameter_lists;
/* If the next token is `template', there are more template
parameters. */
if (cp_lexer_next_token_is_keyword (parser->lexer,
RID_TEMPLATE))
cp_parser_template_declaration_after_export (parser, member_p);
else
{
/* There are no access checks when parsing a template, as we do not
know if a specialization will be a friend. */
push_deferring_access_checks (dk_no_check);
decl = cp_parser_single_declaration (parser,
checks,
member_p,
&friend_p);
pop_deferring_access_checks ();
/* If this is a member template declaration, let the front
end know. */
if (member_p && !friend_p && decl)
{
if (TREE_CODE (decl) == TYPE_DECL)
cp_parser_check_access_in_redeclaration (decl);
decl = finish_member_template_decl (decl);
}
else if (friend_p && decl && TREE_CODE (decl) == TYPE_DECL)
make_friend_class (current_class_type, TREE_TYPE (decl),
/*complain=*/true);
}
/* We are done with the current parameter list. */
--parser->num_template_parameter_lists;
pop_deferring_access_checks ();
/* Finish up. */
finish_template_decl (parameter_list);
/* Register member declarations. */
if (member_p && !friend_p && decl && !DECL_CLASS_TEMPLATE_P (decl))
finish_member_declaration (decl);
/* For the erroneous case of a template with C linkage, we pushed an
implicit C++ linkage scope; exit that scope now. */
if (need_lang_pop)
pop_lang_context ();
/* If DECL is a function template, we must return to parse it later.
(Even though there is no definition, there might be default
arguments that need handling.) */
if (member_p && decl
&& (TREE_CODE (decl) == FUNCTION_DECL
|| DECL_FUNCTION_TEMPLATE_P (decl)))
TREE_VALUE (parser->unparsed_functions_queues)
= tree_cons (NULL_TREE, decl,
TREE_VALUE (parser->unparsed_functions_queues));
}
/* Perform the deferred access checks from a template-parameter-list.
CHECKS is a TREE_LIST of access checks, as returned by
get_deferred_access_checks. */
static void
cp_parser_perform_template_parameter_access_checks (VEC (deferred_access_check,gc)* checks)
{
++processing_template_parmlist;
perform_access_checks (checks);
--processing_template_parmlist;
}
/* Parse a `decl-specifier-seq [opt] init-declarator [opt] ;' or
`function-definition' sequence. MEMBER_P is true, this declaration
appears in a class scope.
Returns the DECL for the declared entity. If FRIEND_P is non-NULL,
*FRIEND_P is set to TRUE iff the declaration is a friend. */
static tree
cp_parser_single_declaration (cp_parser* parser,
VEC (deferred_access_check,gc)* checks,
bool member_p,
bool* friend_p)
{
int declares_class_or_enum;
tree decl = NULL_TREE;
cp_decl_specifier_seq decl_specifiers;
bool function_definition_p = false;
/* This function is only used when processing a template
declaration. */
gcc_assert (innermost_scope_kind () == sk_template_parms
|| innermost_scope_kind () == sk_template_spec);
/* Defer access checks until we know what is being declared. */
push_deferring_access_checks (dk_deferred);
/* Try the `decl-specifier-seq [opt] init-declarator [opt]'
alternative. */
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_OPTIONAL,
&decl_specifiers,
&declares_class_or_enum);
if (friend_p)
*friend_p = cp_parser_friend_p (&decl_specifiers);
/* There are no template typedefs. */
if (decl_specifiers.specs[(int) ds_typedef])
{
error ("template declaration of %qs", "typedef");
decl = error_mark_node;
}
/* Gather up the access checks that occurred the
decl-specifier-seq. */
stop_deferring_access_checks ();
/* Check for the declaration of a template class. */
if (declares_class_or_enum)
{
if (cp_parser_declares_only_class_p (parser))
{
decl = shadow_tag (&decl_specifiers);
/* In this case:
struct C {
friend template <typename T> struct A<T>::B;
};
A<T>::B will be represented by a TYPENAME_TYPE, and
therefore not recognized by shadow_tag. */
if (friend_p && *friend_p
&& !decl
&& decl_specifiers.type
&& TYPE_P (decl_specifiers.type))
decl = decl_specifiers.type;
if (decl && decl != error_mark_node)
decl = TYPE_NAME (decl);
else
decl = error_mark_node;
/* Perform access checks for template parameters. */
cp_parser_perform_template_parameter_access_checks (checks);
}
}
/* If it's not a template class, try for a template function. If
the next token is a `;', then this declaration does not declare
anything. But, if there were errors in the decl-specifiers, then
the error might well have come from an attempted class-specifier.
In that case, there's no need to warn about a missing declarator. */
if (!decl
&& (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON)
|| decl_specifiers.type != error_mark_node))
decl = cp_parser_init_declarator (parser,
&decl_specifiers,
checks,
/*function_definition_allowed_p=*/true,
member_p,
declares_class_or_enum,
&function_definition_p);
pop_deferring_access_checks ();
/* Clear any current qualification; whatever comes next is the start
of something new. */
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
/* Look for a trailing `;' after the declaration. */
if (!function_definition_p
&& (decl == error_mark_node
|| !cp_parser_require (parser, CPP_SEMICOLON, "`;'")))
cp_parser_skip_to_end_of_block_or_statement (parser);
return decl;
}
/* Parse a cast-expression that is not the operand of a unary "&". */
static tree
cp_parser_simple_cast_expression (cp_parser *parser)
{
return cp_parser_cast_expression (parser, /*address_p=*/false,
/*cast_p=*/false);
}
/* Parse a functional cast to TYPE. Returns an expression
representing the cast. */
static tree
cp_parser_functional_cast (cp_parser* parser, tree type)
{
tree expression_list;
tree cast;
expression_list
= cp_parser_parenthesized_expression_list (parser, false,
/*cast_p=*/true,
/*non_constant_p=*/NULL);
cast = build_functional_cast (type, expression_list);
/* [expr.const]/1: In an integral constant expression "only type
conversions to integral or enumeration type can be used". */
if (TREE_CODE (type) == TYPE_DECL)
type = TREE_TYPE (type);
if (cast != error_mark_node
&& !cast_valid_in_integral_constant_expression_p (type)
&& (cp_parser_non_integral_constant_expression
(parser, "a call to a constructor")))
return error_mark_node;
return cast;
}
/* Save the tokens that make up the body of a member function defined
in a class-specifier. The DECL_SPECIFIERS and DECLARATOR have
already been parsed. The ATTRIBUTES are any GNU "__attribute__"
specifiers applied to the declaration. Returns the FUNCTION_DECL
for the member function. */
static tree
cp_parser_save_member_function_body (cp_parser* parser,
cp_decl_specifier_seq *decl_specifiers,
cp_declarator *declarator,
tree attributes)
{
cp_token *first;
cp_token *last;
tree fn;
/* Create the function-declaration. */
fn = start_method (decl_specifiers, declarator, attributes);
/* If something went badly wrong, bail out now. */
if (fn == error_mark_node)
{
/* If there's a function-body, skip it. */
if (cp_parser_token_starts_function_definition_p
(cp_lexer_peek_token (parser->lexer)))
cp_parser_skip_to_end_of_block_or_statement (parser);
return error_mark_node;
}
/* Remember it, if there default args to post process. */
cp_parser_save_default_args (parser, fn);
/* Save away the tokens that make up the body of the
function. */
first = parser->lexer->next_token;
cp_parser_cache_group (parser, CPP_CLOSE_BRACE, /*depth=*/0);
/* Handle function try blocks. */
while (cp_lexer_next_token_is_keyword (parser->lexer, RID_CATCH))
cp_parser_cache_group (parser, CPP_CLOSE_BRACE, /*depth=*/0);
last = parser->lexer->next_token;
/* Save away the inline definition; we will process it when the
class is complete. */
DECL_PENDING_INLINE_INFO (fn) = cp_token_cache_new (first, last);
DECL_PENDING_INLINE_P (fn) = 1;
/* We need to know that this was defined in the class, so that
friend templates are handled correctly. */
DECL_INITIALIZED_IN_CLASS_P (fn) = 1;
/* We're done with the inline definition. */
finish_method (fn);
/* Add FN to the queue of functions to be parsed later. */
TREE_VALUE (parser->unparsed_functions_queues)
= tree_cons (NULL_TREE, fn,
TREE_VALUE (parser->unparsed_functions_queues));
return fn;
}
/* Parse a template-argument-list, as well as the trailing ">" (but
not the opening ">"). See cp_parser_template_argument_list for the
return value. */
static tree
cp_parser_enclosed_template_argument_list (cp_parser* parser)
{
tree arguments;
tree saved_scope;
tree saved_qualifying_scope;
tree saved_object_scope;
bool saved_greater_than_is_operator_p;
bool saved_skip_evaluation;
/* [temp.names]
When parsing a template-id, the first non-nested `>' is taken as
the end of the template-argument-list rather than a greater-than
operator. */
saved_greater_than_is_operator_p
= parser->greater_than_is_operator_p;
parser->greater_than_is_operator_p = false;
/* Parsing the argument list may modify SCOPE, so we save it
here. */
saved_scope = parser->scope;
saved_qualifying_scope = parser->qualifying_scope;
saved_object_scope = parser->object_scope;
/* We need to evaluate the template arguments, even though this
template-id may be nested within a "sizeof". */
saved_skip_evaluation = skip_evaluation;
skip_evaluation = false;
/* Parse the template-argument-list itself. */
if (cp_lexer_next_token_is (parser->lexer, CPP_GREATER))
arguments = NULL_TREE;
else
arguments = cp_parser_template_argument_list (parser);
/* Look for the `>' that ends the template-argument-list. If we find
a '>>' instead, it's probably just a typo. */
if (cp_lexer_next_token_is (parser->lexer, CPP_RSHIFT))
{
if (!saved_greater_than_is_operator_p)
{
/* If we're in a nested template argument list, the '>>' has
to be a typo for '> >'. We emit the error message, but we
continue parsing and we push a '>' as next token, so that
the argument list will be parsed correctly. Note that the
global source location is still on the token before the
'>>', so we need to say explicitly where we want it. */
cp_token *token = cp_lexer_peek_token (parser->lexer);
error ("%H%<>>%> should be %<> >%> "
"within a nested template argument list",
&token->location);
/* ??? Proper recovery should terminate two levels of
template argument list here. */
token->type = CPP_GREATER;
}
else
{
/* If this is not a nested template argument list, the '>>'
is a typo for '>'. Emit an error message and continue.
Same deal about the token location, but here we can get it
right by consuming the '>>' before issuing the diagnostic. */
cp_lexer_consume_token (parser->lexer);
error ("spurious %<>>%>, use %<>%> to terminate "
"a template argument list");
}
}
else
cp_parser_skip_to_end_of_template_parameter_list (parser);
/* The `>' token might be a greater-than operator again now. */
parser->greater_than_is_operator_p
= saved_greater_than_is_operator_p;
/* Restore the SAVED_SCOPE. */
parser->scope = saved_scope;
parser->qualifying_scope = saved_qualifying_scope;
parser->object_scope = saved_object_scope;
skip_evaluation = saved_skip_evaluation;
return arguments;
}
/* MEMBER_FUNCTION is a member function, or a friend. If default
arguments, or the body of the function have not yet been parsed,
parse them now. */
static void
cp_parser_late_parsing_for_member (cp_parser* parser, tree member_function)
{
/* If this member is a template, get the underlying
FUNCTION_DECL. */
if (DECL_FUNCTION_TEMPLATE_P (member_function))
member_function = DECL_TEMPLATE_RESULT (member_function);
/* There should not be any class definitions in progress at this
point; the bodies of members are only parsed outside of all class
definitions. */
gcc_assert (parser->num_classes_being_defined == 0);
/* While we're parsing the member functions we might encounter more
classes. We want to handle them right away, but we don't want
them getting mixed up with functions that are currently in the
queue. */
parser->unparsed_functions_queues
= tree_cons (NULL_TREE, NULL_TREE, parser->unparsed_functions_queues);
/* Make sure that any template parameters are in scope. */
maybe_begin_member_template_processing (member_function);
/* If the body of the function has not yet been parsed, parse it
now. */
if (DECL_PENDING_INLINE_P (member_function))
{
tree function_scope;
cp_token_cache *tokens;
/* The function is no longer pending; we are processing it. */
tokens = DECL_PENDING_INLINE_INFO (member_function);
DECL_PENDING_INLINE_INFO (member_function) = NULL;
DECL_PENDING_INLINE_P (member_function) = 0;
/* If this is a local class, enter the scope of the containing
function. */
function_scope = current_function_decl;
if (function_scope)
push_function_context_to (function_scope);
/* Push the body of the function onto the lexer stack. */
cp_parser_push_lexer_for_tokens (parser, tokens);
/* Let the front end know that we going to be defining this
function. */
start_preparsed_function (member_function, NULL_TREE,
SF_PRE_PARSED | SF_INCLASS_INLINE);
/* Don't do access checking if it is a templated function. */
if (processing_template_decl)
push_deferring_access_checks (dk_no_check);
/* Now, parse the body of the function. */
cp_parser_function_definition_after_declarator (parser,
/*inline_p=*/true);
if (processing_template_decl)
pop_deferring_access_checks ();
/* Leave the scope of the containing function. */
if (function_scope)
pop_function_context_from (function_scope);
cp_parser_pop_lexer (parser);
}
/* Remove any template parameters from the symbol table. */
maybe_end_member_template_processing ();
/* Restore the queue. */
parser->unparsed_functions_queues
= TREE_CHAIN (parser->unparsed_functions_queues);
}
/* If DECL contains any default args, remember it on the unparsed
functions queue. */
static void
cp_parser_save_default_args (cp_parser* parser, tree decl)
{
tree probe;
for (probe = TYPE_ARG_TYPES (TREE_TYPE (decl));
probe;
probe = TREE_CHAIN (probe))
if (TREE_PURPOSE (probe))
{
TREE_PURPOSE (parser->unparsed_functions_queues)
= tree_cons (current_class_type, decl,
TREE_PURPOSE (parser->unparsed_functions_queues));
break;
}
}
/* FN is a FUNCTION_DECL which may contains a parameter with an
unparsed DEFAULT_ARG. Parse the default args now. This function
assumes that the current scope is the scope in which the default
argument should be processed. */
static void
cp_parser_late_parsing_default_args (cp_parser *parser, tree fn)
{
bool saved_local_variables_forbidden_p;
tree parm;
/* While we're parsing the default args, we might (due to the
statement expression extension) encounter more classes. We want
to handle them right away, but we don't want them getting mixed
up with default args that are currently in the queue. */
parser->unparsed_functions_queues
= tree_cons (NULL_TREE, NULL_TREE, parser->unparsed_functions_queues);
/* Local variable names (and the `this' keyword) may not appear
in a default argument. */
saved_local_variables_forbidden_p = parser->local_variables_forbidden_p;
parser->local_variables_forbidden_p = true;
for (parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
parm;
parm = TREE_CHAIN (parm))
{
cp_token_cache *tokens;
tree default_arg = TREE_PURPOSE (parm);
tree parsed_arg;
VEC(tree,gc) *insts;
tree copy;
unsigned ix;
if (!default_arg)
continue;
if (TREE_CODE (default_arg) != DEFAULT_ARG)
/* This can happen for a friend declaration for a function
already declared with default arguments. */
continue;
/* Push the saved tokens for the default argument onto the parser's
lexer stack. */
tokens = DEFARG_TOKENS (default_arg);
cp_parser_push_lexer_for_tokens (parser, tokens);
/* Parse the assignment-expression. */
parsed_arg = cp_parser_assignment_expression (parser, /*cast_p=*/false);
if (!processing_template_decl)
parsed_arg = check_default_argument (TREE_VALUE (parm), parsed_arg);
TREE_PURPOSE (parm) = parsed_arg;
/* Update any instantiations we've already created. */
for (insts = DEFARG_INSTANTIATIONS (default_arg), ix = 0;
VEC_iterate (tree, insts, ix, copy); ix++)
TREE_PURPOSE (copy) = parsed_arg;
/* If the token stream has not been completely used up, then
there was extra junk after the end of the default
argument. */
if (!cp_lexer_next_token_is (parser->lexer, CPP_EOF))
cp_parser_error (parser, "expected %<,%>");
/* Revert to the main lexer. */
cp_parser_pop_lexer (parser);
}
/* Make sure no default arg is missing. */
check_default_args (fn);
/* Restore the state of local_variables_forbidden_p. */
parser->local_variables_forbidden_p = saved_local_variables_forbidden_p;
/* Restore the queue. */
parser->unparsed_functions_queues
= TREE_CHAIN (parser->unparsed_functions_queues);
}
/* Parse the operand of `sizeof' (or a similar operator). Returns
either a TYPE or an expression, depending on the form of the
input. The KEYWORD indicates which kind of expression we have
encountered. */
static tree
cp_parser_sizeof_operand (cp_parser* parser, enum rid keyword)
{
static const char *format;
tree expr = NULL_TREE;
const char *saved_message;
bool saved_integral_constant_expression_p;
bool saved_non_integral_constant_expression_p;
/* Initialize FORMAT the first time we get here. */
if (!format)
format = "types may not be defined in '%s' expressions";
/* Types cannot be defined in a `sizeof' expression. Save away the
old message. */
saved_message = parser->type_definition_forbidden_message;
/* And create the new one. */
parser->type_definition_forbidden_message
= XNEWVEC (const char, strlen (format)
+ strlen (IDENTIFIER_POINTER (ridpointers[keyword]))
+ 1 /* `\0' */);
sprintf ((char *) parser->type_definition_forbidden_message,
format, IDENTIFIER_POINTER (ridpointers[keyword]));
/* The restrictions on constant-expressions do not apply inside
sizeof expressions. */
saved_integral_constant_expression_p
= parser->integral_constant_expression_p;
saved_non_integral_constant_expression_p
= parser->non_integral_constant_expression_p;
parser->integral_constant_expression_p = false;
/* Do not actually evaluate the expression. */
++skip_evaluation;
/* If it's a `(', then we might be looking at the type-id
construction. */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
tree type;
bool saved_in_type_id_in_expr_p;
/* We can't be sure yet whether we're looking at a type-id or an
expression. */
cp_parser_parse_tentatively (parser);
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Parse the type-id. */
saved_in_type_id_in_expr_p = parser->in_type_id_in_expr_p;
parser->in_type_id_in_expr_p = true;
type = cp_parser_type_id (parser);
parser->in_type_id_in_expr_p = saved_in_type_id_in_expr_p;
/* Now, look for the trailing `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "%<)%>");
/* If all went well, then we're done. */
if (cp_parser_parse_definitely (parser))
{
cp_decl_specifier_seq decl_specs;
/* Build a trivial decl-specifier-seq. */
clear_decl_specs (&decl_specs);
decl_specs.type = type;
/* Call grokdeclarator to figure out what type this is. */
expr = grokdeclarator (NULL,
&decl_specs,
TYPENAME,
/*initialized=*/0,
/*attrlist=*/NULL);
}
}
/* If the type-id production did not work out, then we must be
looking at the unary-expression production. */
if (!expr)
expr = cp_parser_unary_expression (parser, /*address_p=*/false,
/*cast_p=*/false);
/* Go back to evaluating expressions. */
--skip_evaluation;
/* Free the message we created. */
free ((char *) parser->type_definition_forbidden_message);
/* And restore the old one. */
parser->type_definition_forbidden_message = saved_message;
parser->integral_constant_expression_p
= saved_integral_constant_expression_p;
parser->non_integral_constant_expression_p
= saved_non_integral_constant_expression_p;
return expr;
}
/* If the current declaration has no declarator, return true. */
static bool
cp_parser_declares_only_class_p (cp_parser *parser)
{
/* If the next token is a `;' or a `,' then there is no
declarator. */
return (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)
|| cp_lexer_next_token_is (parser->lexer, CPP_COMMA));
}
/* Update the DECL_SPECS to reflect the storage class indicated by
KEYWORD. */
static void
cp_parser_set_storage_class (cp_parser *parser,
cp_decl_specifier_seq *decl_specs,
enum rid keyword)
{
cp_storage_class storage_class;
if (parser->in_unbraced_linkage_specification_p)
{
error ("invalid use of %qD in linkage specification",
ridpointers[keyword]);
return;
}
else if (decl_specs->storage_class != sc_none)
{
decl_specs->conflicting_specifiers_p = true;
return;
}
if ((keyword == RID_EXTERN || keyword == RID_STATIC)
&& decl_specs->specs[(int) ds_thread])
{
error ("%<__thread%> before %qD", ridpointers[keyword]);
decl_specs->specs[(int) ds_thread] = 0;
}
switch (keyword)
{
case RID_AUTO:
storage_class = sc_auto;
break;
case RID_REGISTER:
storage_class = sc_register;
break;
case RID_STATIC:
storage_class = sc_static;
break;
case RID_EXTERN:
storage_class = sc_extern;
break;
case RID_MUTABLE:
storage_class = sc_mutable;
break;
default:
gcc_unreachable ();
}
decl_specs->storage_class = storage_class;
/* A storage class specifier cannot be applied alongside a typedef
specifier. If there is a typedef specifier present then set
conflicting_specifiers_p which will trigger an error later
on in grokdeclarator. */
if (decl_specs->specs[(int)ds_typedef])
decl_specs->conflicting_specifiers_p = true;
}
/* Update the DECL_SPECS to reflect the TYPE_SPEC. If USER_DEFINED_P
is true, the type is a user-defined type; otherwise it is a
built-in type specified by a keyword. */
static void
cp_parser_set_decl_spec_type (cp_decl_specifier_seq *decl_specs,
tree type_spec,
bool user_defined_p)
{
decl_specs->any_specifiers_p = true;
/* If the user tries to redeclare bool or wchar_t (with, for
example, in "typedef int wchar_t;") we remember that this is what
happened. In system headers, we ignore these declarations so
that G++ can work with system headers that are not C++-safe. */
if (decl_specs->specs[(int) ds_typedef]
&& !user_defined_p
&& (type_spec == boolean_type_node
|| type_spec == wchar_type_node)
&& (decl_specs->type
|| decl_specs->specs[(int) ds_long]
|| decl_specs->specs[(int) ds_short]
|| decl_specs->specs[(int) ds_unsigned]
|| decl_specs->specs[(int) ds_signed]))
{
decl_specs->redefined_builtin_type = type_spec;
if (!decl_specs->type)
{
decl_specs->type = type_spec;
decl_specs->user_defined_type_p = false;
}
}
else if (decl_specs->type)
decl_specs->multiple_types_p = true;
else
{
decl_specs->type = type_spec;
decl_specs->user_defined_type_p = user_defined_p;
decl_specs->redefined_builtin_type = NULL_TREE;
}
}
/* DECL_SPECIFIERS is the representation of a decl-specifier-seq.
Returns TRUE iff `friend' appears among the DECL_SPECIFIERS. */
static bool
cp_parser_friend_p (const cp_decl_specifier_seq *decl_specifiers)
{
return decl_specifiers->specs[(int) ds_friend] != 0;
}
/* If the next token is of the indicated TYPE, consume it. Otherwise,
issue an error message indicating that TOKEN_DESC was expected.
Returns the token consumed, if the token had the appropriate type.
Otherwise, returns NULL. */
static cp_token *
cp_parser_require (cp_parser* parser,
enum cpp_ttype type,
const char* token_desc)
{
if (cp_lexer_next_token_is (parser->lexer, type))
return cp_lexer_consume_token (parser->lexer);
else
{
/* Output the MESSAGE -- unless we're parsing tentatively. */
if (!cp_parser_simulate_error (parser))
{
char *message = concat ("expected ", token_desc, NULL);
cp_parser_error (parser, message);
free (message);
}
return NULL;
}
}
/* An error message is produced if the next token is not '>'.
All further tokens are skipped until the desired token is
found or '{', '}', ';' or an unbalanced ')' or ']'. */
static void
cp_parser_skip_to_end_of_template_parameter_list (cp_parser* parser)
{
/* Current level of '< ... >'. */
unsigned level = 0;
/* Ignore '<' and '>' nested inside '( ... )' or '[ ... ]'. */
unsigned nesting_depth = 0;
/* Are we ready, yet? If not, issue error message. */
if (cp_parser_require (parser, CPP_GREATER, "%<>%>"))
return;
/* Skip tokens until the desired token is found. */
while (true)
{
/* Peek at the next token. */
switch (cp_lexer_peek_token (parser->lexer)->type)
{
case CPP_LESS:
if (!nesting_depth)
++level;
break;
case CPP_GREATER:
if (!nesting_depth && level-- == 0)
{
/* We've reached the token we want, consume it and stop. */
cp_lexer_consume_token (parser->lexer);
return;
}
break;
case CPP_OPEN_PAREN:
case CPP_OPEN_SQUARE:
++nesting_depth;
break;
case CPP_CLOSE_PAREN:
case CPP_CLOSE_SQUARE:
if (nesting_depth-- == 0)
return;
break;
case CPP_EOF:
case CPP_PRAGMA_EOL:
case CPP_SEMICOLON:
case CPP_OPEN_BRACE:
case CPP_CLOSE_BRACE:
/* The '>' was probably forgotten, don't look further. */
return;
default:
break;
}
/* Consume this token. */
cp_lexer_consume_token (parser->lexer);
}
}
/* If the next token is the indicated keyword, consume it. Otherwise,
issue an error message indicating that TOKEN_DESC was expected.
Returns the token consumed, if the token had the appropriate type.
Otherwise, returns NULL. */
static cp_token *
cp_parser_require_keyword (cp_parser* parser,
enum rid keyword,
const char* token_desc)
{
cp_token *token = cp_parser_require (parser, CPP_KEYWORD, token_desc);
if (token && token->keyword != keyword)
{
dyn_string_t error_msg;
/* Format the error message. */
error_msg = dyn_string_new (0);
dyn_string_append_cstr (error_msg, "expected ");
dyn_string_append_cstr (error_msg, token_desc);
cp_parser_error (parser, error_msg->s);
dyn_string_delete (error_msg);
return NULL;
}
return token;
}
/* Returns TRUE iff TOKEN is a token that can begin the body of a
function-definition. */
static bool
cp_parser_token_starts_function_definition_p (cp_token* token)
{
return (/* An ordinary function-body begins with an `{'. */
token->type == CPP_OPEN_BRACE
/* A ctor-initializer begins with a `:'. */
|| token->type == CPP_COLON
/* A function-try-block begins with `try'. */
|| token->keyword == RID_TRY
/* The named return value extension begins with `return'. */
|| token->keyword == RID_RETURN);
}
/* Returns TRUE iff the next token is the ":" or "{" beginning a class
definition. */
static bool
cp_parser_next_token_starts_class_definition_p (cp_parser *parser)
{
cp_token *token;
token = cp_lexer_peek_token (parser->lexer);
return (token->type == CPP_OPEN_BRACE || token->type == CPP_COLON);
}
/* Returns TRUE iff the next token is the "," or ">" ending a
template-argument. */
static bool
cp_parser_next_token_ends_template_argument_p (cp_parser *parser)
{
cp_token *token;
token = cp_lexer_peek_token (parser->lexer);
return (token->type == CPP_COMMA || token->type == CPP_GREATER);
}
/* Returns TRUE iff the n-th token is a "<", or the n-th is a "[" and the
(n+1)-th is a ":" (which is a possible digraph typo for "< ::"). */
static bool
cp_parser_nth_token_starts_template_argument_list_p (cp_parser * parser,
size_t n)
{
cp_token *token;
token = cp_lexer_peek_nth_token (parser->lexer, n);
if (token->type == CPP_LESS)
return true;
/* Check for the sequence `<::' in the original code. It would be lexed as
`[:', where `[' is a digraph, and there is no whitespace before
`:'. */
if (token->type == CPP_OPEN_SQUARE && token->flags & DIGRAPH)
{
cp_token *token2;
token2 = cp_lexer_peek_nth_token (parser->lexer, n+1);
if (token2->type == CPP_COLON && !(token2->flags & PREV_WHITE))
return true;
}
return false;
}
/* Returns the kind of tag indicated by TOKEN, if it is a class-key,
or none_type otherwise. */
static enum tag_types
cp_parser_token_is_class_key (cp_token* token)
{
switch (token->keyword)
{
case RID_CLASS:
return class_type;
case RID_STRUCT:
return record_type;
case RID_UNION:
return union_type;
default:
return none_type;
}
}
/* Issue an error message if the CLASS_KEY does not match the TYPE. */
static void
cp_parser_check_class_key (enum tag_types class_key, tree type)
{
if ((TREE_CODE (type) == UNION_TYPE) != (class_key == union_type))
pedwarn ("%qs tag used in naming %q#T",
class_key == union_type ? "union"
: class_key == record_type ? "struct" : "class",
type);
}
/* Issue an error message if DECL is redeclared with different
access than its original declaration [class.access.spec/3].
This applies to nested classes and nested class templates.
[class.mem/1]. */
static void
cp_parser_check_access_in_redeclaration (tree decl)
{
if (!CLASS_TYPE_P (TREE_TYPE (decl)))
return;
if ((TREE_PRIVATE (decl)
!= (current_access_specifier == access_private_node))
|| (TREE_PROTECTED (decl)
!= (current_access_specifier == access_protected_node)))
error ("%qD redeclared with different access", decl);
}
/* Look for the `template' keyword, as a syntactic disambiguator.
Return TRUE iff it is present, in which case it will be
consumed. */
static bool
cp_parser_optional_template_keyword (cp_parser *parser)
{
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_TEMPLATE))
{
/* The `template' keyword can only be used within templates;
outside templates the parser can always figure out what is a
template and what is not. */
if (!processing_template_decl)
{
error ("%<template%> (as a disambiguator) is only allowed "
"within templates");
/* If this part of the token stream is rescanned, the same
error message would be generated. So, we purge the token
from the stream. */
cp_lexer_purge_token (parser->lexer);
return false;
}
else
{
/* Consume the `template' keyword. */
cp_lexer_consume_token (parser->lexer);
return true;
}
}
return false;
}
/* The next token is a CPP_NESTED_NAME_SPECIFIER. Consume the token,
set PARSER->SCOPE, and perform other related actions. */
static void
cp_parser_pre_parsed_nested_name_specifier (cp_parser *parser)
{
int i;
struct tree_check *check_value;
deferred_access_check *chk;
VEC (deferred_access_check,gc) *checks;
/* Get the stored value. */
check_value = cp_lexer_consume_token (parser->lexer)->u.tree_check_value;
/* Perform any access checks that were deferred. */
checks = check_value->checks;
if (checks)
{
for (i = 0 ;
VEC_iterate (deferred_access_check, checks, i, chk) ;
++i)
{
perform_or_defer_access_check (chk->binfo,
chk->decl,
chk->diag_decl);
}
}
/* Set the scope from the stored value. */
parser->scope = check_value->value;
parser->qualifying_scope = check_value->qualifying_scope;
parser->object_scope = NULL_TREE;
}
/* Consume tokens up through a non-nested END token. */
static void
cp_parser_cache_group (cp_parser *parser,
enum cpp_ttype end,
unsigned depth)
{
while (true)
{
cp_token *token;
/* Abort a parenthesized expression if we encounter a brace. */
if ((end == CPP_CLOSE_PAREN || depth == 0)
&& cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
return;
/* If we've reached the end of the file, stop. */
if (cp_lexer_next_token_is (parser->lexer, CPP_EOF)
|| (end != CPP_PRAGMA_EOL
&& cp_lexer_next_token_is (parser->lexer, CPP_PRAGMA_EOL)))
return;
/* Consume the next token. */
token = cp_lexer_consume_token (parser->lexer);
/* See if it starts a new group. */
if (token->type == CPP_OPEN_BRACE)
{
cp_parser_cache_group (parser, CPP_CLOSE_BRACE, depth + 1);
if (depth == 0)
return;
}
else if (token->type == CPP_OPEN_PAREN)
cp_parser_cache_group (parser, CPP_CLOSE_PAREN, depth + 1);
else if (token->type == CPP_PRAGMA)
cp_parser_cache_group (parser, CPP_PRAGMA_EOL, depth + 1);
else if (token->type == end)
return;
}
}
/* Begin parsing tentatively. We always save tokens while parsing
tentatively so that if the tentative parsing fails we can restore the
tokens. */
static void
cp_parser_parse_tentatively (cp_parser* parser)
{
/* Enter a new parsing context. */
parser->context = cp_parser_context_new (parser->context);
/* Begin saving tokens. */
cp_lexer_save_tokens (parser->lexer);
/* In order to avoid repetitive access control error messages,
access checks are queued up until we are no longer parsing
tentatively. */
push_deferring_access_checks (dk_deferred);
}
/* Commit to the currently active tentative parse. */
static void
cp_parser_commit_to_tentative_parse (cp_parser* parser)
{
cp_parser_context *context;
cp_lexer *lexer;
/* Mark all of the levels as committed. */
lexer = parser->lexer;
for (context = parser->context; context->next; context = context->next)
{
if (context->status == CP_PARSER_STATUS_KIND_COMMITTED)
break;
context->status = CP_PARSER_STATUS_KIND_COMMITTED;
while (!cp_lexer_saving_tokens (lexer))
lexer = lexer->next;
cp_lexer_commit_tokens (lexer);
}
}
/* Abort the currently active tentative parse. All consumed tokens
will be rolled back, and no diagnostics will be issued. */
static void
cp_parser_abort_tentative_parse (cp_parser* parser)
{
cp_parser_simulate_error (parser);
/* Now, pretend that we want to see if the construct was
successfully parsed. */
cp_parser_parse_definitely (parser);
}
/* Stop parsing tentatively. If a parse error has occurred, restore the
token stream. Otherwise, commit to the tokens we have consumed.
Returns true if no error occurred; false otherwise. */
static bool
cp_parser_parse_definitely (cp_parser* parser)
{
bool error_occurred;
cp_parser_context *context;
/* Remember whether or not an error occurred, since we are about to
destroy that information. */
error_occurred = cp_parser_error_occurred (parser);
/* Remove the topmost context from the stack. */
context = parser->context;
parser->context = context->next;
/* If no parse errors occurred, commit to the tentative parse. */
if (!error_occurred)
{
/* Commit to the tokens read tentatively, unless that was
already done. */
if (context->status != CP_PARSER_STATUS_KIND_COMMITTED)
cp_lexer_commit_tokens (parser->lexer);
pop_to_parent_deferring_access_checks ();
}
/* Otherwise, if errors occurred, roll back our state so that things
are just as they were before we began the tentative parse. */
else
{
cp_lexer_rollback_tokens (parser->lexer);
pop_deferring_access_checks ();
}
/* Add the context to the front of the free list. */
context->next = cp_parser_context_free_list;
cp_parser_context_free_list = context;
return !error_occurred;
}
/* Returns true if we are parsing tentatively and are not committed to
this tentative parse. */
static bool
cp_parser_uncommitted_to_tentative_parse_p (cp_parser* parser)
{
return (cp_parser_parsing_tentatively (parser)
&& parser->context->status != CP_PARSER_STATUS_KIND_COMMITTED);
}
/* Returns nonzero iff an error has occurred during the most recent
tentative parse. */
static bool
cp_parser_error_occurred (cp_parser* parser)
{
return (cp_parser_parsing_tentatively (parser)
&& parser->context->status == CP_PARSER_STATUS_KIND_ERROR);
}
/* Returns nonzero if GNU extensions are allowed. */
static bool
cp_parser_allow_gnu_extensions_p (cp_parser* parser)
{
return parser->allow_gnu_extensions_p;
}
/* Objective-C++ Productions */
/* APPLE LOCAL begin CW asm blocks */
/* This is the section of CW-asm-specific parsing functions. */
static tree
cp_parser_iasm_compound_statement (cp_parser *parser)
{
tree compound_stmt;
iasm_state = iasm_asm;
inside_iasm_block = true;
iasm_kill_regs = true;
/* LLVM LOCAL */
iasm_label_counter = 0;
if (!cp_parser_require (parser, CPP_OPEN_BRACE, "`{'"))
return error_mark_node;
/* Begin the compound-statement. */
compound_stmt = begin_compound_stmt (/*has_no_scope=*/false);
/* Parse an (optional) statement-seq. */
cp_parser_iasm_line_seq_opt (parser);
/* Finish the compound-statement. */
finish_compound_stmt (compound_stmt);
/* Consume the `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
/* We're done with the block of asm. */
iasm_end_block ();
iasm_state = iasm_none;
return compound_stmt;
}
static void
cp_parser_iasm_top_statement (cp_parser *parser)
{
tree compound_stmt;
iasm_state = iasm_asm;
inside_iasm_block = true;
iasm_kill_regs = true;
/* LLVM LOCAL */
iasm_label_counter = 0;
/* Begin the compound-statement. */
compound_stmt = begin_compound_stmt (/*has_no_scope=*/false);
if (!cp_lexer_iasm_bol (parser->lexer))
{
/* Parse a line. */
cp_parser_iasm_line (parser);
}
/* Finish the compound-statement. */
finish_compound_stmt (compound_stmt);
/* We're done with the block of asm. */
iasm_end_block ();
iasm_state = iasm_none;
}
static void
cp_parser_iasm_declaration_seq_opt (cp_parser* parser)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_NAME
&& !iasm_typename_or_reserved (token->u.value))
return;
/* Scan declarations until there aren't any more. */
while (true)
{
/* If we're looking at a `}', then we've run out of statements. */
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE)
|| cp_lexer_next_token_is (parser->lexer, CPP_EOF))
break;
/* Parse a declaration. */
cp_parser_simple_declaration (parser, false);
/* CPP_PRAGMA is a #pragma inside a function body, which
constitutes a declaration all its own. */
if (token->type == CPP_PRAGMA)
cp_parser_pragma (parser, pragma_external);
if (iasm_state >= iasm_decls
&& (cp_lexer_iasm_bol (parser->lexer)
|| cp_lexer_next_token_is (parser->lexer, CPP_NAME)))
break;
}
}
/* Parse an (optional) line-seq.
line-seq:
line
line-seq [opt] line */
static void
cp_parser_iasm_line_seq_opt (cp_parser* parser)
{
/* Scan lines of asm until there aren't any more. */
while (true)
{
/* If we're looking at a `}', then we've run out of lines. */
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE)
|| cp_lexer_next_token_is (parser->lexer, CPP_EOF))
break;
/* Parse the line. */
cp_parser_iasm_line (parser);
}
}
static void
cp_parser_iasm_line (cp_parser* parser)
{
cp_parser_iasm_statement_seq_opt (parser);
}
/* Skip tokens until the end of line is seen. */
static void
cp_parser_iasm_skip_to_eol (cp_parser *parser)
{
while (true)
{
cp_token *token;
/* Do CPP_NUMBER specially to avoid errors on things like ; 1st
when doing MS-style asms. */
if ((token = parser->lexer->next_token)->type == CPP_NUMBER
|| token->type == CPP_HASH
|| token->type == CPP_PASTE
|| token->type == CPP_OTHER)
;
else
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* If we've run out of tokens, stop. */
if (token->type == CPP_EOF)
break;
/* If the next token starts a new line, stop. */
if (cp_lexer_iasm_bol (parser->lexer))
break;
/* Otherwise, consume the token. */
cp_lexer_consume_token (parser->lexer);
}
}
static void
cp_parser_iasm_maybe_skip_comments (cp_parser *parser)
{
if (flag_ms_asms
&& cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
{
/* Eat the ';', then skip rest of characters on this line. */
cp_lexer_consume_token (parser->lexer);
cp_parser_iasm_skip_to_eol (parser);
}
}
/* Parse an asm line. The first token cannot be at the beginning of
the line. */
static void
cp_parser_iasm_statement_seq_opt (cp_parser* parser)
{
int check;
/* Scan statements until there aren't any more. */
while (true)
{
check = 0;
/* Semicolons divide up individual statements. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
{
/* ; denotes comments in MS-style asms. */
if (flag_ms_asms)
{
cp_parser_iasm_maybe_skip_comments (parser);
return;
}
cp_lexer_consume_token (parser->lexer);
}
else if (cp_lexer_next_token_is_keyword (parser->lexer, RID_ASM))
{
cp_lexer_consume_token (parser->lexer);
}
else
{
/* Parse a single statement. */
cp_parser_iasm_statement (parser);
check = 1;
}
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE)
|| cp_lexer_next_token_is (parser->lexer, CPP_EOF)
/* We parse at most, one line. */
|| cp_lexer_iasm_bol (parser->lexer))
return;
if (check
&& !(cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE)
|| cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)
|| cp_lexer_next_token_is_keyword (parser->lexer, RID_ASM)
|| cp_lexer_iasm_bol (parser->lexer)))
{
cp_parser_error (parser, "expected `;' or `}' `asm' or end-of-line");
}
}
if (!cp_lexer_iasm_bol (parser->lexer))
cp_parser_iasm_maybe_skip_comments (parser);
}
/* Build an identifier comprising the string passed and the
next token. */
static tree
iasm_build_identifier_string (cp_parser* parser, const char* str)
{
char *buf;
int len;
tree id;
if (strcmp (str, ".") == 0
&& (cp_lexer_peek_token (parser->lexer)->flags & PREV_WHITE) == 0)
{
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_SHORT))
{
cp_lexer_consume_token (parser->lexer);
return get_identifier (".short");
}
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_LONG))
{
cp_lexer_consume_token (parser->lexer);
return get_identifier (".long");
}
}
id = cp_parser_iasm_identifier_or_number (parser);
len = strlen (str);
buf = (char *) alloca (IDENTIFIER_LENGTH (id) + len + 1);
memcpy (buf, str, len);
memcpy (buf+len, IDENTIFIER_POINTER (id), IDENTIFIER_LENGTH (id));
buf[IDENTIFIER_LENGTH (id) + len] = 0;
return get_identifier (buf);
}
/* Parse a CW asm identifier. Returns an IDENTIFIER_NODE representing
the identifier. The CW asm identifieriers include [.+-] as part of
the identifier. */
static tree
cp_parser_iasm_identifier (cp_parser* parser)
{
cp_token *token;
tree t;
const char *str = "";
/* We have to accept certain keywords. */
token = cp_lexer_peek_token (parser->lexer);
if (token->flags & NAMED_OP)
{
const char *s = 0;
switch (token->type) {
case CPP_AND_AND: s="and"; break;
case CPP_AND_EQ: s="and_eq"; break;
case CPP_AND: s="bitand"; break;
case CPP_OR: s="bitor"; break;
case CPP_COMPL: s="compl"; break;
case CPP_NOT: s="not"; break;
case CPP_NOT_EQ: s="not_eq"; break;
case CPP_OR_OR: s="or"; break;
case CPP_OR_EQ: s="or_eq"; break;
case CPP_XOR: s="xor"; break;
case CPP_XOR_EQ: s="xor_eq"; break;
default: break;
}
/* The above list is the entire list of named operators. We
can't fail to translate the name. See operator_array in
libcpp/init.c. */
gcc_assert (s != 0);
cp_lexer_consume_token (parser->lexer);
t = get_identifier (s);
}
else if (token->type == CPP_DOT)
{
/* .align */
cp_lexer_consume_token (parser->lexer);
t = iasm_build_identifier_string (parser, ".");
}
else if (token->u.value
&& IASM_SEE_OPCODE (TYPESPEC, token->u.value) == IDENTIFIER)
{
cp_lexer_consume_token (parser->lexer);
t = token->u.value;
}
else
t = cp_parser_identifier (parser);
if (t == error_mark_node)
return t;
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_DOT:
str = ".";
break;
case CPP_PLUS:
str = "+";
break;
case CPP_MINUS:
str = "-";
break;
case CPP_PLUS_PLUS:
str = "++";
break;
case CPP_MINUS_MINUS:
str = "--";
break;
default:
return t;
}
/* If there was whitespace between the identifier and the [.+-]
character, then that character can't be part of the
identifier. */
if (token->flags & PREV_WHITE)
return t;
cp_lexer_consume_token (parser->lexer);
return iasm_get_identifier (t, str);
}
static tree
cp_parser_iasm_identifier_or_number (cp_parser* parser)
{
cp_token *token;
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_NUMBER
&& TREE_CODE (token->u.value) == INTEGER_CST)
{
char buf[60];
sprintf (buf, HOST_WIDE_INT_PRINT_UNSIGNED, tree_low_cst (token->u.value, 0));
cp_lexer_consume_token (parser->lexer);
return get_identifier (buf);
}
return cp_parser_identifier (parser);
}
static tree
cp_parser_iasm_maybe_prefix (cp_parser *parser, tree id)
{
tree prefix_list = NULL_TREE;
while (iasm_is_prefix (id))
{
if (cp_lexer_iasm_bol (parser->lexer))
break;
prefix_list = tree_cons (NULL_TREE, id, prefix_list);
id = cp_parser_iasm_identifier (parser);
}
if (prefix_list)
id = tree_cons (NULL_TREE, id, prefix_list);
return id;
}
/* A single statement consists of one or more labels (identified by a
leading '@' and/or a trailing ':'), optionally followed by opcode
and operands. */
static void
cp_parser_iasm_statement (cp_parser* parser)
{
tree aname, anothername, operands;
/* Keep sucking labels from the front of the statement until a
non-label is seen. */
while (true)
{
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)
|| cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE)
|| cp_lexer_next_token_is (parser->lexer, CPP_EOF))
break;
if (cp_lexer_next_token_is (parser->lexer, CPP_PRAGMA))
{
cp_parser_pragma (parser, pragma_compound);
}
else if (cp_lexer_next_token_is (parser->lexer, CPP_ATSIGN))
{
cp_lexer_consume_token (parser->lexer);
aname = cp_parser_iasm_identifier_or_number (parser);
/* Optional ':' after a label. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COLON))
cp_lexer_consume_token (parser->lexer);
iasm_label (aname, true);
}
else
{
aname = cp_parser_iasm_identifier (parser);
if (cp_lexer_next_token_is (parser->lexer, CPP_COLON))
{
cp_lexer_consume_token (parser->lexer);
iasm_label (aname, false);
}
else
{
enum rid scspec = RID_EXTERN;
if (strcmp (IDENTIFIER_POINTER (aname), "entry") == 0)
{
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_STATIC)
|| cp_lexer_next_token_is_keyword (parser->lexer, RID_EXTERN))
scspec = cp_lexer_consume_token (parser->lexer)->keyword;
anothername = cp_parser_iasm_operand (parser);
iasm_entry (scspec, anothername);
}
else
{
aname = cp_parser_iasm_maybe_prefix (parser, aname);
iasm_in_operands = true;
operands = cp_parser_iasm_operands (parser);
iasm_stmt (aname, operands, input_line);
}
if (cp_lexer_iasm_bol (parser->lexer))
return;
break;
}
}
if (cp_lexer_iasm_bol (parser->lexer))
return;
}
cp_parser_iasm_maybe_skip_comments (parser);
}
/* Eat tokens until we get back to something we recognize. */
static void
cp_parser_iasm_skip_to_next_asm (cp_parser *parser)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
do
{
if (cp_lexer_iasm_bol (parser->lexer)
|| token->type == CPP_SEMICOLON
|| token->type == CPP_CLOSE_BRACE
|| token->type == CPP_EOF
|| token->keyword == RID_ASM)
return;
cp_lexer_consume_token (parser->lexer);
}
while (1);
}
static tree
cp_parser_iasm_operands (cp_parser *parser)
{
tree operands = NULL_TREE, operand;
while (true)
{
/* If we're looking at the end of the line, then we've run out of operands. */
if (cp_lexer_iasm_bol (parser->lexer)
|| cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON)
|| cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE)
|| cp_lexer_next_token_is (parser->lexer, CPP_EOF)
|| cp_lexer_next_token_is_keyword (parser->lexer, RID_ASM))
break;
operand = cp_parser_iasm_operand (parser);
if (operand && operand != error_mark_node)
{
operands = chainon (operands, build_tree_list (NULL_TREE, operand));
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
cp_lexer_consume_token (parser->lexer);
}
else
{
cp_parser_iasm_skip_to_next_asm (parser);
return NULL_TREE;
}
}
return operands;
}
static tree
cp_parser_iasm_operand (cp_parser *parser)
{
tree operand;
/* Jump into the usual operand precedence stack. */
operand = cp_parser_binary_expression (parser, false);
/* Maybe this should go up higher. */
if (BASELINK_P (operand)
&& TREE_CODE (BASELINK_FUNCTIONS (operand)) == FUNCTION_DECL)
{
operand = BASELINK_FUNCTIONS (operand);
}
return operand;
}
/* Need to handle case of relative branch using: .[+|-]number
syntax */
static tree
cp_parser_iasm_relative_branch (cp_parser *parser)
{
cp_token *token;
token = cp_lexer_peek_nth_token (parser->lexer, 2);
if (token->type == CPP_PLUS || token->type == CPP_MINUS)
{
const char *str = (token->type == CPP_PLUS) ? ".+" : ".-";
/* consume '.' */
cp_lexer_consume_token (parser->lexer);
/* consume '-' or '+' */
cp_lexer_consume_token (parser->lexer);
return iasm_build_identifier_string (parser, str);
}
return error_mark_node;
}
/* Parse a CW asm-style postfix-expression.
postfix-expression:
primary-expression
postfix-expression [ expression ]
postfix-expression ( expression-list [opt] )
simple-type-specifier ( expression-list [opt] )
postfix-expression . template [opt] id-expression
postfix-expression -> template [opt] id-expression
postfix-expression . pseudo-destructor-name
postfix-expression -> pseudo-destructor-name
typeid ( expression )
typeid ( type-id )
GNU Extension:
postfix-expression:
( type-id ) { initializer-list , [opt] }
This extension is a GNU version of the C99 compound-literal
construct. (The C99 grammar uses `type-name' instead of `type-id',
but they are essentially the same concept.)
If ADDRESS_P is true, the postfix expression is the operand of the
`&' operator. CAST_P is true if this expression is the target of a
cast.
Returns a representation of the expression. */
static tree
cp_parser_iasm_postfix_expression (cp_parser *parser, bool address_p, bool cast_p)
{
bool for_offsetof = false;
cp_token *token;
enum rid keyword;
cp_id_kind idk = CP_ID_KIND_NONE;
tree postfix_expression = NULL_TREE;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
/* Some of the productions are determined by keywords. */
keyword = token->keyword;
switch (keyword)
{
case RID_SIZEOF:
{
tree operand;
/* Consume the token. */
cp_lexer_consume_token (parser->lexer);
/* Parse the operand. */
operand = cp_parser_sizeof_operand (parser, keyword);
postfix_expression = cxx_sizeof_or_alignof_type (operand, SIZEOF_EXPR, true);
break;
}
default:
{
tree type;
/* If the next thing is a simple-type-specifier, we may be
looking at a functional cast. We could also be looking at
an id-expression. So, we try the functional cast, and if
that doesn't work we fall back to the primary-expression. */
cp_parser_parse_tentatively (parser);
/* Look for the simple-type-specifier. */
type = cp_parser_simple_type_specifier (parser,
CP_PARSER_FLAGS_NONE,
/*identifier_p=*/false);
/* Parse the cast itself. */
if (!cp_parser_error_occurred (parser))
postfix_expression
= cp_parser_functional_cast (parser, type);
/* If that worked, we're done. */
if (cp_parser_parse_definitely (parser))
break;
if (token->type == CPP_DOT || token->type == CPP_MULT)
{
postfix_expression = cp_parser_iasm_relative_branch (parser);
if (postfix_expression != error_mark_node)
break;
}
/* If the functional-cast didn't work out, try a
compound-literal. */
if (cp_parser_allow_gnu_extensions_p (parser)
&& cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
VEC(constructor_elt,gc) *initializer_list = NULL;
bool saved_in_type_id_in_expr_p;
cp_parser_parse_tentatively (parser);
/* Consume the `('. */
cp_lexer_consume_token (parser->lexer);
/* Parse the type. */
saved_in_type_id_in_expr_p = parser->in_type_id_in_expr_p;
parser->in_type_id_in_expr_p = true;
type = cp_parser_type_id (parser);
parser->in_type_id_in_expr_p = saved_in_type_id_in_expr_p;
/* Look for the `)'. */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* Look for the `{'. */
cp_parser_require (parser, CPP_OPEN_BRACE, "`{'");
/* If things aren't going well, there's no need to
keep going. */
if (!cp_parser_error_occurred (parser))
{
bool non_constant_p;
/* Parse the initializer-list. */
initializer_list
= cp_parser_initializer_list (parser, &non_constant_p);
/* Allow a trailing `,'. */
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
cp_lexer_consume_token (parser->lexer);
/* Look for the final `}'. */
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
}
/* If that worked, we're definitely looking at a
compound-literal expression. */
if (cp_parser_parse_definitely (parser))
{
/* Warn the user that a compound literal is not
allowed in standard C++. */
if (pedantic)
pedwarn ("ISO C++ forbids compound-literals");
/* Form the representation of the compound-literal. */
postfix_expression
= finish_compound_literal (type, initializer_list);
break;
}
}
/* It must be a primary-expression. */
postfix_expression = cp_parser_primary_expression (parser, address_p, cast_p,
/*template_arg_p=*/false,
&idk);
}
break;
}
/* Keep looping until the postfix-expression is complete. */
while (true)
{
if (idk == CP_ID_KIND_UNQUALIFIED
&& TREE_CODE (postfix_expression) == IDENTIFIER_NODE
&& cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_PAREN))
/* It is not a Koenig lookup function call. */
postfix_expression
= unqualified_name_lookup_error (postfix_expression);
if (cp_lexer_iasm_bol (parser->lexer))
return postfix_expression;
/* Peek at the next token. */
token = cp_lexer_peek_token (parser->lexer);
switch (token->type)
{
case CPP_OPEN_SQUARE:
postfix_expression
= cp_parser_postfix_open_square_expression (parser,
postfix_expression,
false);
idk = CP_ID_KIND_NONE;
break;
case CPP_OPEN_PAREN:
/* postfix-expression ( expression ) */
{
tree expr;
cp_lexer_consume_token (parser->lexer);
expr = cp_parser_binary_expression (parser, false);
if (expr == error_mark_node)
{
postfix_expression = error_mark_node;
break;
}
postfix_expression =
iasm_build_register_offset (postfix_expression, expr);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* The POSTFIX_EXPRESSION is certainly no longer an id. */
idk = CP_ID_KIND_NONE;
}
break;
case CPP_DOT:
case CPP_DEREF:
/* postfix-expression . template [opt] id-expression
postfix-expression . pseudo-destructor-name
postfix-expression -> template [opt] id-expression
postfix-expression -> pseudo-destructor-name */
{
tree name;
bool dependent_p;
bool template_p;
tree scope = NULL_TREE;
enum cpp_ttype token_type = token->type;
/* We allow [eax].16 to refer to [eax + 16]. */
if (TREE_CODE (postfix_expression) == BRACKET_EXPR)
{
cp_token *new_token;
new_token = cp_lexer_peek_nth_token (parser->lexer, 2);
if (new_token->type == CPP_NUMBER)
{
/* Consume the `.' or `->' operator. */
cp_lexer_consume_token (parser->lexer);
postfix_expression = iasm_build_bracket (postfix_expression,
new_token->u.value);
cp_lexer_consume_token (parser->lexer);
break;
}
}
/* If this is a `->' operator, dereference the pointer. */
if (token->type == CPP_DEREF)
postfix_expression = build_x_arrow (postfix_expression);
/* Check to see whether or not the expression is
type-dependent. */
dependent_p = type_dependent_expression_p (postfix_expression);
/* The identifier following the `->' or `.' is not
qualified. */
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
idk = CP_ID_KIND_NONE;
/* Enter the scope corresponding to the type of the object
given by the POSTFIX_EXPRESSION. */
if (!dependent_p
&& TREE_TYPE (postfix_expression) != NULL_TREE)
{
scope = TREE_TYPE (postfix_expression);
/* According to the standard, no expression should
ever have reference type. Unfortunately, we do not
currently match the standard in this respect in
that our internal representation of an expression
may have reference type even when the standard says
it does not. Therefore, we have to manually obtain
the underlying type here. */
scope = non_reference (scope);
/* The type of the POSTFIX_EXPRESSION must be
complete. */
scope = complete_type_or_else (scope, NULL_TREE);
/* Let the name lookup machinery know that we are
processing a class member access expression. */
parser->context->object_type = scope;
/* If something went wrong, we want to be able to
discern that case, as opposed to the case where
there was no SCOPE due to the type of expression
being dependent. */
if (!scope)
scope = error_mark_node;
/* If the SCOPE was erroneous, make the various
semantic analysis functions exit quickly -- and
without issuing additional error messages. */
if (scope == error_mark_node)
postfix_expression = error_mark_node;
}
/* Consume the `.' or `->' operator. */
cp_lexer_consume_token (parser->lexer);
/* If the SCOPE is not a scalar type, we are looking at an
ordinary class member access expression, rather than a
pseudo-destructor-name. */
if (!scope || !SCALAR_TYPE_P (scope))
{
template_p = cp_parser_optional_template_keyword (parser);
/* Parse the id-expression. */
name = cp_parser_id_expression (parser,
template_p,
/*check_dependency_p=*/true,
/*template_p=*/NULL,
/*declarator_p=*/false,
/*optional_p=*/false);
/* In general, build a SCOPE_REF if the member name is
qualified. However, if the name was not dependent
and has already been resolved; there is no need to
build the SCOPE_REF. For example;
struct X { void f(); };
template <typename T> void f(T* t) { t->X::f(); }
Even though "t" is dependent, "X::f" is not and has
been resolved to a BASELINK; there is no need to
include scope information. */
/* But we do need to remember that there was an explicit
scope for virtual function calls. */
if (parser->scope)
idk = CP_ID_KIND_QUALIFIED;
if (name != error_mark_node
&& !BASELINK_P (name)
&& parser->scope)
{
name = build_nt (SCOPE_REF, parser->scope, name);
parser->scope = NULL_TREE;
parser->qualifying_scope = NULL_TREE;
parser->object_scope = NULL_TREE;
}
if (scope && name && BASELINK_P (name))
adjust_result_of_qualified_name_lookup
(name, BINFO_TYPE (BASELINK_BINFO (name)), scope);
postfix_expression
= iasm_cp_build_component_ref (postfix_expression, name);
}
/* Otherwise, try the pseudo-destructor-name production. */
else
{
tree s = NULL_TREE;
tree type;
/* Parse the pseudo-destructor-name. */
cp_parser_pseudo_destructor_name (parser, &s, &type);
/* Form the call. */
postfix_expression
= finish_pseudo_destructor_expr (postfix_expression,
s, TREE_TYPE (type));
}
/* We no longer need to look up names in the scope of the
object on the left-hand side of the `.' or `->'
operator. */
parser->context->object_type = NULL_TREE;
/* Outside of offsetof, these operators may not appear in
constant-expressions. */
if (!for_offsetof
&& (cp_parser_non_integral_constant_expression
(parser, token_type == CPP_DEREF ? "'->'" : "`.'")))
postfix_expression = error_mark_node;
}
break;
case CPP_NAME:
if (strcasecmp (IDENTIFIER_POINTER (token->u.value), "ptr") == 0)
{
/* Handle things like: inc dword ptr [eax] */
tree type = postfix_expression;
cp_lexer_consume_token (parser->lexer);
postfix_expression = cp_parser_iasm_postfix_expression (parser, address_p, cast_p);
postfix_expression = iasm_ptr_conv (type, postfix_expression);
}
default:
return postfix_expression;
}
}
/* We should never get here. */
abort ();
return error_mark_node;
}
int
iasm_typename_or_reserved (tree value)
{
tree type_decl;
if (IASM_SEE_OPCODE (TYPESPEC, value) == IDENTIFIER)
return 0;
if (C_IS_RESERVED_WORD (value))
return 1;
type_decl = lookup_name_real (value, 0, 0, true, 0, 0);
return type_decl
&& (TREE_CODE (type_decl) == TYPE_DECL
|| TREE_CODE (type_decl) == NAMESPACE_DECL
|| TREE_CODE (type_decl) == TEMPLATE_DECL);
}
/* APPLE LOCAL end CW asm blocks */
/* Parse an Objective-C expression, which feeds into a primary-expression
above.
objc-expression:
objc-message-expression
objc-string-literal
objc-encode-expression
objc-protocol-expression
objc-selector-expression
Returns a tree representation of the expression. */
static tree
cp_parser_objc_expression (cp_parser* parser)
{
/* Try to figure out what kind of declaration is present. */
cp_token *kwd = cp_lexer_peek_token (parser->lexer);
switch (kwd->type)
{
case CPP_OPEN_SQUARE:
return cp_parser_objc_message_expression (parser);
case CPP_OBJC_STRING:
kwd = cp_lexer_consume_token (parser->lexer);
return objc_build_string_object (kwd->u.value);
case CPP_KEYWORD:
switch (kwd->keyword)
{
case RID_AT_ENCODE:
return cp_parser_objc_encode_expression (parser);
case RID_AT_PROTOCOL:
return cp_parser_objc_protocol_expression (parser);
case RID_AT_SELECTOR:
return cp_parser_objc_selector_expression (parser);
default:
break;
}
default:
error ("misplaced %<@%D%> Objective-C++ construct", kwd->u.value);
cp_parser_skip_to_end_of_block_or_statement (parser);
}
return error_mark_node;
}
/* Parse an Objective-C message expression.
objc-message-expression:
[ objc-message-receiver objc-message-args ]
Returns a representation of an Objective-C message. */
static tree
cp_parser_objc_message_expression (cp_parser* parser)
{
tree receiver, messageargs;
cp_lexer_consume_token (parser->lexer); /* Eat '['. */
receiver = cp_parser_objc_message_receiver (parser);
messageargs = cp_parser_objc_message_args (parser);
cp_parser_require (parser, CPP_CLOSE_SQUARE, "`]'");
return objc_build_message_expr (build_tree_list (receiver, messageargs));
}
/* APPLE LOCAL begin radar 5277239 */
/* Parse an Objective-C dot-syntax class expression.
objc-message-expression:
class-name '.' class-method-name
Returns an objc_property_reference expression. */
static tree
cp_parser_objc_reference_expression (cp_parser* parser, tree type_decl)
{
tree receiver, component;
receiver = objc_get_class_reference (TREE_TYPE (type_decl));
cp_lexer_consume_token (parser->lexer); /* Eact '.' */
component = cp_parser_objc_message_args (parser);
return objc_build_property_reference_expr (receiver, TREE_PURPOSE (component));
}
/* APPLE LOCAL end radar 5277239 */
/* Parse an objc-message-receiver.
objc-message-receiver:
expression
simple-type-specifier
Returns a representation of the type or expression. */
static tree
cp_parser_objc_message_receiver (cp_parser* parser)
{
tree rcv;
/* An Objective-C message receiver may be either (1) a type
or (2) an expression. */
cp_parser_parse_tentatively (parser);
rcv = cp_parser_expression (parser, false);
if (cp_parser_parse_definitely (parser))
return rcv;
rcv = cp_parser_simple_type_specifier (parser,
/*decl_specs=*/NULL,
CP_PARSER_FLAGS_NONE);
return objc_get_class_reference (rcv);
}
/* Parse the arguments and selectors comprising an Objective-C message.
objc-message-args:
objc-selector
objc-selector-args
objc-selector-args , objc-comma-args
objc-selector-args:
objc-selector [opt] : assignment-expression
objc-selector-args objc-selector [opt] : assignment-expression
objc-comma-args:
assignment-expression
objc-comma-args , assignment-expression
Returns a TREE_LIST, with TREE_PURPOSE containing a list of
selector arguments and TREE_VALUE containing a list of comma
arguments. */
static tree
cp_parser_objc_message_args (cp_parser* parser)
{
tree sel_args = NULL_TREE, addl_args = NULL_TREE;
bool maybe_unary_selector_p = true;
cp_token *token = cp_lexer_peek_token (parser->lexer);
while (cp_parser_objc_selector_p (token->type) || token->type == CPP_COLON)
{
tree selector = NULL_TREE, arg;
if (token->type != CPP_COLON)
selector = cp_parser_objc_selector (parser);
/* Detect if we have a unary selector. */
if (maybe_unary_selector_p
&& cp_lexer_next_token_is_not (parser->lexer, CPP_COLON))
return build_tree_list (selector, NULL_TREE);
maybe_unary_selector_p = false;
cp_parser_require (parser, CPP_COLON, "`:'");
arg = cp_parser_assignment_expression (parser, false);
sel_args
= chainon (sel_args,
build_tree_list (selector, arg));
token = cp_lexer_peek_token (parser->lexer);
}
/* Handle non-selector arguments, if any. */
while (token->type == CPP_COMMA)
{
tree arg;
cp_lexer_consume_token (parser->lexer);
arg = cp_parser_assignment_expression (parser, false);
addl_args
= chainon (addl_args,
build_tree_list (NULL_TREE, arg));
token = cp_lexer_peek_token (parser->lexer);
}
/* APPLE LOCAL begin radar 4294425 */
if (sel_args == NULL_TREE && addl_args == NULL_TREE)
{
cp_parser_error (parser, "objective-c++ message argument(s) are expected");
return build_tree_list (error_mark_node, error_mark_node);
}
/* APPLE LOCAL end radar 4294425 */
return build_tree_list (sel_args, addl_args);
}
/* Parse an Objective-C encode expression.
objc-encode-expression:
@encode objc-typename
Returns an encoded representation of the type argument. */
static tree
cp_parser_objc_encode_expression (cp_parser* parser)
{
tree type;
cp_lexer_consume_token (parser->lexer); /* Eat '@encode'. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
type = complete_type (cp_parser_type_id (parser));
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
if (!type)
{
error ("%<@encode%> must specify a type as an argument");
return error_mark_node;
}
/* APPLE LOCAL begin radar 4278774 */
if (dependent_type_p (type))
{
tree value = build_min (AT_ENCODE_EXPR, size_type_node, type);
TREE_READONLY (value) = 1;
return value;
}
/* APPLE LOCAL end radar 4278774 */
return objc_build_encode_expr (type);
}
/* Parse an Objective-C @defs expression. */
static tree
cp_parser_objc_defs_expression (cp_parser *parser)
{
tree name;
cp_lexer_consume_token (parser->lexer); /* Eat '@defs'. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
name = cp_parser_identifier (parser);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
return objc_get_class_ivars (name);
}
/* Parse an Objective-C protocol expression.
objc-protocol-expression:
@protocol ( identifier )
Returns a representation of the protocol expression. */
static tree
cp_parser_objc_protocol_expression (cp_parser* parser)
{
tree proto;
cp_lexer_consume_token (parser->lexer); /* Eat '@protocol'. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
proto = cp_parser_identifier (parser);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
return objc_build_protocol_expr (proto);
}
/* Parse an Objective-C selector expression.
objc-selector-expression:
@selector ( objc-method-signature )
objc-method-signature:
objc-selector
objc-selector-seq
objc-selector-seq:
objc-selector :
objc-selector-seq objc-selector :
Returns a representation of the method selector. */
static tree
cp_parser_objc_selector_expression (cp_parser* parser)
{
tree sel_seq = NULL_TREE;
bool maybe_unary_selector_p = true;
cp_token *token;
cp_lexer_consume_token (parser->lexer); /* Eat '@selector'. */
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
token = cp_lexer_peek_token (parser->lexer);
while (cp_parser_objc_selector_p (token->type) || token->type == CPP_COLON
|| token->type == CPP_SCOPE)
{
tree selector = NULL_TREE;
if (token->type != CPP_COLON
|| token->type == CPP_SCOPE)
selector = cp_parser_objc_selector (parser);
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COLON)
&& cp_lexer_next_token_is_not (parser->lexer, CPP_SCOPE))
{
/* Detect if we have a unary selector. */
if (maybe_unary_selector_p)
{
sel_seq = selector;
goto finish_selector;
}
else
{
cp_parser_error (parser, "expected %<:%>");
}
}
maybe_unary_selector_p = false;
token = cp_lexer_consume_token (parser->lexer);
if (token->type == CPP_SCOPE)
{
sel_seq
= chainon (sel_seq,
build_tree_list (selector, NULL_TREE));
sel_seq
= chainon (sel_seq,
build_tree_list (NULL_TREE, NULL_TREE));
}
else
sel_seq
= chainon (sel_seq,
build_tree_list (selector, NULL_TREE));
token = cp_lexer_peek_token (parser->lexer);
}
finish_selector:
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
return objc_build_selector_expr (sel_seq);
}
/* Parse a list of identifiers.
objc-identifier-list:
identifier
objc-identifier-list , identifier
Returns a TREE_LIST of identifier nodes. */
static tree
cp_parser_objc_identifier_list (cp_parser* parser)
{
tree list = build_tree_list (NULL_TREE, cp_parser_identifier (parser));
cp_token *sep = cp_lexer_peek_token (parser->lexer);
while (sep->type == CPP_COMMA)
{
cp_lexer_consume_token (parser->lexer); /* Eat ','. */
list = chainon (list,
build_tree_list (NULL_TREE,
cp_parser_identifier (parser)));
sep = cp_lexer_peek_token (parser->lexer);
}
return list;
}
/* Parse an Objective-C alias declaration.
objc-alias-declaration:
@compatibility_alias identifier identifier ;
This function registers the alias mapping with the Objective-C front-end.
It returns nothing. */
static void
cp_parser_objc_alias_declaration (cp_parser* parser)
{
tree alias, orig;
cp_lexer_consume_token (parser->lexer); /* Eat '@compatibility_alias'. */
alias = cp_parser_identifier (parser);
orig = cp_parser_identifier (parser);
objc_declare_alias (alias, orig);
cp_parser_consume_semicolon_at_end_of_statement (parser);
}
/* Parse an Objective-C class forward-declaration.
objc-class-declaration:
@class objc-identifier-list ;
The function registers the forward declarations with the Objective-C
front-end. It returns nothing. */
static void
cp_parser_objc_class_declaration (cp_parser* parser)
{
cp_lexer_consume_token (parser->lexer); /* Eat '@class'. */
objc_declare_class (cp_parser_objc_identifier_list (parser));
cp_parser_consume_semicolon_at_end_of_statement (parser);
}
/* Parse a list of Objective-C protocol references.
objc-protocol-refs-opt:
objc-protocol-refs [opt]
objc-protocol-refs:
< objc-identifier-list >
Returns a TREE_LIST of identifiers, if any. */
static tree
cp_parser_objc_protocol_refs_opt (cp_parser* parser)
{
tree protorefs = NULL_TREE;
if(cp_lexer_next_token_is (parser->lexer, CPP_LESS))
{
cp_lexer_consume_token (parser->lexer); /* Eat '<'. */
protorefs = cp_parser_objc_identifier_list (parser);
cp_parser_require (parser, CPP_GREATER, "`>'");
}
return protorefs;
}
/* APPLE LOCAL begin radar 5355344 */
/* This routine also parses a list of Objective-C protocol references; except that
if list is not valid, it returns FALSE and back-tracks parsing. */
static bool
cp_parser_objc_tentative_protocol_refs_opt (cp_parser* parser, tree *protorefs)
{
*protorefs = NULL_TREE;
if(cp_lexer_next_token_is (parser->lexer, CPP_LESS))
{
cp_parser_parse_tentatively (parser);
cp_lexer_consume_token (parser->lexer); /* Eat '<'. */
*protorefs = cp_parser_objc_identifier_list (parser);
if (!cp_objc_protocol_id_list (*protorefs))
{
cp_parser_abort_tentative_parse (parser);
return false;
}
if (cp_parser_parse_definitely (parser))
cp_parser_require (parser, CPP_GREATER, "`>'");
}
return true;
}
/* APPLE LOCAL end radar 5355344 */
/* Parse a Objective-C visibility specification. */
static void
cp_parser_objc_visibility_spec (cp_parser* parser)
{
cp_token *vis = cp_lexer_peek_token (parser->lexer);
switch (vis->keyword)
{
case RID_AT_PRIVATE:
objc_set_visibility (2);
break;
case RID_AT_PROTECTED:
objc_set_visibility (0);
break;
case RID_AT_PUBLIC:
objc_set_visibility (1);
break;
/* APPLE LOCAL begin radar 4564694 */
case RID_AT_PACKAGE:
objc_set_visibility (3);
break;
/* APPLE LOCAL end radar 4564694 */
default:
return;
}
/* Eat '@private'/'@protected'/'@public'. */
cp_lexer_consume_token (parser->lexer);
}
/* Parse an Objective-C method type. */
static void
cp_parser_objc_method_type (cp_parser* parser)
{
objc_set_method_type
(cp_lexer_consume_token (parser->lexer)->type == CPP_PLUS
? PLUS_EXPR
: MINUS_EXPR);
}
/* Parse an Objective-C protocol qualifier. */
static tree
cp_parser_objc_protocol_qualifiers (cp_parser* parser)
{
tree quals = NULL_TREE, node;
cp_token *token = cp_lexer_peek_token (parser->lexer);
node = token->u.value;
while (node && TREE_CODE (node) == IDENTIFIER_NODE
&& (node == ridpointers [(int) RID_IN]
|| node == ridpointers [(int) RID_OUT]
|| node == ridpointers [(int) RID_INOUT]
|| node == ridpointers [(int) RID_BYCOPY]
|| node == ridpointers [(int) RID_BYREF]
|| node == ridpointers [(int) RID_ONEWAY]))
{
quals = tree_cons (NULL_TREE, node, quals);
cp_lexer_consume_token (parser->lexer);
token = cp_lexer_peek_token (parser->lexer);
node = token->u.value;
}
return quals;
}
/* Parse an Objective-C typename. */
static tree
cp_parser_objc_typename (cp_parser* parser)
{
tree typename = NULL_TREE;
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
tree proto_quals, cp_type = NULL_TREE;
cp_lexer_consume_token (parser->lexer); /* Eat '('. */
proto_quals = cp_parser_objc_protocol_qualifiers (parser);
/* An ObjC type name may consist of just protocol qualifiers, in which
case the type shall default to 'id'. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_PAREN))
cp_type = cp_parser_type_id (parser);
/* APPLE LOCAL begin radar 6261630 */
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_ATTRIBUTE))
{
/* Chain on the trailing attribute. */
tree attrs = chainon (NULL_TREE,
cp_parser_attributes_opt (parser));
cplus_decl_attributes (&cp_type, attrs, 0);
}
/* APPLE LOCAL end radar 6261630 */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
typename = build_tree_list (proto_quals, cp_type);
}
return typename;
}
/* Check to see if TYPE refers to an Objective-C selector name. */
static bool
cp_parser_objc_selector_p (enum cpp_ttype type)
{
return (type == CPP_NAME || type == CPP_KEYWORD
|| type == CPP_AND_AND || type == CPP_AND_EQ || type == CPP_AND
|| type == CPP_OR || type == CPP_COMPL || type == CPP_NOT
|| type == CPP_NOT_EQ || type == CPP_OR_OR || type == CPP_OR_EQ
|| type == CPP_XOR || type == CPP_XOR_EQ);
}
/* Parse an Objective-C selector. */
static tree
cp_parser_objc_selector (cp_parser* parser)
{
cp_token *token = cp_lexer_consume_token (parser->lexer);
if (!cp_parser_objc_selector_p (token->type))
{
error ("invalid Objective-C++ selector name");
return error_mark_node;
}
/* C++ operator names are allowed to appear in ObjC selectors. */
switch (token->type)
{
case CPP_AND_AND: return get_identifier ("and");
case CPP_AND_EQ: return get_identifier ("and_eq");
case CPP_AND: return get_identifier ("bitand");
case CPP_OR: return get_identifier ("bitor");
case CPP_COMPL: return get_identifier ("compl");
case CPP_NOT: return get_identifier ("not");
case CPP_NOT_EQ: return get_identifier ("not_eq");
case CPP_OR_OR: return get_identifier ("or");
case CPP_OR_EQ: return get_identifier ("or_eq");
case CPP_XOR: return get_identifier ("xor");
case CPP_XOR_EQ: return get_identifier ("xor_eq");
default: return token->u.value;
}
}
/* APPLE LOCAL begin radar 3803157 - objc attribute */
static void
cp_parser_objc_maybe_attributes (cp_parser* parser, tree* attributes)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
if (*attributes != NULL_TREE)
{
error ("method attributes must be specified at the end only");
*attributes = NULL_TREE;
}
if (token->keyword == RID_ATTRIBUTE)
*attributes = cp_parser_attributes_opt (parser);
}
/* Parse an Objective-C params list. */
static tree
cp_parser_objc_method_keyword_params (cp_parser* parser, tree* attributes)
/* APPLE LOCAL end radar 3803157 - objc attribute */
{
tree params = NULL_TREE;
bool maybe_unary_selector_p = true;
cp_token *token = cp_lexer_peek_token (parser->lexer);
while (cp_parser_objc_selector_p (token->type) || token->type == CPP_COLON)
{
tree selector = NULL_TREE, typename, identifier;
/* APPLE LOCAL radar 4157812 */
tree attr = NULL_TREE;
if (token->type != CPP_COLON)
selector = cp_parser_objc_selector (parser);
/* Detect if we have a unary selector. */
if (maybe_unary_selector_p
&& cp_lexer_next_token_is_not (parser->lexer, CPP_COLON))
/* APPLE LOCAL begin radar 3803157 - objc attribute */
{
cp_parser_objc_maybe_attributes (parser, attributes);
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COLON))
return selector;
}
/* APPLE LOCAL end radar 3803157 - objc attribute */
maybe_unary_selector_p = false;
cp_parser_require (parser, CPP_COLON, "`:'");
typename = cp_parser_objc_typename (parser);
/* APPLE LOCAL radar 4157812 */
cp_parser_objc_maybe_attributes (parser, &attr);
identifier = cp_parser_identifier (parser);
/* APPLE LOCAL radar 3803157 - objc attribute */
cp_parser_objc_maybe_attributes (parser, attributes);
params
= chainon (params,
objc_build_keyword_decl (selector,
typename,
/* APPLE LOCAL radar 4157812 */
identifier, attr));
token = cp_lexer_peek_token (parser->lexer);
}
/* APPLE LOCAL begin radar 4290840 */
if (params == NULL_TREE)
{
cp_parser_error (parser, "objective-c++ method declaration is expected");
return error_mark_node;
}
/* APPLE LOCAL end radar 4290840 */
return params;
}
/* Parse the non-keyword Objective-C params. */
static tree
/* APPLE LOCAL radar 3803157 - objc attribute */
cp_parser_objc_method_tail_params_opt (cp_parser* parser, bool *ellipsisp, tree* attributes)
{
tree params = make_node (TREE_LIST);
cp_token *token = cp_lexer_peek_token (parser->lexer);
*ellipsisp = false; /* Initially, assume no ellipsis. */
while (token->type == CPP_COMMA)
{
cp_parameter_declarator *parmdecl;
tree parm;
cp_lexer_consume_token (parser->lexer); /* Eat ','. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_ELLIPSIS)
{
cp_lexer_consume_token (parser->lexer); /* Eat '...'. */
*ellipsisp = true;
/* APPLE LOCAL radar 3803157 - objc attribute */
cp_parser_objc_maybe_attributes (parser, attributes);
break;
}
parmdecl = cp_parser_parameter_declaration (parser, false, NULL);
parm = grokdeclarator (parmdecl->declarator,
&parmdecl->decl_specifiers,
PARM, /*initialized=*/0,
/*attrlist=*/NULL);
chainon (params, build_tree_list (NULL_TREE, parm));
token = cp_lexer_peek_token (parser->lexer);
}
return params;
}
/* Parse a linkage specification, a pragma, an extra semicolon or a block. */
static void
cp_parser_objc_interstitial_code (cp_parser* parser)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
/* If the next token is `extern' and the following token is a string
literal, then we have a linkage specification. */
if (token->keyword == RID_EXTERN
&& cp_parser_is_string_literal (cp_lexer_peek_nth_token (parser->lexer, 2)))
cp_parser_linkage_specification (parser);
/* Handle #pragma, if any. */
else if (token->type == CPP_PRAGMA)
cp_parser_pragma (parser, pragma_external);
/* Allow stray semicolons. */
else if (token->type == CPP_SEMICOLON)
cp_lexer_consume_token (parser->lexer);
/* APPLE LOCAL begin C* language */
else if (token->keyword == RID_AT_OPTIONAL)
{
cp_lexer_consume_token (parser->lexer);
objc_set_method_opt (1);
}
else if (token->keyword == RID_AT_REQUIRED)
{
cp_lexer_consume_token (parser->lexer);
objc_set_method_opt (0);
}
/* APPLE LOCAL end C* language */
/* APPLE LOCAL begin radar 4508851 */
else if (token->keyword == RID_NAMESPACE)
cp_parser_namespace_definition (parser);
/* APPLE LOCAL end radar 4508851 */
/* APPLE LOCAL begin 4093475 */
/* Other stray characters must generate errors. */
else if (token->type == CPP_OPEN_BRACE || token->type == CPP_CLOSE_BRACE)
{
cp_lexer_consume_token (parser->lexer);
error ("stray %<%s%> between Objective-C++ methods",
token->type == CPP_OPEN_BRACE ? "{" : "}");
}
/* APPLE LOCAL end 4093475 */
/* APPLE LOCAL begin radar 5976344 */
else if (token->keyword == RID_TEMPLATE)
cp_parser_declaration (parser);
/* APPLE LOCAL end radar 5976344 */
/* Finally, try to parse a block-declaration, or a function-definition. */
else
cp_parser_block_declaration (parser, /*statement_p=*/false);
}
/* Parse a method signature. */
static tree
/* APPLE LOCAL radar 3803157 - objc attribute */
cp_parser_objc_method_signature (cp_parser* parser, tree* attributes)
{
tree rettype, kwdparms, optparms;
bool ellipsis = false;
cp_parser_objc_method_type (parser);
rettype = cp_parser_objc_typename (parser);
/* APPLE LOCAL begin radar 3803157 - objc attribute */
*attributes = NULL_TREE;
kwdparms = cp_parser_objc_method_keyword_params (parser, attributes);
optparms = cp_parser_objc_method_tail_params_opt (parser, &ellipsis, attributes);
/* APPLE LOCAL end radar 3803157 - objc attribute */
return objc_build_method_signature (rettype, kwdparms, optparms, ellipsis);
}
/* APPLE LOCAL Pars --> Parse */
/* Parse an Objective-C method prototype list. */
static void
cp_parser_objc_method_prototype_list (cp_parser* parser)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL 4093475 */
while (token->keyword != RID_AT_END && token->type != CPP_EOF)
{
if (token->type == CPP_PLUS || token->type == CPP_MINUS)
{
/* APPLE LOCAL begin radar 3803157 - objc attribute */
tree attributes, sig;
sig = cp_parser_objc_method_signature (parser, &attributes);
objc_add_method_declaration (sig, attributes);
/* APPLE LOCAL end radar 3803157 - objc attribute */
cp_parser_consume_semicolon_at_end_of_statement (parser);
}
/* APPLE LOCAL begin C* interface */
else if (token->keyword == RID_AT_PROPERTY)
objc_cp_parser_at_property (parser);
/* APPLE LOCAL end C* interface */
else
/* Allow for interspersed non-ObjC++ code. */
cp_parser_objc_interstitial_code (parser);
token = cp_lexer_peek_token (parser->lexer);
}
/* APPLE LOCAL 4093475 */
cp_parser_require_keyword (parser, RID_AT_END, "`@end'");
objc_finish_interface ();
}
/* Parse an Objective-C method definition list. */
static void
cp_parser_objc_method_definition_list (cp_parser* parser)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL 4093475 */
while (token->keyword != RID_AT_END && token->type != CPP_EOF)
{
tree meth;
if (token->type == CPP_PLUS || token->type == CPP_MINUS)
{
/* APPLE LOCAL radar 4290840 */
cp_token *ptk;
/* APPLE LOCAL begin radar 3803157 - objc attribute */
tree sig, attribute;
push_deferring_access_checks (dk_deferred);
sig = cp_parser_objc_method_signature (parser, &attribute);
objc_start_method_definition (sig, attribute);
/* APPLE LOCAL end radar 3803157 - objc attribute */
/* For historical reasons, we accept an optional semicolon. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
cp_lexer_consume_token (parser->lexer);
/* APPLE LOCAL begin radar 4290840 */
/* Check for all possibilities of illegal lookahead tokens. */
ptk = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL radar 6271728 */
if (ptk->type == CPP_OPEN_BRACE)
{
perform_deferred_access_checks ();
stop_deferring_access_checks ();
meth = cp_parser_function_definition_after_declarator (parser,
false);
pop_deferring_access_checks ();
objc_finish_method_definition (meth);
}
/* APPLE LOCAL begin radar 6271728 */
else
cp_parser_require (parser, CPP_OPEN_BRACE, "`{'");
/* APPLE LOCAL end radar 6271728 */
/* APPLE LOCAL end radar 4290840 */
}
/* APPLE LOCAL begin C* interface */
else if (token->keyword == RID_AT_PROPERTY)
objc_cp_parser_at_property (parser);
/* APPLE LOCAL end C* interface */
/* APPLE LOCAL begin objc new property */
else if (token->keyword == RID_AT_SYNTHESIZE
|| token->keyword == RID_AT_DYNAMIC)
objc_cp_parser_property_impl (parser, token->keyword);
/* APPLE LOCAL end objc new property */
else
/* Allow for interspersed non-ObjC++ code. */
cp_parser_objc_interstitial_code (parser);
token = cp_lexer_peek_token (parser->lexer);
}
/* APPLE LOCAL 4093475 */
cp_parser_require_keyword (parser, RID_AT_END, "`@end'");
objc_finish_implementation ();
}
/* Parse Objective-C ivars. */
static void
cp_parser_objc_class_ivars (cp_parser* parser)
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
if (token->type != CPP_OPEN_BRACE)
return; /* No ivars specified. */
cp_lexer_consume_token (parser->lexer); /* Eat '{'. */
token = cp_lexer_peek_token (parser->lexer);
/* APPLE LOCAL begin radar 4261146 */
while (token->type != CPP_CLOSE_BRACE
&& token->keyword != RID_AT_END
&& token->type != CPP_EOF)
/* APPLE LOCAL end radar 4261146 */
{
cp_decl_specifier_seq declspecs;
int decl_class_or_enum_p;
tree prefix_attributes;
cp_parser_objc_visibility_spec (parser);
if (cp_lexer_next_token_is (parser->lexer, CPP_CLOSE_BRACE))
break;
cp_parser_decl_specifier_seq (parser,
CP_PARSER_FLAGS_OPTIONAL,
&declspecs,
&decl_class_or_enum_p);
/* APPLE LOCAL begin radar 4360010 */
if (declspecs.storage_class == sc_static)
{
error ("storage class specified for ivar");
/* recover */
declspecs.storage_class = sc_none;
}
/* APPLE LOCAL end radar 4360010 */
/* APPLE LOCAL begin radar 4652027 */
else if (declspecs.specs[(int) ds_typedef])
{
error ("typedef declaration among ivars");
cp_lexer_consume_token (parser->lexer); /* recover */
}
/* APPLE LOCAL end radar 4652027 */
prefix_attributes = declspecs.attributes;
declspecs.attributes = NULL_TREE;
/* Keep going until we hit the `;' at the end of the
declaration. */
while (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
{
tree width = NULL_TREE, attributes, first_attribute, decl;
cp_declarator *declarator = NULL;
int ctor_dtor_or_conv_p;
/* Check for a (possibly unnamed) bitfield declaration. */
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_COLON)
goto eat_colon;
if (token->type == CPP_NAME
&& (cp_lexer_peek_nth_token (parser->lexer, 2)->type
== CPP_COLON))
{
/* Get the name of the bitfield. */
declarator = make_id_declarator (NULL_TREE,
cp_parser_identifier (parser),
sfk_none);
eat_colon:
cp_lexer_consume_token (parser->lexer); /* Eat ':'. */
/* Get the width of the bitfield. */
width
= cp_parser_constant_expression (parser,
/*allow_non_constant=*/false,
NULL);
}
else
{
/* Parse the declarator. */
declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_NAMED,
&ctor_dtor_or_conv_p,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
}
/* Look for attributes that apply to the ivar. */
attributes = cp_parser_attributes_opt (parser);
/* Remember which attributes are prefix attributes and
which are not. */
first_attribute = attributes;
/* Combine the attributes. */
attributes = chainon (prefix_attributes, attributes);
if (width)
{
/* Create the bitfield declaration. */
decl = grokbitfield (declarator, &declspecs, width);
cplus_decl_attributes (&decl, attributes, /*flags=*/0);
}
else
decl = grokfield (declarator, &declspecs,
NULL_TREE, /*init_const_expr_p=*/false,
NULL_TREE, attributes);
/* Add the instance variable. */
objc_add_instance_variable (decl);
/* Reset PREFIX_ATTRIBUTES. */
while (attributes && TREE_CHAIN (attributes) != first_attribute)
attributes = TREE_CHAIN (attributes);
if (attributes)
TREE_CHAIN (attributes) = NULL_TREE;
token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_COMMA)
{
cp_lexer_consume_token (parser->lexer); /* Eat ','. */
continue;
}
break;
}
cp_parser_consume_semicolon_at_end_of_statement (parser);
token = cp_lexer_peek_token (parser->lexer);
}
cp_lexer_consume_token (parser->lexer); /* Eat '}'. */
/* For historical reasons, we accept an optional semicolon. */
if (cp_lexer_next_token_is (parser->lexer, CPP_SEMICOLON))
cp_lexer_consume_token (parser->lexer);
}
/* Parse an Objective-C protocol declaration. */
static void
/* APPLE LOCAL radar 4947311 */
cp_parser_objc_protocol_declaration (cp_parser* parser, tree attributes)
{
tree proto, protorefs;
cp_token *tok;
cp_lexer_consume_token (parser->lexer); /* Eat '@protocol'. */
if (cp_lexer_next_token_is_not (parser->lexer, CPP_NAME))
{
error ("identifier expected after %<@protocol%>");
goto finish;
}
/* See if we have a forward declaration or a definition. */
tok = cp_lexer_peek_nth_token (parser->lexer, 2);
/* Try a forward declaration first. */
if (tok->type == CPP_COMMA || tok->type == CPP_SEMICOLON)
{
/* APPLE LOCAL radar 4947311 */
objc_declare_protocols (cp_parser_objc_identifier_list (parser), attributes);
finish:
cp_parser_consume_semicolon_at_end_of_statement (parser);
}
/* Ok, we got a full-fledged definition (or at least should). */
else
{
proto = cp_parser_identifier (parser);
protorefs = cp_parser_objc_protocol_refs_opt (parser);
/* APPLE LOCAL radar 4947311 */
objc_start_protocol (proto, protorefs, attributes);
cp_parser_objc_method_prototype_list (parser);
}
}
/* Parse an Objective-C superclass or category. */
/* APPLE LOCAL begin radar 4965989 */
static void
cp_parser_objc_superclass_or_category (cp_parser *parser, tree *super,
tree *categ, bool *is_category)
{
cp_token *next = cp_lexer_peek_token (parser->lexer);
*super = *categ = NULL_TREE;
*is_category = false;
if (next->type == CPP_COLON)
{
cp_lexer_consume_token (parser->lexer); /* Eat ':'. */
*super = cp_parser_identifier (parser);
}
else if (next->type == CPP_OPEN_PAREN)
{
cp_lexer_consume_token (parser->lexer); /* Eat '('. */
/* APPLE LOCAL begin radar 4965989 */
next = cp_lexer_peek_token (parser->lexer);
*categ = (next->type == CPP_CLOSE_PAREN) ? NULL_TREE : cp_parser_identifier (parser);
*is_category = true;
/* APPLE LOCAL end radar 4965989 */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
}
}
/* APPLE LOCAL end radar 4965989 */
/* Parse an Objective-C class interface. */
static void
/* APPLE LOCAL radar 4947311 */
cp_parser_objc_class_interface (cp_parser* parser, tree attributes)
{
tree name, super, categ, protos;
/* APPLE LOCAL radar 4965989 */
bool is_categ;
/* APPLE LOCAL radar 4947311 */
/* Code for radar 4548636 removed. */
cp_lexer_consume_token (parser->lexer); /* Eat '@interface'. */
name = cp_parser_identifier (parser);
/* APPLE LOCAL radar 4965989 */
cp_parser_objc_superclass_or_category (parser, &super, &categ, &is_categ);
protos = cp_parser_objc_protocol_refs_opt (parser);
/* We have either a class or a category on our hands. */
/* APPLE LOCAL radar 4965989 */
if (is_categ)
/* APPLE LOCAL begin radar 4548636 */
{
if (attributes)
error ("attributes may not be specified on a category");
objc_start_category_interface (name, categ, protos);
}
/* APPLE LOCAL end radar 4548636 */
else
{
/* APPLE LOCAL radar 4548636 */
objc_start_class_interface (name, super, protos, attributes);
/* Handle instance variable declarations, if any. */
cp_parser_objc_class_ivars (parser);
objc_continue_interface ();
}
cp_parser_objc_method_prototype_list (parser);
}
/* Parse an Objective-C class implementation. */
static void
cp_parser_objc_class_implementation (cp_parser* parser)
{
tree name, super, categ;
/* APPLE LOCAL radar 4965989 */
bool is_categ;
cp_lexer_consume_token (parser->lexer); /* Eat '@implementation'. */
name = cp_parser_identifier (parser);
/* APPLE LOCAL radar 4965989 */
cp_parser_objc_superclass_or_category (parser, &super, &categ, &is_categ);
/* We have either a class or a category on our hands. */
/* APPLE LOCAL begin radar 4965989 */
if (is_categ)
{
if (categ == NULL_TREE)
{
error ("cannot implement anonymous category");
return;
}
objc_start_category_implementation (name, categ);
}
/* APPLE LOCAL end radar 4965989 */
else
{
objc_start_class_implementation (name, super);
/* Handle instance variable declarations, if any. */
cp_parser_objc_class_ivars (parser);
objc_continue_implementation ();
}
cp_parser_objc_method_definition_list (parser);
}
/* Consume the @end token and finish off the implementation. */
static void
cp_parser_objc_end_implementation (cp_parser* parser)
{
cp_lexer_consume_token (parser->lexer); /* Eat '@end'. */
objc_finish_implementation ();
}
/* Parse an Objective-C declaration. */
static void
cp_parser_objc_declaration (cp_parser* parser)
{
/* Try to figure out what kind of declaration is present. */
cp_token *kwd = cp_lexer_peek_token (parser->lexer);
switch (kwd->keyword)
{
case RID_AT_ALIAS:
cp_parser_objc_alias_declaration (parser);
break;
case RID_AT_CLASS:
cp_parser_objc_class_declaration (parser);
break;
case RID_AT_PROTOCOL:
/* APPLE LOCAL radar 4947311 */
cp_parser_objc_protocol_declaration (parser, NULL_TREE);
break;
/* APPLE LOCAL begin radar 4548636 - radar 4947311 */
case RID_ATTRIBUTE:
{
tree attributes = NULL_TREE;
cp_parser_objc_maybe_attributes (parser, &attributes);
if (cp_lexer_peek_token (parser->lexer)->keyword == RID_AT_INTERFACE)
cp_parser_objc_class_interface (parser, attributes);
else if (cp_lexer_peek_token (parser->lexer)->keyword == RID_AT_PROTOCOL)
cp_parser_objc_protocol_declaration (parser, attributes);
break;
}
/* APPLE LOCAL end radar 4548636 - radar 4947311 */
case RID_AT_INTERFACE:
/* APPLE LOCAL radar 4947311 */
cp_parser_objc_class_interface (parser, NULL_TREE);
break;
case RID_AT_IMPLEMENTATION:
cp_parser_objc_class_implementation (parser);
break;
case RID_AT_END:
cp_parser_objc_end_implementation (parser);
break;
default:
error ("misplaced %<@%D%> Objective-C++ construct", kwd->u.value);
cp_parser_skip_to_end_of_block_or_statement (parser);
}
}
/* Parse an Objective-C try-catch-finally statement.
objc-try-catch-finally-stmt:
@try compound-statement objc-catch-clause-seq [opt]
objc-finally-clause [opt]
objc-catch-clause-seq:
objc-catch-clause objc-catch-clause-seq [opt]
objc-catch-clause:
@catch ( exception-declaration ) compound-statement
objc-finally-clause
@finally compound-statement
Returns NULL_TREE. */
static tree
cp_parser_objc_try_catch_finally_statement (cp_parser *parser) {
location_t location;
tree stmt;
cp_parser_require_keyword (parser, RID_AT_TRY, "`@try'");
location = cp_lexer_peek_token (parser->lexer)->location;
/* NB: The @try block needs to be wrapped in its own STATEMENT_LIST
node, lest it get absorbed into the surrounding block. */
stmt = push_stmt_list ();
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, false, false);
objc_begin_try_stmt (location, pop_stmt_list (stmt));
while (cp_lexer_next_token_is_keyword (parser->lexer, RID_AT_CATCH))
{
cp_parameter_declarator *parmdecl;
tree parm;
/* APPLE LOCAL radar 2848255 */
bool ellipsis_seen = false;
cp_lexer_consume_token (parser->lexer);
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
/* APPLE LOCAL begin radar 2848255 */
/* APPLE LOCAL begin radar 4995967 */
{
cp_token *token = cp_lexer_peek_token (parser->lexer);
if (token->type == CPP_ELLIPSIS)
{
/* @catch (...) */
parm = NULL_TREE;
cp_lexer_consume_token (parser->lexer);
ellipsis_seen = true;
}
}
/* APPLE LOCAL end radar 4995967 */
if (!ellipsis_seen)
{
parmdecl = cp_parser_parameter_declaration (parser, false, NULL);
parm = grokdeclarator (parmdecl->declarator,
&parmdecl->decl_specifiers,
PARM, /*initialized=*/0,
/*attrlist=*/NULL);
}
/* APPLE LOCAL end radar 2848255 */
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
objc_begin_catch_clause (parm);
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, false, false);
objc_finish_catch_clause ();
}
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_AT_FINALLY))
{
cp_lexer_consume_token (parser->lexer);
location = cp_lexer_peek_token (parser->lexer)->location;
/* NB: The @finally block needs to be wrapped in its own STATEMENT_LIST
node, lest it get absorbed into the surrounding block. */
stmt = push_stmt_list ();
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, false, false);
objc_build_finally_clause (location, pop_stmt_list (stmt));
}
return objc_finish_try_stmt ();
}
/* Parse an Objective-C synchronized statement.
objc-synchronized-stmt:
@synchronized ( expression ) compound-statement
Returns NULL_TREE. */
static tree
cp_parser_objc_synchronized_statement (cp_parser *parser) {
location_t location;
tree lock, stmt;
cp_parser_require_keyword (parser, RID_AT_SYNCHRONIZED, "`@synchronized'");
location = cp_lexer_peek_token (parser->lexer)->location;
cp_parser_require (parser, CPP_OPEN_PAREN, "`('");
lock = cp_parser_expression (parser, false);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* NB: The @synchronized block needs to be wrapped in its own STATEMENT_LIST
node, lest it get absorbed into the surrounding block. */
stmt = push_stmt_list ();
/* APPLE LOCAL radar 5982990 */
cp_parser_compound_statement (parser, NULL, false, flag_objc_sjlj_exceptions);
return objc_build_synchronized (location, lock, pop_stmt_list (stmt));
}
/* Parse an Objective-C throw statement.
objc-throw-stmt:
@throw assignment-expression [opt] ;
Returns a constructed '@throw' statement. */
static tree
cp_parser_objc_throw_statement (cp_parser *parser) {
tree expr = NULL_TREE;
cp_parser_require_keyword (parser, RID_AT_THROW, "`@throw'");
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
expr = cp_parser_assignment_expression (parser, false);
cp_parser_consume_semicolon_at_end_of_statement (parser);
return objc_build_throw_stmt (expr);
}
/* Parse an Objective-C statement. */
static tree
cp_parser_objc_statement (cp_parser * parser) {
/* Try to figure out what kind of declaration is present. */
cp_token *kwd = cp_lexer_peek_token (parser->lexer);
switch (kwd->keyword)
{
case RID_AT_TRY:
return cp_parser_objc_try_catch_finally_statement (parser);
case RID_AT_SYNCHRONIZED:
return cp_parser_objc_synchronized_statement (parser);
case RID_AT_THROW:
return cp_parser_objc_throw_statement (parser);
default:
error ("misplaced %<@%D%> Objective-C++ construct", kwd->u.value);
cp_parser_skip_to_end_of_block_or_statement (parser);
}
return error_mark_node;
}
/* APPLE LOCAL begin C* language */
/* Routine closes up the C*'s foreach statement.
*/
static void
objc_finish_foreach_stmt (tree for_stmt)
{
if (flag_new_for_scope > 0)
{
tree scope = TREE_CHAIN (for_stmt);
TREE_CHAIN (for_stmt) = NULL;
add_stmt (do_poplevel (scope));
}
finish_stmt ();
}
/*
Synthesizer routine for C*'s feareach statement.
It synthesizes:
for ( type elem in collection) { stmts; }
Into:
{
type elem;
__objcFastEnumerationState enumState = { 0 };
id items[16];
unsigned long limit = [collection countByEnumeratingWithState:&enumState objects:items count:16];
if (limit) {
unsigned long startMutations = *enumState.mutationsPtr;
do {
unsigned long counter = 0;
do {
if (startMutations != *enumState.mutationsPtr) objc_enumerationMutation(collection);
elem = enumState.itemsPtr[counter++];
stmts;
} while (counter < limit);
} while (limit = [collection countByEnumeratingWithState:&enumState objects:items count:16]);
}
else
elem = nil; radar 4854605, 5128402
*/
static void
objc_foreach_stmt (cp_parser* parser, tree statement)
{
unsigned char in_statement;
tree enumerationMutation_call_exp;
tree countByEnumeratingWithState;
tree receiver;
tree exp, bind;
tree enumState_decl, items_decl;
tree limit_decl, limit_decl_assign_expr;
tree outer_if_stmt, inner_if_stmt, if_condition, startMutations_decl;
tree outer_do_stmt, inner_do_stmt, do_condition;
tree counter_decl;
tree_stmt_iterator i = tsi_start (TREE_CHAIN (statement));
tree t = tsi_stmt (i);
/* APPLE LOCAL radar 5130983 */
tree elem_decl = TREE_CODE (t) == DECL_EXPR ? DECL_EXPR_DECL (t) : t;
receiver = cp_parser_condition (parser);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
/* APPLE LOCAL begin radar 5130983 */
if (elem_decl == error_mark_node)
return;
if (!lvalue_or_else (&elem_decl, lv_foreach))
return;
/* APPLE LOCAL end radar 5130983 */
/* APPLE LOCAL begin radar 4507230 */
if (!objc_type_valid_for_messaging (TREE_TYPE (elem_decl)))
{
error ("selector element does not have a valid object type");
return;
}
if (!objc_type_valid_for_messaging (TREE_TYPE (receiver)))
{
error ("expression does not have a valid object type");
return;
}
/* APPLE LOCAL end radar 4507230 */
enumerationMutation_call_exp = objc_build_foreach_components (receiver, &enumState_decl,
&items_decl, &limit_decl,
&startMutations_decl, &counter_decl,
&countByEnumeratingWithState);
/* __objcFastEnumerationState enumState = { 0 }; */
exp = build_stmt (DECL_EXPR, enumState_decl);
bind = build3 (BIND_EXPR, void_type_node, enumState_decl, exp, NULL);
TREE_SIDE_EFFECTS (bind) = 1;
add_stmt (bind);
/* id items[16]; */
bind = build3 (BIND_EXPR, void_type_node, items_decl, NULL, NULL);
TREE_SIDE_EFFECTS (bind) = 1;
add_stmt (bind);
/* Generate this statement and add it to the list. */
/* limit = [collection countByEnumeratingWithState:&enumState objects:items count:16] */
limit_decl_assign_expr = build2 (MODIFY_EXPR, TREE_TYPE (limit_decl), limit_decl,
countByEnumeratingWithState);
bind = build3 (BIND_EXPR, void_type_node, limit_decl, NULL, NULL);
TREE_SIDE_EFFECTS (bind) = 1;
add_stmt (bind);
/* if (limit) { */
outer_if_stmt = begin_if_stmt ();
/* APPLE LOCAL radar 4547045 */
if_condition = build_binary_op (NE_EXPR, limit_decl_assign_expr,
fold_convert (TREE_TYPE (limit_decl), integer_zero_node),
1);
finish_if_stmt_cond (if_condition, outer_if_stmt);
/* unsigned long startMutations = *enumState.mutationsPtr; */
exp = objc_build_component_ref (enumState_decl, get_identifier("mutationsPtr"));
exp = build_indirect_ref (exp, "unary *");
exp = build2 (MODIFY_EXPR, void_type_node, startMutations_decl, exp);
bind = build3 (BIND_EXPR, void_type_node, startMutations_decl, exp, NULL);
TREE_SIDE_EFFECTS (bind) = 1;
add_stmt (bind);
/* do { */
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
outer_do_stmt = begin_do_stmt (NULL_TREE);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
/* Body of the outer do-while loop */
/* unsigned int counter = 0; */
exp = build2 (MODIFY_EXPR, void_type_node, counter_decl,
fold_convert (TREE_TYPE (counter_decl), integer_zero_node));
bind = build3 (BIND_EXPR, void_type_node, counter_decl, exp, NULL);
TREE_SIDE_EFFECTS (bind) = 1;
add_stmt (bind);
/* do { */
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
inner_do_stmt = begin_do_stmt (NULL_TREE);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
/* Body of the inner do-while loop */
/* if (startMutations != *enumState.mutationsPtr) objc_enumerationMutation (collection); */
inner_if_stmt = begin_if_stmt ();
exp = objc_build_component_ref (enumState_decl, get_identifier("mutationsPtr"));
exp = build_indirect_ref (exp, "unary *");
if_condition = build_binary_op (NE_EXPR, startMutations_decl, exp, 1);
finish_if_stmt_cond (if_condition, inner_if_stmt);
add_stmt (enumerationMutation_call_exp);
finish_then_clause (inner_if_stmt);
finish_if_stmt (inner_if_stmt);
/* elem = enumState.itemsPtr [counter]; */
exp = objc_build_component_ref (enumState_decl, get_identifier("itemsPtr"));
exp = build_array_ref (exp, counter_decl);
add_stmt (build2 (MODIFY_EXPR, void_type_node, elem_decl, exp));
/* APPLE LOCAL radar 4538105 */
TREE_USED (elem_decl) = 1;
/* counter++; */
exp = build2 (PLUS_EXPR, TREE_TYPE (counter_decl), counter_decl,
build_int_cst (NULL_TREE, 1));
add_stmt (build2 (MODIFY_EXPR, void_type_node, counter_decl, exp));
/* ADD << stmts >> from the foreach loop. */
/* Parse the body of the for-statement. */
in_statement = parser->in_statement;
parser->in_statement = IN_ITERATION_STMT;
cp_parser_already_scoped_statement (parser);
parser->in_statement = in_statement;
finish_do_body (inner_do_stmt);
/* } while (counter < limit ); */
do_condition = build_binary_op (LT_EXPR, counter_decl, limit_decl, 1);
finish_do_stmt (do_condition, inner_do_stmt);
DO_FOREACH (inner_do_stmt) = integer_zero_node;
/* APPLE LOCAL radar 4667060 */
DO_FOREACH (outer_do_stmt) = elem_decl;
finish_do_body (outer_do_stmt);
/* } while (limit = [collection countByEnumeratingWithState:&enumState objects:items count:16]); */
exp = unshare_expr (limit_decl_assign_expr);
do_condition = build_binary_op (NE_EXPR, exp,
fold_convert (TREE_TYPE (limit_decl), integer_zero_node),
1);
finish_do_stmt (do_condition, outer_do_stmt);
finish_then_clause (outer_if_stmt);
/* } */
/* APPLE LOCAL begin radar 4854605 - radar 5128402 */
begin_else_clause (outer_if_stmt);
add_stmt (build2 (MODIFY_EXPR, void_type_node, elem_decl,
fold_convert (TREE_TYPE (elem_decl), integer_zero_node)));
finish_else_clause (outer_if_stmt);
/* APPLE LOCAL end radar 4854605 - radar 5128402 */
finish_if_stmt (outer_if_stmt);
objc_finish_foreach_stmt (statement);
}
/* APPLE LOCAL end C* language */
/* APPLE LOCAL begin blocks 6040305 (ce) */
#define I_SYMBOL_BINDING(t) IDENTIFIER_BINDING(t)
tree build_component_ref (tree e, tree member);
tree
build_component_ref (tree e, tree member)
{
if (!DECL_P (member))
member = lookup_member (TREE_TYPE (e), member, 0, 0);
if (processing_template_decl)
return build3 (COMPONENT_REF, TREE_TYPE (member), e, DECL_NAME (member), NULL_TREE);
return build_class_member_access_expr (e, member,
NULL_TREE, false);
}
/* APPLE LOCAL begin radar 6214617 */
static bool
cp_block_requires_copying (tree exp)
{
return (block_requires_copying (exp)
|| TYPE_HAS_CONSTRUCTOR (TREE_TYPE (exp))
|| TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (exp)));
}
/* APPLE LOCAL end radar 6214617 */
/* APPLE LOCAL begin radar 5847213 - radar 6329245 */
/** build_descriptor_block_decl -
This routine builds a static block_descriptior variable of type:
struct __block_descriptor; and initializes it to:
{0, sizeof(struct literal_block_n),
copy_helper_block_1, // only if block BLOCK_HAS_COPY_DISPOSE
destroy_helper_block_1, // only if block BLOCK_HAS_COPY_DISPOSE
// APPLE LOCAL begin radar 8143947
// const char *signature; // the block signature set to 0
// const char *layout; // reserved set to 0
// APPLE LOCAL end radar 8143947
}
*/
static tree
build_descriptor_block_decl (tree block_struct_type, struct block_sema_info *block_impl)
{
extern tree create_tmp_var_raw (tree, const char *);
static int desc_unique_count;
int size;
tree helper_addr;
tree decl, constructor;
char name [32];
VEC(constructor_elt,gc) *impl_v = NULL;
tree descriptor_type =
TREE_TYPE (build_block_descriptor_type (block_impl->BlockHasCopyDispose));
sprintf (name, "__block_descriptor_tmp_%d", ++desc_unique_count);
decl = create_tmp_var_raw (descriptor_type, name);
DECL_CONTEXT (decl) = NULL_TREE;
/* Initialize "reserved" field to 0 for now. */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, build_int_cst (long_unsigned_type_node, 0));
/* Initialize "Size" field. */
size = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (block_struct_type));
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, build_int_cst (long_unsigned_type_node, size));
if (block_impl->BlockHasCopyDispose)
{
/* Initialize "CopyFuncPtr" and "DestroyFuncPtr" fields. */
/* Helpers were previously generated completeley as a nested
function (and context was required for code gen.) But they are not,
so context must be set to NULL so initialization logic does not complain. */
DECL_CONTEXT (block_impl->copy_helper_func_decl) = NULL_TREE;
helper_addr = build_fold_addr_expr (block_impl->copy_helper_func_decl);
helper_addr = convert (ptr_type_node, helper_addr);
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, helper_addr);
DECL_CONTEXT (block_impl->destroy_helper_func_decl) = NULL_TREE;
helper_addr = build_fold_addr_expr (block_impl->destroy_helper_func_decl);
helper_addr = convert (ptr_type_node, helper_addr);
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, helper_addr);
}
/* APPLE LOCAL begin radar 8143947 */
/* signature field is set to 0 */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE,
build_int_cst (build_pointer_type (char_type_node), 0));
/* layout field is set to 0 */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE,
build_int_cst (build_pointer_type (char_type_node), 0));
/* APPLE LOCAL end radar 8143947 */
/* Create a CONSTRUCTOR to represent the braced-initializer. */
constructor = make_node (CONSTRUCTOR);
CONSTRUCTOR_ELTS (constructor) = impl_v;
TREE_PUBLIC (decl) = 0;
TREE_STATIC (decl) = 1;
cp_finish_decl (decl, constructor, 0, 0, LOOKUP_ONLYCONVERTING);
return decl;
}
/* APPLE LOCAL begin radar 6300081 */
/* This function builds a "generic" block struct type, to be passed
into the debug information for blocks pointers, to allow gdb to
find the actual function pointer for the block. Any time the Blocks
structure layout changes, this may also need to change.
Currently a block pointer is a pointer to a __block_literal_n struct,
the third field of which is a pointer to a __block_descriptor struct,
whose third field is the function pointer. There are other fields as
well, but these are the ones gdb needs to know about to find the
function pointer. Therefore a generic block struct currently looks
like this:
struct __block_literal_generic
{
void * __isa;
int __flags;
int __reserved;
void *__FuncPtr;
struct __block_descriptor
{
unsigned long int reserved;
unsigned long int Size;
// APPLE LOCAL begin radar 8143927
const char *signature; // the block signature
const char *layout; // reserved
// APPLE LOCAL end radar 8143927
} *__descriptor;
};
IF AT ANY TIME THE STRUCTURE OF A __BLOCK_LITERAL_N CHANGES, THIS
MUST BE CHANGED ALSO!!
*/
tree
/* APPLE LOCAL radar 6353006 */
c_build_generic_block_struct_type (void)
{
tree fields = NULL_TREE;
tree field;
tree block_struct_type;
push_to_top_level ();
block_struct_type = xref_tag (record_type,
get_identifier ("__block_literal_generic"),
ts_current, false);
xref_basetypes (block_struct_type, NULL_TREE);
CLASSTYPE_DECLARED_CLASS (block_struct_type) = 0;
pushclass (block_struct_type);
field = build_decl (FIELD_DECL, get_identifier ("__isa"), ptr_type_node);
TREE_CHAIN (field) = fields;
fields = field;
field = build_decl (FIELD_DECL, get_identifier ("__flags"),
integer_type_node);
TREE_CHAIN (field) = fields;
fields = field;
field = build_decl (FIELD_DECL, get_identifier ("__reserved"),
integer_type_node);
TREE_CHAIN (field) = fields;
fields = field;
field = build_decl (FIELD_DECL, get_identifier ("__FuncPtr"),
ptr_type_node);
TREE_CHAIN (field) = fields;
fields = field;
field = build_decl (FIELD_DECL, get_identifier ("__descriptor"),
build_block_descriptor_type (false));
TREE_CHAIN (field) = fields;
fields = field;
TYPE_FIELDS (block_struct_type) = fields;
TYPE_NAME (block_struct_type) = build_decl (TYPE_DECL,
get_identifier ("__block_literal_generic"),
block_struct_type);
TYPE_STUB_DECL (block_struct_type) = TYPE_NAME (block_struct_type);
TYPE_BLOCK_IMPL_STRUCT (block_struct_type) = 1;
finish_struct (block_struct_type, NULL_TREE);
pop_from_top_level ();
return block_struct_type;
}
/* APPLE LOCAL end radar 6300081 */
/** build_block_struct_type -
struct __block_literal_n {
void *__isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock
int __flags;
int __reserved;
void *__FuncPtr;
struct __block_descriptor {
unsigned long int reserved; // NULL
unsigned long int Size; // sizeof(struct __block_literal_n)
// optional helper functions
void *CopyFuncPtr; // When BLOCK_HAS_COPY_DISPOSE
void *DestroyFuncPtr; // When BLOCK_HAS_COPY_DISPOSE
} *__descriptor;
// imported variables
int x; // ref variable list ...
int *y; // byref variable list
};
*/
static tree
build_block_struct_type (struct block_sema_info * block_impl)
{
tree fields = NULL_TREE, field, chain;
char buffer[32];
static int unique_count;
tree block_struct_type;
/* Check and see if this block is required to have a Copy/Dispose
helper function. If yes, set BlockHasCopyDispose to TRUE. */
for (chain = block_impl->block_ref_decl_list; chain;
chain = TREE_CHAIN (chain))
/* APPLE LOCAL begin radar 6214617 */
if (cp_block_requires_copying (TREE_VALUE (chain)))
{
tree type = TREE_TYPE (TREE_VALUE (chain));
block_impl->BlockHasCopyDispose = TRUE;
if (TYPE_HAS_CONSTRUCTOR (type) || TYPE_NEEDS_CONSTRUCTING (type))
{
block_impl->BlockImportsCxxObjects = TRUE;
break;
}
/* APPLE LOCAL end radar 6214617 */
}
/* Further check to see that we have __block variables which require
Copy/Dispose helpers. */
for (chain = block_impl->block_byref_decl_list; chain;
chain = TREE_CHAIN (chain))
if (COPYABLE_BYREF_LOCAL_VAR (TREE_VALUE (chain)))
{
block_impl->BlockHasCopyDispose = TRUE;
break;
}
sprintf(buffer, "__block_literal_%d", ++unique_count);
push_to_top_level ();
/* APPLE LOCAL begin radar 6243400 */
block_struct_type = xref_tag (record_type, get_identifier (buffer), ts_current, false);
xref_basetypes (block_struct_type, NULL_TREE);
CLASSTYPE_DECLARED_CLASS (block_struct_type) = 0;
pushclass (block_struct_type);
/* APPLE LOCAL end radar 6243400 */
/* void * __isa; */
field = build_decl (FIELD_DECL, get_identifier ("__isa"), ptr_type_node);
TREE_CHAIN (field) = fields;
fields = field;
/* int __flags. */
field = build_decl (FIELD_DECL, get_identifier ("__flags"), integer_type_node);
TREE_CHAIN (field) = fields;
fields = field;
/* int __reserved. */
field = build_decl (FIELD_DECL, get_identifier ("__reserved"), integer_type_node);
TREE_CHAIN (field) = fields;
fields = field;
/* void *__FuncPtr. */
field = build_decl (FIELD_DECL, get_identifier ("__FuncPtr"),
ptr_type_node);
TREE_CHAIN (field) = fields;
fields = field;
/* struct __block_descriptor *__descriptor */
field = build_decl (FIELD_DECL, get_identifier ("__descriptor"),
build_block_descriptor_type (block_impl->BlockHasCopyDispose));
TREE_CHAIN (field) = fields;
fields = field;
if (block_impl->BlockHasCopyDispose)
{
/* If inner block of a nested block has BlockHasCopyDispose, so
does its outer block. */
if (block_impl->prev_block_info)
block_impl->prev_block_info->BlockHasCopyDispose = TRUE;
}
/* int x; // ref variable list ... */
for (chain = block_impl->block_ref_decl_list; chain; chain = TREE_CHAIN (chain))
{
tree p = TREE_VALUE (chain);
/* Note! const-ness of copied in variable must not be carried over to the
type of the synthesized struct field. It prevents to assign to this
field when copy constructor is synthesized. */
field = build_decl (FIELD_DECL, DECL_NAME (p),
c_build_qualified_type (TREE_TYPE (p),
TYPE_UNQUALIFIED));
TREE_CHAIN (field) = fields;
fields = field;
}
/* int *y; // byref variable list */
for (chain = block_impl->block_byref_decl_list; chain; chain = TREE_CHAIN (chain))
{
tree p = TREE_VALUE (chain);
field = build_decl (FIELD_DECL, DECL_NAME (p),
TREE_TYPE (p));
TREE_CHAIN (field) = fields;
fields = field;
}
/* APPLE LOCAL begin radar 6243400 */
TYPE_FIELDS (block_struct_type) = fields;
TYPE_NAME (block_struct_type) =
build_decl (TYPE_DECL, get_identifier (buffer), block_struct_type);
TYPE_STUB_DECL (block_struct_type) = TYPE_NAME (block_struct_type);
finish_struct (block_struct_type, NULL_TREE);
pop_from_top_level ();
/* APPLE LOCAL end radar 6243400 */
return block_struct_type;
}
/**
build_block_struct_initlist - builds the initializer list:
{ &_NSConcreteStackBlock or &_NSConcreteGlobalBlock // __isa,
BLOCK_USE_STRET | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL // __flags,
| BLOCK_HAS_SIGNATURE // __flags
0, // __reserved,
&helper_1, // __FuncPtr,
&static_descriptor_variable // __descriptor,
x, // user variables.
&y
...
}
*/
/* APPLE LOCAL begin radar 6169527 */
/* This routine is entirely rewritten as we now have to deal with full-blown
c++ classes with fields which may require construction. */
static VEC(constructor_elt,gc) *
build_block_struct_initlist (tree block_struct_type,
struct block_sema_info *block_impl)
{
tree expr, chain, helper_addr;
/* APPLE LOCAL radar 7735196 */
unsigned flags = BLOCK_HAS_SIGNATURE;
static tree NSConcreteStackBlock_decl = NULL_TREE;
static tree NSConcreteGlobalBlock_decl = NULL_TREE;
VEC(constructor_elt,gc) *impl_v = NULL;
tree descriptor_block_decl = build_descriptor_block_decl (block_struct_type, block_impl);
if (block_impl->BlockHasCopyDispose)
/* Note! setting of this flag merely indicates to the runtime that
we have destroy_helper_block/copy_helper_block helper
routines. */
flags |= BLOCK_HAS_COPY_DISPOSE;
/* APPLE LOCAL begin radar 6214617 */
/* Set BLOCK_HAS_CXX_OBJ if block is importing a cxx object. */
if (block_impl->BlockImportsCxxObjects)
flags |= BLOCK_HAS_CXX_OBJ;
/* APPLE LOCAL end radar 6214617 */
/* APPLE LOCAL begin radar 7735196 */
if (block_impl->return_type && aggregate_value_p(block_impl->return_type, 0))
flags |= BLOCK_USE_STRET;
/* APPLE LOCAL end 7735196 */
/* APPLE LOCAL begin radar 6230297 */
if (!current_function_decl ||
(block_impl->block_ref_decl_list == NULL_TREE &&
block_impl->block_byref_decl_list == NULL_TREE))
/* APPLE LOCAL end radar 6230297 */
{
/* This is a global block. */
/* Find an existing declaration for _NSConcreteGlobalBlock or declare
extern void *_NSConcreteGlobalBlock; */
if (NSConcreteGlobalBlock_decl == NULL_TREE)
{
tree name_id = get_identifier("_NSConcreteGlobalBlock");
NSConcreteGlobalBlock_decl = lookup_name (name_id);
if (!NSConcreteGlobalBlock_decl)
{
NSConcreteGlobalBlock_decl = build_decl (VAR_DECL, name_id, ptr_type_node);
DECL_EXTERNAL (NSConcreteGlobalBlock_decl) = 1;
TREE_PUBLIC (NSConcreteGlobalBlock_decl) = 1;
pushdecl_top_level (NSConcreteGlobalBlock_decl);
rest_of_decl_compilation (NSConcreteGlobalBlock_decl, 0, 0);
}
}
/* APPLE LOCAL begin radar 6457359 */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE,
convert (ptr_type_node,
build_fold_addr_expr (NSConcreteGlobalBlock_decl)));
/* APPLE LOCAL end radar 6457359 */
flags |= BLOCK_IS_GLOBAL;
}
else
{
/* Find an existing declaration for _NSConcreteStackBlock or declare
extern void *_NSConcreteStackBlock; */
if (NSConcreteStackBlock_decl == NULL_TREE)
{
tree name_id = get_identifier("_NSConcreteStackBlock");
NSConcreteStackBlock_decl = lookup_name (name_id);
if (!NSConcreteStackBlock_decl)
{
NSConcreteStackBlock_decl = build_decl (VAR_DECL, name_id, ptr_type_node);
DECL_EXTERNAL (NSConcreteStackBlock_decl) = 1;
TREE_PUBLIC (NSConcreteStackBlock_decl) = 1;
pushdecl_top_level (NSConcreteStackBlock_decl);
rest_of_decl_compilation (NSConcreteStackBlock_decl, 0, 0);
}
}
/* APPLE LOCAL begin radar 6457359 */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE,
convert (ptr_type_node,
build_fold_addr_expr (NSConcreteStackBlock_decl)));
/* APPLE LOCAL end radar 6457359 */
}
/* __flags */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, build_int_cst (integer_type_node, flags));
/* __reserved */
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, build_int_cst (integer_type_node, 0));
/* __FuncPtr */
helper_addr = build_fold_addr_expr (block_impl->helper_func_decl);
helper_addr = convert (ptr_type_node, helper_addr);
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, helper_addr);
/* &static_descriptor_variable initializer */
expr = build_fold_addr_expr (descriptor_block_decl);
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, expr);
for (chain = block_impl->block_original_ref_decl_list; chain;
chain = TREE_CHAIN (chain))
{
tree y = TREE_VALUE (chain);
TREE_USED (y) = 1;
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, y);
}
for (chain = block_impl->block_byref_decl_list; chain;
chain = TREE_CHAIN (chain))
{
tree y = lookup_name (DECL_NAME (TREE_VALUE (chain)));
tree forwarding_expr;
gcc_assert (y);
TREE_USED (y) = 1;
if (COPYABLE_BYREF_LOCAL_VAR (y))
{
/* For variables declared __block, either the original one
at the point of declaration or the imported version (which is
initialized in the helper function's prologue) is used to
initilize the byref variable field in the temporary. */
if (TREE_CODE (TREE_TYPE (y)) != RECORD_TYPE)
y = build_indirect_ref (y, "unary *");
/* We will be using the __block_struct_variable.__forwarding as the
initializer. */
forwarding_expr = build_component_ref (y, get_identifier ("__forwarding"));
}
else
/* Global variable is always assumed passed by its address. */
forwarding_expr = build_fold_addr_expr (y);
CONSTRUCTOR_APPEND_ELT(impl_v, NULL_TREE, forwarding_expr);
}
return impl_v;
}
/* APPLE LOCAL end radar 6169527 */
/* APPLE LOCAL end radar 5847213 - radar 6329245 */
/**
build_block_literal_tmp - This routine:
1) builds block type:
struct __block_literal_n {
void *__isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock
int __flags;
int __reserved;
void *__FuncPtr;
struct __block_descriptor {
unsigned long int reserved; // NULL
unsigned long int Size; // sizeof(struct Block_literal_1)
// optional helper functions
void *CopyFuncPtr; // When BLOCK_HAS_COPY_DISPOSE
void *DestroyFuncPtr; // When BLOCK_HAS_COPY_DISPOSE
} *__descriptor;
// imported variables
int x; // ref variable list ...
int *y; // byref variable list
};
2) build function prototype:
double helper_1(struct block_1 *ii, int z);
3) build the temporary initialization:
struct block_1 I = {
{ &_NSConcreteStackBlock or &_NSConcreteGlobalBlock // isa,
BLOCK_HAS_CXX_OBJ | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL // flags,
0, // reserved,
&helper_1,
&{
NULL,
sizeof(struct block_1),
copy_helper_block_1, // only if block BLOCK_HAS_COPY_DISPOSE
destroy_helper_block_1, // only if block BLOCK_HAS_COPY_DISPOSE
},
x,
&y
};
It return the temporary.
*/
/* APPLE LOCAL begin radar 6169527 */
static tree
build_block_literal_tmp (const char *name,
struct block_sema_info * block_impl)
{
extern tree create_tmp_var_raw (tree, const char *);
tree block_holder_tmp_decl;
tree constructor;
tree block_struct_type = TREE_TYPE (block_impl->block_arg_ptr_type);
/* APPLE LOCAL begin radar 6230297 */
bool staticBlockTmp = (block_impl->block_ref_decl_list == NULL_TREE &&
block_impl->block_byref_decl_list == NULL_TREE);
block_holder_tmp_decl = create_tmp_var_raw (block_struct_type, name);
/* Context will not be known until when the literal is synthesized.
This is more so in the case of nested block literal blocks. */
maybe_push_decl (block_holder_tmp_decl);
DECL_CONTEXT (block_holder_tmp_decl) = staticBlockTmp ? NULL_TREE
: current_function_decl;
if (staticBlockTmp)
DECL_CONTEXT (block_impl->helper_func_decl) = NULL_TREE;
/* APPLE LOCAL end radar 6230297 */
DECL_ARTIFICIAL (block_holder_tmp_decl) = 1;
/* Create a CONSTRUCTOR to represent the braced-initializer. */
constructor = make_node (CONSTRUCTOR);
CONSTRUCTOR_ELTS (constructor) = build_block_struct_initlist (block_struct_type,
block_impl);
/* Temporary representing a global block is made global static. */
/* APPLE LOCAL radar 6230297 */
if (staticBlockTmp || global_bindings_p ()) {
TREE_PUBLIC (block_holder_tmp_decl) = 0;
TREE_STATIC (block_holder_tmp_decl) = 1;
}
cp_finish_decl (block_holder_tmp_decl, constructor, 0, 0, LOOKUP_ONLYCONVERTING);
return block_holder_tmp_decl;
}
/* APPLE LOCAL end radar 6169527 */
static tree
clean_and_exit (tree block)
{
pop_function_context ();
pop_lang_context ();
if (current_function_decl)
free (finish_block (block));
return error_mark_node;
}
/** synth_copy_helper_block_func - This function synthesizes
void copy_helper_block (struct block* _dest, struct block *_src) function.
*/
static void
synth_copy_helper_block_func (struct block_sema_info * block_impl)
{
tree stmt, chain;
tree dst_arg, src_arg;
/* struct c_arg_info * arg_info; */
/* Set up: (struct block* _dest, struct block *_src) parameters. */
dst_arg = build_decl (PARM_DECL, get_identifier ("_dst"),
block_impl->block_arg_ptr_type);
DECL_CONTEXT (dst_arg) = cur_block->copy_helper_func_decl;
TREE_USED (dst_arg) = 1;
DECL_ARG_TYPE (dst_arg) = block_impl->block_arg_ptr_type;
src_arg = build_decl (PARM_DECL, get_identifier ("_src"),
block_impl->block_arg_ptr_type);
DECL_CONTEXT (src_arg) = cur_block->copy_helper_func_decl;
TREE_USED (src_arg) = 1;
DECL_ARG_TYPE (src_arg) = block_impl->block_arg_ptr_type;
/* arg_info = xcalloc (1, sizeof (struct c_arg_info)); */
TREE_CHAIN (dst_arg) = src_arg;
pushdecl (cur_block->copy_helper_func_decl);
/* arg_info->parms = dst_arg; */
/* arg_info->types = tree_cons (NULL_TREE, block_impl->block_arg_ptr_type,
tree_cons (NULL_TREE,
block_impl->block_arg_ptr_type,
NULL_TREE)); */
DECL_ARGUMENTS (cur_block->copy_helper_func_decl) = dst_arg;
/* function header synthesis. */
push_function_context ();
/* start_block_helper_function (cur_block->copy_helper_func_decl, true); */
/* store_parm_decls (arg_info); */
start_preparsed_function (cur_block->copy_helper_func_decl,
/*attrs*/NULL_TREE,
SF_PRE_PARSED);
/* Body of the function. */
stmt = begin_compound_stmt (BCS_FN_BODY);
for (chain = block_impl->block_ref_decl_list; chain;
chain = TREE_CHAIN (chain))
/* APPLE LOCAL radar 6214617 */
if (cp_block_requires_copying (TREE_VALUE (chain)))
{
/* APPLE LOCAL begin radar 6175959 */
int flag = 0;
tree p = TREE_VALUE (chain);
tree dst_block_component, src_block_component;
dst_block_component = build_component_ref (build_indirect_ref (dst_arg, "->"),
DECL_NAME (p));
src_block_component = build_component_ref (build_indirect_ref (src_arg, "->"),
DECL_NAME (p));
if (TREE_CODE (TREE_TYPE (p)) == BLOCK_POINTER_TYPE)
/* _Block_object_assign(&_dest->myImportedBlock, _src->myImportedClosure, BLOCK_FIELD_IS_BLOCK) */
flag = BLOCK_FIELD_IS_BLOCK;
/* APPLE LOCAL begin radar 6214617 */
else if (TYPE_HAS_CONSTRUCTOR (TREE_TYPE (p))
|| TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (p)))
{
tree call_exp = build_aggr_init (dst_block_component, src_block_component,
LOOKUP_ONLYCONVERTING);
add_stmt (call_exp);
}
/* APPLE LOCAL end radar 6214617 */
else
/* _Block_object_assign(&_dest->myImportedBlock, _src->myImportedClosure, BLOCK_FIELD_IS_OBJECT) */
flag = BLOCK_FIELD_IS_OBJECT;
if (flag)
{
tree call_exp;
dst_block_component = build_fold_addr_expr (dst_block_component);
call_exp = build_block_object_assign_call_exp (dst_block_component, src_block_component, flag);
add_stmt (call_exp);
}
/* APPLE LOCAL end radar 6175959 */
}
/* For each __block declared variable used in |...| Must generate call to:
_Block_object_assign(&_dest->myImportedBlock, _src->myImportedBlock, BLOCK_FIELD_IS_BYREF [|BLOCK_FIELD_IS_WEAK])
*/
for (chain = block_impl->block_byref_decl_list; chain;
chain = TREE_CHAIN (chain))
if (COPYABLE_BYREF_LOCAL_VAR (TREE_VALUE (chain)))
{
int flag = BLOCK_FIELD_IS_BYREF;
tree call_exp;
tree p = TREE_VALUE (chain);
tree dst_block_component, src_block_component;
dst_block_component = build_component_ref (build_indirect_ref (dst_arg, "->"),
DECL_NAME (p));
src_block_component = build_component_ref (build_indirect_ref (src_arg, "->"),
DECL_NAME (p));
/* _Block_object_assign(&_dest->myImportedClosure, _src->myImportedClosure, BLOCK_FIELD_IS_BYREF [|BLOCK_FIELD_IS_WEAK]) */
if (COPYABLE_WEAK_BLOCK (p))
flag |= BLOCK_FIELD_IS_WEAK;
dst_block_component = build_fold_addr_expr (dst_block_component);
call_exp = build_block_object_assign_call_exp (dst_block_component, src_block_component, flag);
add_stmt (call_exp);
}
finish_compound_stmt (stmt);
/* APPLE LOCAL radar 6169580 */
finish_function (4);
/* Hum, would be nice if someone else did this for us. */
if (global_bindings_p ())
cgraph_finalize_function (block_impl->copy_helper_func_decl, false);
pop_function_context ();
/* free (arg_info); */
}
static void
synth_destroy_helper_block_func (struct block_sema_info * block_impl)
{
tree stmt, chain;
tree src_arg;
/* struct c_arg_info * arg_info; */
/* Set up: (struct block *_src) parameter. */
src_arg = build_decl (PARM_DECL, get_identifier ("_src"),
block_impl->block_arg_ptr_type);
DECL_CONTEXT (src_arg) = cur_block->destroy_helper_func_decl;
TREE_USED (src_arg) = 1;
DECL_ARG_TYPE (src_arg) = block_impl->block_arg_ptr_type;
/* arg_info = xcalloc (1, sizeof (struct c_arg_info)); */
pushdecl (cur_block->destroy_helper_func_decl);
/* arg_info->parms = src_arg; */
/* arg_info->types = tree_cons (NULL_TREE, block_impl->block_arg_ptr_type,
NULL_TREE); */
DECL_ARGUMENTS (cur_block->destroy_helper_func_decl) = src_arg;
/* function header synthesis. */
push_function_context ();
/* start_block_helper_function (cur_block->destroy_helper_func_decl, true); */
/* store_parm_decls_from (arg_info); */
start_preparsed_function (cur_block->destroy_helper_func_decl,
/*attrs*/NULL_TREE,
SF_PRE_PARSED);
/* Body of the function. */
stmt = begin_compound_stmt (BCS_FN_BODY);
for (chain = block_impl->block_ref_decl_list; chain;
chain = TREE_CHAIN (chain))
/* APPLE LOCAL begin radar 6214617 */
if (block_requires_copying (TREE_VALUE (chain))
|| (TREE_CODE (TREE_TYPE (TREE_VALUE (chain))) == RECORD_TYPE
&& CLASSTYPE_DESTRUCTORS (TREE_TYPE (TREE_VALUE (chain)))))
/* APPLE LOCAL end radar 6214617 */
{
int flag = 0;
tree rel_exp;
tree p = TREE_VALUE (chain);
tree src_block_component;
src_block_component = build_component_ref (build_indirect_ref (src_arg, "->"),
DECL_NAME (p));
if (TREE_CODE (TREE_TYPE (p)) == BLOCK_POINTER_TYPE)
/* _Block_object_dispose(_src->imported_object_0, BLOCK_FIELD_IS_BLOCK); */
flag = BLOCK_FIELD_IS_BLOCK;
/* APPLE LOCAL begin radar 6214617 */
else if (TREE_CODE (TREE_TYPE (p)) == RECORD_TYPE
&& CLASSTYPE_DESTRUCTORS (TREE_TYPE (p)))
{
tree call_exp = cxx_maybe_build_cleanup (src_block_component);
gcc_assert (call_exp);
add_stmt (call_exp);
}
/* APPLE LOCAL end radar 6214617 */
else
/* _Block_object_dispose(_src->imported_object_0, BLOCK_FIELD_IS_OBJECT); */
flag = BLOCK_FIELD_IS_OBJECT;
if (flag)
{
rel_exp = build_block_object_dispose_call_exp (src_block_component, flag);
add_stmt (rel_exp);
}
}
/* For each __block declared variable used in |...| Must generate call to:
_Block_object_dispose(_src->myImportedClosure, BLOCK_FIELD_IS_BYREF[|BLOCK_FIELD_IS_WEAK])
*/
for (chain = block_impl->block_byref_decl_list; chain;
chain = TREE_CHAIN (chain))
if (COPYABLE_BYREF_LOCAL_VAR (TREE_VALUE (chain)))
{
tree call_exp;
int flag = BLOCK_FIELD_IS_BYREF;
tree p = TREE_VALUE (chain);
tree src_block_component;
src_block_component = build_component_ref (build_indirect_ref (src_arg, "->"),
DECL_NAME (p));
if (COPYABLE_WEAK_BLOCK (p))
flag |= BLOCK_FIELD_IS_WEAK;
/* _Block_object_dispose(_src->myImportedClosure, BLOCK_FIELD_IS_BYREF[|BLOCK_FIELD_IS_WEAK]) */
call_exp = build_block_object_dispose_call_exp (src_block_component, flag);
add_stmt (call_exp);
}
finish_compound_stmt (stmt);
/* APPLE LOCAL radar 6169580 */
finish_function (4);
/* Hum, would be nice if someone else did this for us. */
if (global_bindings_p ())
cgraph_finalize_function (block_impl->destroy_helper_func_decl, false);
pop_function_context ();
}
/* Parse a block-id.
GNU Extension:
block-id:
type-specifier-seq block-declarator
Returns the DECL specified or implied. */
static tree
cp_parser_block_id (cp_parser* parser)
{
cp_decl_specifier_seq type_specifier_seq;
cp_declarator *declarator;
/* Parse the type-specifier-seq. */
cp_parser_type_specifier_seq (parser, /*is_condition=*/false,
&type_specifier_seq);
if (type_specifier_seq.type == error_mark_node)
return error_mark_node;
/* Look for the block-declarator. */
declarator
= cp_parser_declarator (parser, CP_PARSER_DECLARATOR_BLOCK, NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
return grokblockdecl (&type_specifier_seq, declarator);
}
/* Parse a block-literal-expr.
GNU Extension:
block-literal-expr:
^ parameter-declation-clause exception-specification [opt] compound-statement
^ block-id compound-statement
It synthesizes the helper function for later generation and builds
the necessary data to represent the block literal where it is
declared. */
static tree
cp_parser_block_literal_expr (cp_parser* parser)
{
char name [32];
static int global_unique_count;
int unique_count = ++global_unique_count;
tree block_helper_function_decl;
tree expr, type, arglist = NULL_TREE, ftype;
tree self_arg, stmt;
/* struct c_arg_info *args = NULL; */
cp_parameter_declarator *args = NULL;
tree arg_type = void_list_node;
struct block_sema_info *block_impl;
tree tmp;
tree restype;
tree typelist;
tree helper_function_type;
tree block;
/* APPLE LOCAL radar 6185344 */
tree declared_block_return_type = NULL_TREE;
/* APPLE LOCAL radar 6237713 */
tree attributes = NULL_TREE;
/* APPLE LOCAL radar 6169580 */
int context_is_nonstatic_method;
tree raises = NULL_TREE;
cp_lexer_consume_token (parser->lexer); /* eat '^' */
/* APPLE LOCAL begin radar 6237713 */
if (cp_lexer_peek_token (parser->lexer)->keyword == RID_ATTRIBUTE)
attributes = cp_parser_attributes_opt (parser);
/* APPLE LOCAL end radar 6237713 */
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
/* Parse the optional argument list */
cp_lexer_consume_token (parser->lexer);
/* Open the scope to collect parameter decls */
/* push_scope (); */
/* args = c_parser_parms_declarator (parser, true, NULL_TREE); */
/* Parse the parameter-declaration-clause. */
args = cp_parser_parameter_declaration_clause (parser);
cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'");
arg_type = grokparms (args, &arglist);
/* Check for args as it might be NULL due to error. */
if (! args)
{
return error_mark_node;
}
raises = cp_parser_exception_specification_opt (parser);
}
/* APPLE LOCAL begin radar 6185344 */
else if (cp_lexer_next_token_is_not (parser->lexer, CPP_OPEN_BRACE))
{
/* Parse user declared return type. */
tree decl;
/* APPLE LOCAL begin radar 6237713 */
if (attributes)
{
warning (0, "attributes before block type are ignored");
attributes = NULL_TREE;
}
/* APPLE LOCAL end radar 6237713 */
decl = cp_parser_block_id (parser);
if (decl && decl != error_mark_node)
{
arg_type = TYPE_ARG_TYPES (TREE_TYPE (decl));
arglist = DECL_ARGUMENTS (decl);
raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (decl));
declared_block_return_type = TREE_TYPE (TREE_TYPE (decl));
}
}
/* APPLE LOCAL end radar 6185344 */
block = begin_block ();
/* APPLE LOCAL begin radar 6169580 */
context_is_nonstatic_method = (current_function_decl
&& DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl));
/* APPLE LOCAL end radar 6169580 */
/* cur_block->arg_info = NULL; */
/* APPLE LOCAL begin radar 6185344 */
if (declared_block_return_type)
{
cur_block->return_type = TYPE_MAIN_VARIANT (declared_block_return_type);
cur_block->block_has_return_type = true;
}
else
cur_block->return_type = NULL_TREE;
/* APPLE LOCAL end radar 6185344 */
/* Must also build hidden parameter .block_descriptor added to the helper
function, even though we do not know its type yet. */
/* APPLE LOCAL radar 6404979 */
self_arg = build_artificial_parm (get_identifier (".block_descriptor"), ptr_type_node);
/* TREE_CHAIN (self_arg) = cur_block->arg_info->parms; */
TREE_CHAIN (self_arg) = arglist;
arg_type = tree_cons (NULL_TREE, ptr_type_node, arg_type);
arglist = self_arg;
/* APPLE LOCAL begin radar 6185344 */
/* Build the declaration of the helper function (if we do not know its result
type yet, assume it is 'void'. If user provided it, use it).
Treat this as a nested function and use nested function infrastructure for
its generation. */
push_lang_context (lang_name_c);
ftype = build_function_type ((!cur_block->block_has_return_type
? void_type_node : cur_block->return_type),
arg_type);
/* APPLE LOCAL end radar 6185344 */
if (raises)
ftype = build_exception_variant (ftype, raises);
/* APPLE LOCAL radar 6160536 */
block_helper_function_decl = build_helper_func_decl (build_block_helper_name (unique_count),
ftype);
DECL_CONTEXT (block_helper_function_decl) = current_function_decl;
/* LLVM LOCAL begin 6530487 - blocks helper functions never need a static chain */
#ifdef ENABLE_LLVM
DECL_NO_STATIC_CHAIN (block_helper_function_decl) = 1;
#endif
/* LLVM LOCAL end 6530487 - blocks helper functions never need a static chain */
cur_block->helper_func_decl = block_helper_function_decl;
DECL_ARGUMENTS (block_helper_function_decl) = arglist;
push_function_context ();
/* start_block_helper_function (cur_block->helper_func_decl, false); */
/* Enter parameter list to the scope of the helper function. */
/* store_parm_decls_from (cur_block->arg_info); */
start_preparsed_function (cur_block->helper_func_decl,
/*attrs*/NULL_TREE,
SF_PRE_PARSED);
/* APPLE LOCAL begin radar 6237713 */
if (cp_lexer_peek_token (parser->lexer)->keyword == RID_ATTRIBUTE)
attributes = cp_parser_attributes_opt (parser);
/* APPLE LOCAL radar 6246527 */
any_recognized_block_attribute (attributes);
decl_attributes (&cur_block->helper_func_decl, attributes, 0);
/* APPLE LOCAL end radar 6237713 */
/* Start parsing body or expression part of the block literal. */
{
unsigned save = parser->in_statement;
/* Indicate no valid break/continue context. We'll notice and
emit the proper error message in c_finish_bc_stmt. */
parser->in_statement = 0;
stmt = begin_compound_stmt (BCS_FN_BODY);
/* Set block's scope to the scope of the helper function's main body.
This is primarily used when nested blocks are declared. */
cur_block->cp_the_scope = current_binding_level;
/* APPLE LOCAL begin radar 6169580 */
if (context_is_nonstatic_method)
{
tree this_decl = lookup_name (this_identifier);
gcc_assert (this_decl);
build_block_ref_decl (this_identifier, this_decl);
}
/* APPLE LOCAL end radar 6169580 */
cp_parser_compound_statement (parser, NULL, false, false);
parser->in_statement = save;
}
cur_block->block_arg_ptr_type =
build_pointer_type (build_block_struct_type (cur_block));
restype = !cur_block->return_type ? void_type_node
: cur_block->return_type;
if (restype == error_mark_node)
return clean_and_exit (block);
/* Now that we know type of the hidden .block_descriptor argument, fix its type. */
TREE_TYPE (self_arg) = cur_block->block_arg_ptr_type;
DECL_ARG_TYPE (self_arg) = cur_block->block_arg_ptr_type;
/* The DECL_RESULT should already have the correct type by now. */
gcc_assert (TREE_TYPE (DECL_RESULT (current_function_decl))
== restype);
cur_block->block_body = stmt;
block_build_prologue (cur_block);
finish_compound_stmt (stmt);
/* add_stmt (fnbody); */
/* We are done parsing of the block body. Return type of block is now known.
We also know all we need to know about the helper function. So, fix its
type here. */
/* We moved this here because for global blocks, helper function body is
not nested and is gimplified in call to finish_function() and return type
of the function must be correct. */
ftype = build_function_type (restype, TREE_CHAIN (arg_type));
if (raises)
ftype = build_exception_variant (ftype, raises);
/* Declare helper function; as in:
double helper_1(struct block_1 *ii, int z); */
typelist = TYPE_ARG_TYPES (ftype);
/* (struct block_1 *ii, int z, ...) */
typelist = tree_cons (NULL_TREE, cur_block->block_arg_ptr_type,
typelist);
helper_function_type = build_function_type (TREE_TYPE (ftype), typelist);
if (raises)
helper_function_type = build_exception_variant (helper_function_type, raises);
TREE_TYPE (cur_block->helper_func_decl) = helper_function_type;
finish_function (4);
pop_function_context ();
/* Hum, would be nice if someone else did this for us. */
if (global_bindings_p ())
cgraph_finalize_function (cur_block->helper_func_decl, false);
pop_lang_context ();
/* Build the declaration for copy_helper_block and destroy_helper_block
helper functions for later use. */
if (cur_block->BlockHasCopyDispose)
{
tree s_ftype;
push_lang_context (lang_name_c);
/* void copy_helper_block (struct block*, struct block *); */
s_ftype = build_function_type (void_type_node,
tree_cons (NULL_TREE, cur_block->block_arg_ptr_type,
tree_cons (NULL_TREE,
cur_block->block_arg_ptr_type,
void_list_node)));
sprintf (name, "__copy_helper_block_%d", unique_count);
cur_block->copy_helper_func_decl =
build_helper_func_decl (get_identifier (name), s_ftype);
DECL_CONTEXT (cur_block->copy_helper_func_decl) = current_function_decl;
synth_copy_helper_block_func (cur_block);
/* LLVM LOCAL begin Copy helper function should not have source
location. */
DECL_SOURCE_FILE (cur_block->copy_helper_func_decl) = NULL;
DECL_SOURCE_LINE (cur_block->copy_helper_func_decl) = 0;
/* LLVM LOCAL end Copy helper function should not have source
location. */
/* void destroy_helper_block (struct block*); */
s_ftype = build_function_type (void_type_node,
tree_cons (NULL_TREE,
cur_block->block_arg_ptr_type, void_list_node));
sprintf (name, "__destroy_helper_block_%d", unique_count);
cur_block->destroy_helper_func_decl =
build_helper_func_decl (get_identifier (name), s_ftype);
DECL_CONTEXT (cur_block->destroy_helper_func_decl) = current_function_decl;
synth_destroy_helper_block_func (cur_block);
/* LLVM LOCAL begin Destroy helper function should not have source
location. */
DECL_SOURCE_FILE (cur_block->destroy_helper_func_decl) = NULL;
DECL_SOURCE_LINE (cur_block->destroy_helper_func_decl) = 0;
/* LLVM LOCAL end Destroy helper function should not have source
location. */
pop_lang_context ();
}
block_impl = finish_block (block);
/* Build unqiue name of the temporary used in code gen. */
sprintf (name, "__block_holder_tmp_%d", unique_count);
tmp = build_block_literal_tmp (name, block_impl);
tmp = build_fold_addr_expr (tmp);
type = build_block_pointer_type (ftype);
expr = convert (type, convert (ptr_type_node, tmp));
free (block_impl);
return expr;
}
/* APPLE LOCAL end blocks 6040305 (ce) */
/* APPLE LOCAL begin blocks 6040305 (ch) */
/* build_byref_local_var_access - converts EXPR to:
EXPR.__forwarding-><decl-name>.
*/
tree
build_byref_local_var_access (tree expr, tree decl_name)
{
tree exp = build_component_ref (expr, get_identifier ("__forwarding"));
exp = build_indirect_ref (exp, "unary *");
exp = build_component_ref (exp, decl_name);
return exp;
}
#define BINDING_VALUE(b) ((b)->value)
/**
build_block_byref_decl - This routine inserts a variable declared as a
'byref' variable using the |...| syntax in helper function's outer-most scope.
*/
tree
build_block_byref_decl (tree name, tree decl, tree exp)
{
tree ptr_type, byref_decl;
/* APPLE LOCAL begin radar 6225809 */
if (cur_block->prev_block_info) {
/* Traverse enclosing blocks. Insert a __block variable in
each enclosing block which has no declaration of this
variable. This is to ensure that the current (inner) block
gets the __block version of the variable; */
struct block_sema_info *cb = cur_block->prev_block_info;
while (cb) {
struct cxx_binding *b = I_SYMBOL_BINDING (name);
gcc_assert (b);
gcc_assert (BINDING_VALUE (b));
gcc_assert (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL);
/* Find the first declaration not in current block. */
while (b && BINDING_VALUE (b)
&& (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL)
&& DECL_CONTEXT (BINDING_VALUE (b)) == cur_block->helper_func_decl)
{
/* FIXME: This can't happen?! */
abort ();
/* b = b->previous; */
}
gcc_assert (b);
gcc_assert (BINDING_VALUE (b));
gcc_assert (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL);
/* Is the next declaration not in the enclosing block? */
if (b && BINDING_VALUE (b)
&& (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL)
&& DECL_CONTEXT (BINDING_VALUE (b)) != cb->helper_func_decl)
{
/* No declaration of variable seen in the block. Must insert one. */
/* FIXME: does this push enough? scope? */
struct cp_binding_level *save_scope = current_binding_level;
struct block_sema_info *save_current_block = cur_block;
tree save_current_function_decl = current_function_decl;
current_binding_level = cb->cp_the_scope;
cur_block = cb;
current_function_decl = cb->helper_func_decl;
decl = build_block_byref_decl (name, decl, exp);
cur_block = save_current_block;
current_binding_level = save_scope;
current_function_decl = save_current_function_decl;
}
cb = cb->prev_block_info;
}
}
/* APPLE LOCAL end radar 6225809 */
/* If it is already a byref declaration, do not add the pointer type
because such declarations already have the pointer type
added. This happens when we have two nested byref declarations in
nested blocks. */
ptr_type = (TREE_CODE (decl) == VAR_DECL && BLOCK_DECL_BYREF (decl))
? TREE_TYPE (decl) : build_pointer_type (TREE_TYPE (decl));
byref_decl = build_decl (VAR_DECL, name, ptr_type);
DECL_CONTEXT (byref_decl) = current_function_decl;
BLOCK_DECL_BYREF (byref_decl) = 1;
if (TREE_CODE (decl) == VAR_DECL && COPYABLE_BYREF_LOCAL_VAR (decl))
{
COPYABLE_BYREF_LOCAL_VAR (byref_decl) = 1;
COPYABLE_BYREF_LOCAL_NONPOD (byref_decl) = COPYABLE_BYREF_LOCAL_NONPOD (decl);
/* APPLE LOCAL radar 5847976 */
COPYABLE_WEAK_BLOCK (byref_decl) = COPYABLE_WEAK_BLOCK (decl);
}
/* Current scope must be that of the main function body. */
/* FIXME gcc_assert (current_scope->function_body);*/
/* LLVM LOCAL begin 7387470 */
/* Find the scope for function body (outer-most scope) and insert
this variable in that scope. This is to avoid duplicate
declaration of the save variable. */
{
struct cp_binding_level *b = current_binding_level;
while (b->level_chain->kind != sk_function_parms)
b = b->level_chain;
pushdecl_with_scope (byref_decl, b, /*is_friend=*/false);
}
/* LLVM LOCAL end 7387470 */
mark_used (byref_decl);
/* APPLE LOCAL begin radar 6083129 - byref escapes (cp) */
/* FIXME: finish this off, ensure the decl is scoped appropriately
for when we want the cleanup to run. */
if (! flag_objc_gc_only)
push_cleanup (byref_decl, build_block_byref_release_exp (byref_decl), false);
/* APPLE LOCAL end radar 6083129 - byref escapes (cp) */
cur_block->block_byref_decl_list =
tree_cons (NULL_TREE, byref_decl, cur_block->block_byref_decl_list);
/* APPLE LOCAL radar 5847213 */
/* build of block_original_byref_decl_list us removed. */
/* APPLE LOCAL begin radar 6144664 */
DECL_SOURCE_LOCATION (byref_decl)
= DECL_SOURCE_LOCATION (cur_block->helper_func_decl);
/* APPLE LOCAL end radar 6144664 */
return byref_decl;
}
/**
build_block_ref_decl - This routine inserts a copied-in variable (a variable
referenced in the block but whose scope is outside the block) in helper
function's outer-most scope. It also sets its type to 'const' as such
variables are read-only.
*/
tree
build_block_ref_decl (tree name, tree decl)
{
/* FIXME - Broken, should be found via objc runtime testcases. */
/* FIXME - Don't use DECL_CONTEXT on any helpers */
tree ref_decl;
/* APPLE LOCAL radar 6212722 */
tree type, exp;
/* 'decl' was previously declared as __block. Simply, copy the value
embedded in the above variable. */
if (TREE_CODE (decl) == VAR_DECL && COPYABLE_BYREF_LOCAL_VAR (decl))
decl = build_byref_local_var_access (decl, DECL_NAME (decl));
else {
if (cur_block->prev_block_info) {
/* Traverse enclosing blocks. Insert a copied-in variable in
each enclosing block which has no declaration of this
variable. This is to ensure that the current (inner) block
has the 'frozen' value of the copied-in variable; which means
the value of the copied in variable is at the point of the
block declaration and *not* when the inner block is
invoked. */
struct block_sema_info *cb = cur_block->prev_block_info;
while (cb) {
struct cxx_binding *b = I_SYMBOL_BINDING (name);
gcc_assert (b);
gcc_assert (BINDING_VALUE (b));
gcc_assert (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL);
/* Find the first declaration not in current block. */
while (b && BINDING_VALUE (b)
&& (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL)
&& DECL_CONTEXT (BINDING_VALUE (b)) == cur_block->helper_func_decl)
{
/* FIXME: This can't happen?! */
abort ();
/* b = b->previous; */
}
gcc_assert (b);
gcc_assert (BINDING_VALUE (b));
gcc_assert (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL);
/* Is the next declaration not in the enclosing block? */
if (b && BINDING_VALUE (b)
&& (TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
|| TREE_CODE (BINDING_VALUE (b)) == PARM_DECL)
&& DECL_CONTEXT (BINDING_VALUE (b)) != cb->helper_func_decl)
{
/* No declaration of variable seen in the block. Must
insert one, so it 'freezes' the variable in this
block. */
/* FIXME: does this push enough? scope? */
struct cp_binding_level *save_scope = current_binding_level;
struct block_sema_info *save_current_block = cur_block;
tree save_current_function_decl = current_function_decl;
current_binding_level = cb->cp_the_scope;
cur_block = cb;
current_function_decl = cb->helper_func_decl;
decl = build_block_ref_decl (name, decl);
cur_block = save_current_block;
current_binding_level = save_scope;
current_function_decl = save_current_function_decl;
}
cb = cb->prev_block_info;
}
}
}
/* APPLE LOCAL begin radar 6212722 */
exp = decl;
type = TREE_TYPE (exp);
if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == FUNCTION_TYPE) {
exp = decay_conversion (exp);
type = TREE_TYPE (exp);
}
ref_decl = build_decl (VAR_DECL, name,
build_qualified_type (type, TYPE_QUAL_CONST));
/* APPLE LOCAL end radar 6212722 */
/* APPLE LOCAL begin radar 6144664 */
DECL_SOURCE_LOCATION (ref_decl) = DECL_SOURCE_LOCATION
(cur_block->helper_func_decl);
/* APPLE LOCAL end radar 6144664 */
DECL_CONTEXT (ref_decl) = current_function_decl;
DECL_INITIAL (ref_decl) = error_mark_node;
c_apply_type_quals_to_decl (TYPE_QUAL_CONST, ref_decl);
BLOCK_DECL_COPIED (ref_decl) = 1;
/* Find the scope for function body (outer-most scope) and insert
this variable in that scope. This is to avoid duplicate
declaration of the save variable. */
{
struct cp_binding_level *b = current_binding_level;
while (b->level_chain->kind != sk_function_parms)
b = b->level_chain;
pushdecl_with_scope (ref_decl, b, /*is_friend=*/false);
/* APPLE LOCAL radar 6169527 */
add_decl_expr (ref_decl);
}
cur_block->block_ref_decl_list =
tree_cons (NULL_TREE, ref_decl, cur_block->block_ref_decl_list);
cur_block->block_original_ref_decl_list =
/* APPLE LOCAL radar 6212722 */
tree_cons (NULL_TREE, exp, cur_block->block_original_ref_decl_list);
return ref_decl;
}
/* APPLE LOCAL begin radar 5847213 - radar 6329245 */
static GTY (()) tree descriptor_ptr_type;
static GTY (()) tree descriptor_ptr_type_with_copydispose;
/** build_block_descriptor_type - This routine builds following internal type:
struct __block_descriptor {
unsigned long int reserved; // NULL
unsigned long int Size; // sizeof(struct Block_literal_1)
// optional helper functions
void *CopyFuncPtr; // When BLOCK_HAS_COPY_DISPOSE is set (withCopyDispose true)
void *DestroyFuncPtr; // When BLOCK_HAS_COPY_DISPOSE is set (withCopyDispose true)
// APPLE LOCAL begin radar 8143947
const char *signature; // the block signature
const char *layout; // reserved
// APPLE LOCAL end radar 8143947
} *descriptor_ptr_type;
Objects of this type will always be static. This is one main component of abi change.
*/
tree
build_block_descriptor_type (bool withCopyDispose)
{
tree field_decl_chain = NULL_TREE, field_decl;
tree main_type;
if (withCopyDispose && descriptor_ptr_type_with_copydispose)
return descriptor_ptr_type_with_copydispose;
if (!withCopyDispose && descriptor_ptr_type)
return descriptor_ptr_type;
main_type = make_aggr_type (RECORD_TYPE);
xref_basetypes (main_type, NULL_TREE);
/* unsigned long int reserved; */
field_decl = build_decl (FIELD_DECL, get_identifier ("reserved"), long_unsigned_type_node);
TREE_CHAIN (field_decl) = field_decl_chain;
field_decl_chain = field_decl;
/* unsigned long int Size; */
field_decl = build_decl (FIELD_DECL, get_identifier ("Size"), long_unsigned_type_node);
TREE_CHAIN (field_decl) = field_decl_chain;
field_decl_chain = field_decl;
if (withCopyDispose)
{
/* void *CopyFuncPtr; */
field_decl = build_decl (FIELD_DECL, get_identifier ("CopyFuncPtr"), ptr_type_node);
TREE_CHAIN (field_decl) = field_decl_chain;
field_decl_chain = field_decl;
/* void *DestroyFuncPtr; */
field_decl = build_decl (FIELD_DECL, get_identifier ("DestroyFuncPtr"), ptr_type_node);
TREE_CHAIN (field_decl) = field_decl_chain;
field_decl_chain = field_decl;
}
/* APPLE LOCAL begin radar 8143947 */
/* char * signature */
field_decl = build_decl (FIELD_DECL, get_identifier ("signature"), build_pointer_type (char_type_node));
TREE_CHAIN (field_decl) = field_decl_chain;
field_decl_chain = field_decl;
/* char * layout */
field_decl = build_decl (FIELD_DECL, get_identifier ("layout"), build_pointer_type (char_type_node));
TREE_CHAIN (field_decl) = field_decl_chain;
field_decl_chain = field_decl;
/* APPLE LOCAL end radar 8143947 */
/* Mark this struct as being a block struct rather than a 'normal'
struct. */
TYPE_BLOCK_IMPL_STRUCT (main_type) = 1;
if (withCopyDispose)
finish_builtin_struct (main_type, "__block_descriptor_withcopydispose", field_decl_chain, NULL_TREE);
else
finish_builtin_struct (main_type, "__block_descriptor", field_decl_chain, NULL_TREE);
CLASSTYPE_AS_BASE (main_type) = main_type;
main_type = build_pointer_type (main_type);
if (withCopyDispose)
descriptor_ptr_type_with_copydispose = main_type;
else
descriptor_ptr_type = main_type;
return main_type;
}
/* APPLE LOCAL end radar 5847213 - radar 6329245 */
cp_declarator *
make_block_pointer_declarator (tree attributes,
cp_cv_quals quals,
cp_declarator *target)
{
struct cp_declarator *itarget = target;
struct cp_declarator *ret = make_declarator (cdk_block_pointer);
/* APPLE LOCAL radar 5847213 */
/* code removed */
ret->attributes = attributes;
ret->declarator = itarget;
ret->u.block_pointer.qualifiers = quals;
return ret;
}
/* This routine returns 'true' if 'name' has a declaration inside the
current block, 'false' otherwise. If 'name' has no declaration in
the current block, it returns in DECL the user declaration for
'name' found in the enclosing scope. Note that if it is declared
in current declaration, it can be either a user declaration or a
byref/copied-in declaration added in current block's scope by the
compiler. */
bool
lookup_name_in_block (tree name, tree *decl)
{
/* FIXME - Broken, should be found via objc runtime testcases. */
/* FIXME - Don't use DECL_CONTEXT on any helpers */
cxx_binding *b = I_SYMBOL_BINDING (name);
if (b && b->declared_in_block
&& DECL_CONTEXT (BINDING_VALUE (b)) == current_function_decl)
return true;
/* Check for variables only, as we may have parameters, such as
'self' */
/* Note that if a copied-in variable (BLOCK_DECL_COPIED) in the
enclosing block is found, it must be returned as this is
where the variable in current (nested block) will have to get
its value. */
while (b
&& TREE_CODE (BINDING_VALUE (b)) == VAR_DECL
&& (BLOCK_DECL_BYREF (BINDING_VALUE (b))))
b = b->previous;
if (b)
*decl = BINDING_VALUE (b);
return false;
}
/**
build_helper_func_decl - This routine builds a FUNCTION_DECL for
a block helper function.
*/
tree
build_helper_func_decl (tree ident, tree type)
{
tree func_decl = build_decl (FUNCTION_DECL, ident, type);
DECL_EXTERNAL (func_decl) = 0;
TREE_PUBLIC (func_decl) = 0;
TREE_USED (func_decl) = 1;
TREE_NOTHROW (func_decl) = 0;
/* APPLE LOCAL radar 6172148 */
BLOCK_SYNTHESIZED_FUNC (func_decl) = 1;
retrofit_lang_decl (func_decl);
if (current_function_decl)
DECL_NO_STATIC_CHAIN (current_function_decl) = 0;
return func_decl;
}
/**
declare_block_prologue_local_vars - utility routine to do the actual
declaration and initialization for each referecned block variable.
*/
/* APPLE LOCAL begin radar 6169527 */
/* This routine is mostly rewritten for c++ because initialization of variables
may involve copy construction. */
static void
declare_block_prologue_local_vars (tree self_parm, tree component,
tree stmt)
{
tree decl, block_component;
tree_stmt_iterator i;
tree initialization_stmt;
/* APPLE LOCAL radar 6163705 */
int save_line = LOCATION_LINE (input_location);
decl = component;
block_component = build_component_ref (build_indirect_ref (self_parm, "->"),
DECL_NAME (component));
gcc_assert (block_component);
/* APPLE LOCAL radar 6163705 */
LOCATION_LINE (input_location) = DECL_SOURCE_LINE (decl) - 1;
DECL_EXTERNAL (decl) = 0;
TREE_STATIC (decl) = 0;
TREE_USED (decl) = 1;
DECL_CONTEXT (decl) = current_function_decl;
DECL_ARTIFICIAL (decl) = 1;
initialization_stmt = push_stmt_list();
cp_finish_decl (decl, block_component, 0, 0, LOOKUP_ONLYCONVERTING);
initialization_stmt = pop_stmt_list (initialization_stmt);
/* APPLE LOCAL radar 6163705 */
LOCATION_LINE (input_location) = save_line;
/* Prepend a initialization_stmt statement to the statement list. */
i = tsi_start (stmt);
tsi_link_before (&i, initialization_stmt, TSI_SAME_STMT);
}
/**
declare_block_prologue_local_byref_vars - utility routine to do the actual
declaration and initialization for each __block referenced block variable.
*/
static void
declare_block_prologue_local_byref_vars (tree self_parm, tree component,
tree stmt)
{
tree decl, block_component;
tree_stmt_iterator i;
tree decl_stmt;
decl = component;
block_component = build_component_ref (build_indirect_ref (self_parm, "->"),
DECL_NAME (component));
gcc_assert (block_component);
DECL_EXTERNAL (decl) = 0;
TREE_STATIC (decl) = 0;
TREE_USED (decl) = 1;
DECL_CONTEXT (decl) = current_function_decl;
DECL_ARTIFICIAL (decl) = 1;
DECL_INITIAL (decl) = block_component;
/* Prepend a DECL_EXPR statement to the statement list. */
i = tsi_start (stmt);
decl_stmt = build_stmt (DECL_EXPR, decl);
SET_EXPR_LOCATION (decl_stmt, DECL_SOURCE_LOCATION (decl));
/* APPLE LOCAL begin radar 6163705, Blocks prologues */
/* Give the prologue statements a line number of one before the beginning of
the function, to make them easily identifiable later. */
EXPR_LINENO (decl_stmt) = DECL_SOURCE_LINE (decl) - 1;
/* APPLE LOCAL end radar 6163705, Blocks prologues */
decl_stmt = build3 (BIND_EXPR, void_type_node, decl, decl_stmt, NULL);
TREE_SIDE_EFFECTS (decl_stmt) = 1;
tsi_link_before (&i, decl_stmt, TSI_SAME_STMT);
}
/* APPLE LOCAL end radar 6169527 */
/**
block_build_prologue
- This routine builds the declarations for the
variables referenced in the block; as in:
int *y = .block_descriptor->y;
int x = .block_descriptor->x;
The decl_expr declaration for each initialization is enterred at the
beginning of the helper function's statement-list which is passed
in block_impl->block_body.
*/
void
block_build_prologue (struct block_sema_info *block_impl)
{
tree chain;
tree self_parm = lookup_name (get_identifier (".block_descriptor"));
gcc_assert (self_parm);
for (chain = block_impl->block_ref_decl_list; chain;
chain = TREE_CHAIN (chain))
declare_block_prologue_local_vars (self_parm, TREE_VALUE (chain),
block_impl->block_body);
/* APPLE LOCAL begin radar 6169527 */
for (chain = block_impl->block_byref_decl_list; chain;
chain = TREE_CHAIN (chain))
declare_block_prologue_local_byref_vars (self_parm, TREE_VALUE (chain),
block_impl->block_body);
/* APPLE LOCAL end radar 6169527 */
}
/* APPLE LOCAL end blocks 6040305 (ch) */
/* OpenMP 2.5 parsing routines. */
/* All OpenMP clauses. OpenMP 2.5. */
typedef enum pragma_omp_clause {
PRAGMA_OMP_CLAUSE_NONE = 0,
PRAGMA_OMP_CLAUSE_COPYIN,
PRAGMA_OMP_CLAUSE_COPYPRIVATE,
PRAGMA_OMP_CLAUSE_DEFAULT,
PRAGMA_OMP_CLAUSE_FIRSTPRIVATE,
PRAGMA_OMP_CLAUSE_IF,
PRAGMA_OMP_CLAUSE_LASTPRIVATE,
PRAGMA_OMP_CLAUSE_NOWAIT,
PRAGMA_OMP_CLAUSE_NUM_THREADS,
PRAGMA_OMP_CLAUSE_ORDERED,
PRAGMA_OMP_CLAUSE_PRIVATE,
PRAGMA_OMP_CLAUSE_REDUCTION,
PRAGMA_OMP_CLAUSE_SCHEDULE,
PRAGMA_OMP_CLAUSE_SHARED
} pragma_omp_clause;
/* Returns name of the next clause.
If the clause is not recognized PRAGMA_OMP_CLAUSE_NONE is returned and
the token is not consumed. Otherwise appropriate pragma_omp_clause is
returned and the token is consumed. */
static pragma_omp_clause
cp_parser_omp_clause_name (cp_parser *parser)
{
pragma_omp_clause result = PRAGMA_OMP_CLAUSE_NONE;
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_IF))
result = PRAGMA_OMP_CLAUSE_IF;
else if (cp_lexer_next_token_is_keyword (parser->lexer, RID_DEFAULT))
result = PRAGMA_OMP_CLAUSE_DEFAULT;
else if (cp_lexer_next_token_is_keyword (parser->lexer, RID_PRIVATE))
result = PRAGMA_OMP_CLAUSE_PRIVATE;
else if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
{
tree id = cp_lexer_peek_token (parser->lexer)->u.value;
const char *p = IDENTIFIER_POINTER (id);
switch (p[0])
{
case 'c':
if (!strcmp ("copyin", p))
result = PRAGMA_OMP_CLAUSE_COPYIN;
else if (!strcmp ("copyprivate", p))
result = PRAGMA_OMP_CLAUSE_COPYPRIVATE;
break;
case 'f':
if (!strcmp ("firstprivate", p))
result = PRAGMA_OMP_CLAUSE_FIRSTPRIVATE;
break;
case 'l':
if (!strcmp ("lastprivate", p))
result = PRAGMA_OMP_CLAUSE_LASTPRIVATE;
break;
case 'n':
if (!strcmp ("nowait", p))
result = PRAGMA_OMP_CLAUSE_NOWAIT;
else if (!strcmp ("num_threads", p))
result = PRAGMA_OMP_CLAUSE_NUM_THREADS;
break;
case 'o':
if (!strcmp ("ordered", p))
result = PRAGMA_OMP_CLAUSE_ORDERED;
break;
case 'r':
if (!strcmp ("reduction", p))
result = PRAGMA_OMP_CLAUSE_REDUCTION;
break;
case 's':
if (!strcmp ("schedule", p))
result = PRAGMA_OMP_CLAUSE_SCHEDULE;
else if (!strcmp ("shared", p))
result = PRAGMA_OMP_CLAUSE_SHARED;
break;
}
}
if (result != PRAGMA_OMP_CLAUSE_NONE)
cp_lexer_consume_token (parser->lexer);
return result;
}
/* Validate that a clause of the given type does not already exist. */
static void
check_no_duplicate_clause (tree clauses, enum tree_code code, const char *name)
{
tree c;
for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c))
if (OMP_CLAUSE_CODE (c) == code)
{
error ("too many %qs clauses", name);
break;
}
}
/* OpenMP 2.5:
variable-list:
identifier
variable-list , identifier
In addition, we match a closing parenthesis. An opening parenthesis
will have been consumed by the caller.
If KIND is nonzero, create the appropriate node and install the decl
in OMP_CLAUSE_DECL and add the node to the head of the list.
If KIND is zero, create a TREE_LIST with the decl in TREE_PURPOSE;
return the list created. */
static tree
cp_parser_omp_var_list_no_open (cp_parser *parser, enum omp_clause_code kind,
tree list)
{
while (1)
{
tree name, decl;
name = cp_parser_id_expression (parser, /*template_p=*/false,
/*check_dependency_p=*/true,
/*template_p=*/NULL,
/*declarator_p=*/false,
/*optional_p=*/false);
if (name == error_mark_node)
goto skip_comma;
decl = cp_parser_lookup_name_simple (parser, name);
if (decl == error_mark_node)
cp_parser_name_lookup_error (parser, name, decl, NULL);
else if (kind != 0)
{
tree u = build_omp_clause (kind);
OMP_CLAUSE_DECL (u) = decl;
OMP_CLAUSE_CHAIN (u) = list;
list = u;
}
else
list = tree_cons (decl, NULL_TREE, list);
get_comma:
if (cp_lexer_next_token_is_not (parser->lexer, CPP_COMMA))
break;
cp_lexer_consume_token (parser->lexer);
}
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
{
int ending;
/* Try to resync to an unnested comma. Copied from
cp_parser_parenthesized_expression_list. */
skip_comma:
ending = cp_parser_skip_to_closing_parenthesis (parser,
/*recovering=*/true,
/*or_comma=*/true,
/*consume_paren=*/true);
if (ending < 0)
goto get_comma;
}
return list;
}
/* Similarly, but expect leading and trailing parenthesis. This is a very
common case for omp clauses. */
static tree
cp_parser_omp_var_list (cp_parser *parser, enum omp_clause_code kind, tree list)
{
if (cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return cp_parser_omp_var_list_no_open (parser, kind, list);
return list;
}
/* OpenMP 2.5:
default ( shared | none ) */
static tree
cp_parser_omp_clause_default (cp_parser *parser, tree list)
{
enum omp_clause_default_kind kind = OMP_CLAUSE_DEFAULT_UNSPECIFIED;
tree c;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return list;
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
{
tree id = cp_lexer_peek_token (parser->lexer)->u.value;
const char *p = IDENTIFIER_POINTER (id);
switch (p[0])
{
case 'n':
if (strcmp ("none", p) != 0)
goto invalid_kind;
kind = OMP_CLAUSE_DEFAULT_NONE;
break;
case 's':
if (strcmp ("shared", p) != 0)
goto invalid_kind;
kind = OMP_CLAUSE_DEFAULT_SHARED;
break;
default:
goto invalid_kind;
}
cp_lexer_consume_token (parser->lexer);
}
else
{
invalid_kind:
cp_parser_error (parser, "expected %<none%> or %<shared%>");
}
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
if (kind == OMP_CLAUSE_DEFAULT_UNSPECIFIED)
return list;
check_no_duplicate_clause (list, OMP_CLAUSE_DEFAULT, "default");
c = build_omp_clause (OMP_CLAUSE_DEFAULT);
OMP_CLAUSE_CHAIN (c) = list;
OMP_CLAUSE_DEFAULT_KIND (c) = kind;
return c;
}
/* OpenMP 2.5:
if ( expression ) */
static tree
cp_parser_omp_clause_if (cp_parser *parser, tree list)
{
tree t, c;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return list;
t = cp_parser_condition (parser);
if (t == error_mark_node
|| !cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
check_no_duplicate_clause (list, OMP_CLAUSE_IF, "if");
c = build_omp_clause (OMP_CLAUSE_IF);
OMP_CLAUSE_IF_EXPR (c) = t;
OMP_CLAUSE_CHAIN (c) = list;
return c;
}
/* OpenMP 2.5:
nowait */
static tree
cp_parser_omp_clause_nowait (cp_parser *parser ATTRIBUTE_UNUSED, tree list)
{
tree c;
check_no_duplicate_clause (list, OMP_CLAUSE_NOWAIT, "nowait");
c = build_omp_clause (OMP_CLAUSE_NOWAIT);
OMP_CLAUSE_CHAIN (c) = list;
return c;
}
/* OpenMP 2.5:
num_threads ( expression ) */
static tree
cp_parser_omp_clause_num_threads (cp_parser *parser, tree list)
{
tree t, c;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return list;
t = cp_parser_expression (parser, false);
if (t == error_mark_node
|| !cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
check_no_duplicate_clause (list, OMP_CLAUSE_NUM_THREADS, "num_threads");
c = build_omp_clause (OMP_CLAUSE_NUM_THREADS);
OMP_CLAUSE_NUM_THREADS_EXPR (c) = t;
OMP_CLAUSE_CHAIN (c) = list;
return c;
}
/* OpenMP 2.5:
ordered */
static tree
cp_parser_omp_clause_ordered (cp_parser *parser ATTRIBUTE_UNUSED, tree list)
{
tree c;
check_no_duplicate_clause (list, OMP_CLAUSE_ORDERED, "ordered");
c = build_omp_clause (OMP_CLAUSE_ORDERED);
OMP_CLAUSE_CHAIN (c) = list;
return c;
}
/* OpenMP 2.5:
reduction ( reduction-operator : variable-list )
reduction-operator:
One of: + * - & ^ | && || */
static tree
cp_parser_omp_clause_reduction (cp_parser *parser, tree list)
{
enum tree_code code;
tree nlist, c;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return list;
switch (cp_lexer_peek_token (parser->lexer)->type)
{
case CPP_PLUS:
code = PLUS_EXPR;
break;
case CPP_MULT:
code = MULT_EXPR;
break;
case CPP_MINUS:
code = MINUS_EXPR;
break;
case CPP_AND:
code = BIT_AND_EXPR;
break;
case CPP_XOR:
code = BIT_XOR_EXPR;
break;
case CPP_OR:
code = BIT_IOR_EXPR;
break;
case CPP_AND_AND:
code = TRUTH_ANDIF_EXPR;
break;
case CPP_OR_OR:
code = TRUTH_ORIF_EXPR;
break;
default:
cp_parser_error (parser, "`+', `*', `-', `&', `^', `|', `&&', or `||'");
resync_fail:
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
return list;
}
cp_lexer_consume_token (parser->lexer);
if (!cp_parser_require (parser, CPP_COLON, "`:'"))
goto resync_fail;
nlist = cp_parser_omp_var_list_no_open (parser, OMP_CLAUSE_REDUCTION, list);
for (c = nlist; c != list; c = OMP_CLAUSE_CHAIN (c))
OMP_CLAUSE_REDUCTION_CODE (c) = code;
return nlist;
}
/* OpenMP 2.5:
schedule ( schedule-kind )
schedule ( schedule-kind , expression )
schedule-kind:
static | dynamic | guided | runtime */
static tree
cp_parser_omp_clause_schedule (cp_parser *parser, tree list)
{
tree c, t;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>"))
return list;
c = build_omp_clause (OMP_CLAUSE_SCHEDULE);
if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
{
tree id = cp_lexer_peek_token (parser->lexer)->u.value;
const char *p = IDENTIFIER_POINTER (id);
switch (p[0])
{
case 'd':
if (strcmp ("dynamic", p) != 0)
goto invalid_kind;
OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_DYNAMIC;
break;
case 'g':
if (strcmp ("guided", p) != 0)
goto invalid_kind;
OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_GUIDED;
break;
case 'r':
if (strcmp ("runtime", p) != 0)
goto invalid_kind;
OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_RUNTIME;
break;
default:
goto invalid_kind;
}
}
else if (cp_lexer_next_token_is_keyword (parser->lexer, RID_STATIC))
OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_STATIC;
else
goto invalid_kind;
cp_lexer_consume_token (parser->lexer);
if (cp_lexer_next_token_is (parser->lexer, CPP_COMMA))
{
cp_lexer_consume_token (parser->lexer);
t = cp_parser_assignment_expression (parser, false);
if (t == error_mark_node)
goto resync_fail;
else if (OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_RUNTIME)
error ("schedule %<runtime%> does not take "
"a %<chunk_size%> parameter");
else
OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c) = t;
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
goto resync_fail;
}
else if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`,' or `)'"))
goto resync_fail;
check_no_duplicate_clause (list, OMP_CLAUSE_SCHEDULE, "schedule");
OMP_CLAUSE_CHAIN (c) = list;
return c;
invalid_kind:
cp_parser_error (parser, "invalid schedule kind");
resync_fail:
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
return list;
}
/* Parse all OpenMP clauses. The set clauses allowed by the directive
is a bitmask in MASK. Return the list of clauses found; the result
of clause default goes in *pdefault. */
static tree
cp_parser_omp_all_clauses (cp_parser *parser, unsigned int mask,
const char *where, cp_token *pragma_tok)
{
tree clauses = NULL;
while (cp_lexer_next_token_is_not (parser->lexer, CPP_PRAGMA_EOL))
{
pragma_omp_clause c_kind = cp_parser_omp_clause_name (parser);
const char *c_name;
tree prev = clauses;
switch (c_kind)
{
case PRAGMA_OMP_CLAUSE_COPYIN:
clauses = cp_parser_omp_var_list (parser, OMP_CLAUSE_COPYIN, clauses);
c_name = "copyin";
break;
case PRAGMA_OMP_CLAUSE_COPYPRIVATE:
clauses = cp_parser_omp_var_list (parser, OMP_CLAUSE_COPYPRIVATE,
clauses);
c_name = "copyprivate";
break;
case PRAGMA_OMP_CLAUSE_DEFAULT:
clauses = cp_parser_omp_clause_default (parser, clauses);
c_name = "default";
break;
case PRAGMA_OMP_CLAUSE_FIRSTPRIVATE:
clauses = cp_parser_omp_var_list (parser, OMP_CLAUSE_FIRSTPRIVATE,
clauses);
c_name = "firstprivate";
break;
case PRAGMA_OMP_CLAUSE_IF:
clauses = cp_parser_omp_clause_if (parser, clauses);
c_name = "if";
break;
case PRAGMA_OMP_CLAUSE_LASTPRIVATE:
clauses = cp_parser_omp_var_list (parser, OMP_CLAUSE_LASTPRIVATE,
clauses);
c_name = "lastprivate";
break;
case PRAGMA_OMP_CLAUSE_NOWAIT:
clauses = cp_parser_omp_clause_nowait (parser, clauses);
c_name = "nowait";
break;
case PRAGMA_OMP_CLAUSE_NUM_THREADS:
clauses = cp_parser_omp_clause_num_threads (parser, clauses);
c_name = "num_threads";
break;
case PRAGMA_OMP_CLAUSE_ORDERED:
clauses = cp_parser_omp_clause_ordered (parser, clauses);
c_name = "ordered";
break;
case PRAGMA_OMP_CLAUSE_PRIVATE:
clauses = cp_parser_omp_var_list (parser, OMP_CLAUSE_PRIVATE,
clauses);
c_name = "private";
break;
case PRAGMA_OMP_CLAUSE_REDUCTION:
clauses = cp_parser_omp_clause_reduction (parser, clauses);
c_name = "reduction";
break;
case PRAGMA_OMP_CLAUSE_SCHEDULE:
clauses = cp_parser_omp_clause_schedule (parser, clauses);
c_name = "schedule";
break;
case PRAGMA_OMP_CLAUSE_SHARED:
clauses = cp_parser_omp_var_list (parser, OMP_CLAUSE_SHARED,
clauses);
c_name = "shared";
break;
default:
cp_parser_error (parser, "expected %<#pragma omp%> clause");
goto saw_error;
}
if (((mask >> c_kind) & 1) == 0)
{
/* Remove the invalid clause(s) from the list to avoid
confusing the rest of the compiler. */
clauses = prev;
error ("%qs is not valid for %qs", c_name, where);
}
}
saw_error:
cp_parser_skip_to_pragma_eol (parser, pragma_tok);
return finish_omp_clauses (clauses);
}
/* OpenMP 2.5:
structured-block:
statement
In practice, we're also interested in adding the statement to an
outer node. So it is convenient if we work around the fact that
cp_parser_statement calls add_stmt. */
static unsigned
cp_parser_begin_omp_structured_block (cp_parser *parser)
{
unsigned save = parser->in_statement;
/* Only move the values to IN_OMP_BLOCK if they weren't false.
This preserves the "not within loop or switch" style error messages
for nonsense cases like
void foo() {
#pragma omp single
break;
}
*/
if (parser->in_statement)
parser->in_statement = IN_OMP_BLOCK;
return save;
}
static void
cp_parser_end_omp_structured_block (cp_parser *parser, unsigned save)
{
parser->in_statement = save;
}
static tree
cp_parser_omp_structured_block (cp_parser *parser)
{
tree stmt = begin_omp_structured_block ();
unsigned int save = cp_parser_begin_omp_structured_block (parser);
cp_parser_statement (parser, NULL_TREE, false);
cp_parser_end_omp_structured_block (parser, save);
return finish_omp_structured_block (stmt);
}
/* OpenMP 2.5:
# pragma omp atomic new-line
expression-stmt
expression-stmt:
x binop= expr | x++ | ++x | x-- | --x
binop:
+, *, -, /, &, ^, |, <<, >>
where x is an lvalue expression with scalar type. */
static void
cp_parser_omp_atomic (cp_parser *parser, cp_token *pragma_tok)
{
tree lhs, rhs;
enum tree_code code;
cp_parser_require_pragma_eol (parser, pragma_tok);
lhs = cp_parser_unary_expression (parser, /*address_p=*/false,
/*cast_p=*/false);
switch (TREE_CODE (lhs))
{
case ERROR_MARK:
goto saw_error;
case PREINCREMENT_EXPR:
case POSTINCREMENT_EXPR:
lhs = TREE_OPERAND (lhs, 0);
code = PLUS_EXPR;
rhs = integer_one_node;
break;
case PREDECREMENT_EXPR:
case POSTDECREMENT_EXPR:
lhs = TREE_OPERAND (lhs, 0);
code = MINUS_EXPR;
rhs = integer_one_node;
break;
default:
switch (cp_lexer_peek_token (parser->lexer)->type)
{
case CPP_MULT_EQ:
code = MULT_EXPR;
break;
case CPP_DIV_EQ:
code = TRUNC_DIV_EXPR;
break;
case CPP_PLUS_EQ:
code = PLUS_EXPR;
break;
case CPP_MINUS_EQ:
code = MINUS_EXPR;
break;
case CPP_LSHIFT_EQ:
code = LSHIFT_EXPR;
break;
case CPP_RSHIFT_EQ:
code = RSHIFT_EXPR;
break;
case CPP_AND_EQ:
code = BIT_AND_EXPR;
break;
case CPP_OR_EQ:
code = BIT_IOR_EXPR;
break;
case CPP_XOR_EQ:
code = BIT_XOR_EXPR;
break;
default:
cp_parser_error (parser,
"invalid operator for %<#pragma omp atomic%>");
goto saw_error;
}
cp_lexer_consume_token (parser->lexer);
rhs = cp_parser_expression (parser, false);
if (rhs == error_mark_node)
goto saw_error;
break;
}
finish_omp_atomic (code, lhs, rhs);
cp_parser_consume_semicolon_at_end_of_statement (parser);
return;
saw_error:
cp_parser_skip_to_end_of_block_or_statement (parser);
}
/* OpenMP 2.5:
# pragma omp barrier new-line */
static void
cp_parser_omp_barrier (cp_parser *parser, cp_token *pragma_tok)
{
cp_parser_require_pragma_eol (parser, pragma_tok);
finish_omp_barrier ();
}
/* OpenMP 2.5:
# pragma omp critical [(name)] new-line
structured-block */
static tree
cp_parser_omp_critical (cp_parser *parser, cp_token *pragma_tok)
{
tree stmt, name = NULL;
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
{
cp_lexer_consume_token (parser->lexer);
name = cp_parser_identifier (parser);
if (name == error_mark_node
|| !cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
if (name == error_mark_node)
name = NULL;
}
cp_parser_require_pragma_eol (parser, pragma_tok);
stmt = cp_parser_omp_structured_block (parser);
return c_finish_omp_critical (stmt, name);
}
/* OpenMP 2.5:
# pragma omp flush flush-vars[opt] new-line
flush-vars:
( variable-list ) */
static void
cp_parser_omp_flush (cp_parser *parser, cp_token *pragma_tok)
{
if (cp_lexer_next_token_is (parser->lexer, CPP_OPEN_PAREN))
(void) cp_parser_omp_var_list (parser, 0, NULL);
cp_parser_require_pragma_eol (parser, pragma_tok);
finish_omp_flush ();
}
/* Parse the restricted form of the for statment allowed by OpenMP. */
static tree
cp_parser_omp_for_loop (cp_parser *parser)
{
tree init, cond, incr, body, decl, pre_body;
location_t loc;
if (!cp_lexer_next_token_is_keyword (parser->lexer, RID_FOR))
{
cp_parser_error (parser, "for statement expected");
return NULL;
}
loc = cp_lexer_consume_token (parser->lexer)->location;
if (!cp_parser_require (parser, CPP_OPEN_PAREN, "`('"))
return NULL;
init = decl = NULL;
pre_body = push_stmt_list ();
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
{
cp_decl_specifier_seq type_specifiers;
/* First, try to parse as an initialized declaration. See
cp_parser_condition, from whence the bulk of this is copied. */
cp_parser_parse_tentatively (parser);
cp_parser_type_specifier_seq (parser, /*is_condition=*/false,
&type_specifiers);
if (!cp_parser_error_occurred (parser))
{
tree asm_specification, attributes;
cp_declarator *declarator;
declarator = cp_parser_declarator (parser,
CP_PARSER_DECLARATOR_NAMED,
/*ctor_dtor_or_conv_p=*/NULL,
/*parenthesized_p=*/NULL,
/*member_p=*/false);
attributes = cp_parser_attributes_opt (parser);
asm_specification = cp_parser_asm_specification_opt (parser);
cp_parser_require (parser, CPP_EQ, "`='");
if (cp_parser_parse_definitely (parser))
{
tree pushed_scope;
decl = start_decl (declarator, &type_specifiers,
/*initialized_p=*/false, attributes,
/*prefix_attributes=*/NULL_TREE,
&pushed_scope);
init = cp_parser_assignment_expression (parser, false);
cp_finish_decl (decl, NULL_TREE, /*init_const_expr_p=*/false,
asm_specification, LOOKUP_ONLYCONVERTING);
if (pushed_scope)
pop_scope (pushed_scope);
}
}
else
cp_parser_abort_tentative_parse (parser);
/* If parsing as an initialized declaration failed, try again as
a simple expression. */
if (decl == NULL)
init = cp_parser_expression (parser, false);
}
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
pre_body = pop_stmt_list (pre_body);
cond = NULL;
if (cp_lexer_next_token_is_not (parser->lexer, CPP_SEMICOLON))
cond = cp_parser_condition (parser);
cp_parser_require (parser, CPP_SEMICOLON, "`;'");
incr = NULL;
if (cp_lexer_next_token_is_not (parser->lexer, CPP_CLOSE_PAREN))
incr = cp_parser_expression (parser, false);
if (!cp_parser_require (parser, CPP_CLOSE_PAREN, "`)'"))
cp_parser_skip_to_closing_parenthesis (parser, /*recovering=*/true,
/*or_comma=*/false,
/*consume_paren=*/true);
/* Note that we saved the original contents of this flag when we entered
the structured block, and so we don't need to re-save it here. */
parser->in_statement = IN_OMP_FOR;
/* Note that the grammar doesn't call for a structured block here,
though the loop as a whole is a structured block. */
body = push_stmt_list ();
cp_parser_statement (parser, NULL_TREE, false);
body = pop_stmt_list (body);
return finish_omp_for (loc, decl, init, cond, incr, body, pre_body);
}
/* OpenMP 2.5:
#pragma omp for for-clause[optseq] new-line
for-loop */
#define OMP_FOR_CLAUSE_MASK \
( (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_REDUCTION) \
| (1u << PRAGMA_OMP_CLAUSE_ORDERED) \
| (1u << PRAGMA_OMP_CLAUSE_SCHEDULE) \
| (1u << PRAGMA_OMP_CLAUSE_NOWAIT))
static tree
cp_parser_omp_for (cp_parser *parser, cp_token *pragma_tok)
{
tree clauses, sb, ret;
unsigned int save;
clauses = cp_parser_omp_all_clauses (parser, OMP_FOR_CLAUSE_MASK,
"#pragma omp for", pragma_tok);
sb = begin_omp_structured_block ();
save = cp_parser_begin_omp_structured_block (parser);
ret = cp_parser_omp_for_loop (parser);
if (ret)
OMP_FOR_CLAUSES (ret) = clauses;
cp_parser_end_omp_structured_block (parser, save);
add_stmt (finish_omp_structured_block (sb));
return ret;
}
/* OpenMP 2.5:
# pragma omp master new-line
structured-block */
static tree
cp_parser_omp_master (cp_parser *parser, cp_token *pragma_tok)
{
cp_parser_require_pragma_eol (parser, pragma_tok);
return c_finish_omp_master (cp_parser_omp_structured_block (parser));
}
/* OpenMP 2.5:
# pragma omp ordered new-line
structured-block */
static tree
cp_parser_omp_ordered (cp_parser *parser, cp_token *pragma_tok)
{
cp_parser_require_pragma_eol (parser, pragma_tok);
return c_finish_omp_ordered (cp_parser_omp_structured_block (parser));
}
/* OpenMP 2.5:
section-scope:
{ section-sequence }
section-sequence:
section-directive[opt] structured-block
section-sequence section-directive structured-block */
static tree
cp_parser_omp_sections_scope (cp_parser *parser)
{
tree stmt, substmt;
bool error_suppress = false;
cp_token *tok;
if (!cp_parser_require (parser, CPP_OPEN_BRACE, "`{'"))
return NULL_TREE;
stmt = push_stmt_list ();
if (cp_lexer_peek_token (parser->lexer)->pragma_kind != PRAGMA_OMP_SECTION)
{
unsigned save;
substmt = begin_omp_structured_block ();
save = cp_parser_begin_omp_structured_block (parser);
while (1)
{
cp_parser_statement (parser, NULL_TREE, false);
tok = cp_lexer_peek_token (parser->lexer);
if (tok->pragma_kind == PRAGMA_OMP_SECTION)
break;
if (tok->type == CPP_CLOSE_BRACE)
break;
if (tok->type == CPP_EOF)
break;
}
cp_parser_end_omp_structured_block (parser, save);
substmt = finish_omp_structured_block (substmt);
substmt = build1 (OMP_SECTION, void_type_node, substmt);
add_stmt (substmt);
}
while (1)
{
tok = cp_lexer_peek_token (parser->lexer);
if (tok->type == CPP_CLOSE_BRACE)
break;
if (tok->type == CPP_EOF)
break;
if (tok->pragma_kind == PRAGMA_OMP_SECTION)
{
cp_lexer_consume_token (parser->lexer);
cp_parser_require_pragma_eol (parser, tok);
error_suppress = false;
}
else if (!error_suppress)
{
cp_parser_error (parser, "expected %<#pragma omp section%> or %<}%>");
error_suppress = true;
}
substmt = cp_parser_omp_structured_block (parser);
substmt = build1 (OMP_SECTION, void_type_node, substmt);
add_stmt (substmt);
}
cp_parser_require (parser, CPP_CLOSE_BRACE, "`}'");
substmt = pop_stmt_list (stmt);
stmt = make_node (OMP_SECTIONS);
TREE_TYPE (stmt) = void_type_node;
OMP_SECTIONS_BODY (stmt) = substmt;
add_stmt (stmt);
return stmt;
}
/* OpenMP 2.5:
# pragma omp sections sections-clause[optseq] newline
sections-scope */
#define OMP_SECTIONS_CLAUSE_MASK \
( (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_REDUCTION) \
| (1u << PRAGMA_OMP_CLAUSE_NOWAIT))
static tree
cp_parser_omp_sections (cp_parser *parser, cp_token *pragma_tok)
{
tree clauses, ret;
clauses = cp_parser_omp_all_clauses (parser, OMP_SECTIONS_CLAUSE_MASK,
"#pragma omp sections", pragma_tok);
ret = cp_parser_omp_sections_scope (parser);
if (ret)
OMP_SECTIONS_CLAUSES (ret) = clauses;
return ret;
}
/* OpenMP 2.5:
# pragma parallel parallel-clause new-line
# pragma parallel for parallel-for-clause new-line
# pragma parallel sections parallel-sections-clause new-line */
#define OMP_PARALLEL_CLAUSE_MASK \
( (1u << PRAGMA_OMP_CLAUSE_IF) \
| (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_DEFAULT) \
| (1u << PRAGMA_OMP_CLAUSE_SHARED) \
| (1u << PRAGMA_OMP_CLAUSE_COPYIN) \
| (1u << PRAGMA_OMP_CLAUSE_REDUCTION) \
| (1u << PRAGMA_OMP_CLAUSE_NUM_THREADS))
static tree
cp_parser_omp_parallel (cp_parser *parser, cp_token *pragma_tok)
{
enum pragma_kind p_kind = PRAGMA_OMP_PARALLEL;
const char *p_name = "#pragma omp parallel";
tree stmt, clauses, par_clause, ws_clause, block;
unsigned int mask = OMP_PARALLEL_CLAUSE_MASK;
unsigned int save;
if (cp_lexer_next_token_is_keyword (parser->lexer, RID_FOR))
{
cp_lexer_consume_token (parser->lexer);
p_kind = PRAGMA_OMP_PARALLEL_FOR;
p_name = "#pragma omp parallel for";
mask |= OMP_FOR_CLAUSE_MASK;
mask &= ~(1u << PRAGMA_OMP_CLAUSE_NOWAIT);
}
else if (cp_lexer_next_token_is (parser->lexer, CPP_NAME))
{
tree id = cp_lexer_peek_token (parser->lexer)->u.value;
const char *p = IDENTIFIER_POINTER (id);
if (strcmp (p, "sections") == 0)
{
cp_lexer_consume_token (parser->lexer);
p_kind = PRAGMA_OMP_PARALLEL_SECTIONS;
p_name = "#pragma omp parallel sections";
mask |= OMP_SECTIONS_CLAUSE_MASK;
mask &= ~(1u << PRAGMA_OMP_CLAUSE_NOWAIT);
}
}
clauses = cp_parser_omp_all_clauses (parser, mask, p_name, pragma_tok);
block = begin_omp_parallel ();
save = cp_parser_begin_omp_structured_block (parser);
switch (p_kind)
{
case PRAGMA_OMP_PARALLEL:
cp_parser_already_scoped_statement (parser);
par_clause = clauses;
break;
case PRAGMA_OMP_PARALLEL_FOR:
c_split_parallel_clauses (clauses, &par_clause, &ws_clause);
stmt = cp_parser_omp_for_loop (parser);
if (stmt)
OMP_FOR_CLAUSES (stmt) = ws_clause;
break;
case PRAGMA_OMP_PARALLEL_SECTIONS:
c_split_parallel_clauses (clauses, &par_clause, &ws_clause);
stmt = cp_parser_omp_sections_scope (parser);
if (stmt)
OMP_SECTIONS_CLAUSES (stmt) = ws_clause;
break;
default:
gcc_unreachable ();
}
cp_parser_end_omp_structured_block (parser, save);
stmt = finish_omp_parallel (par_clause, block);
if (p_kind != PRAGMA_OMP_PARALLEL)
OMP_PARALLEL_COMBINED (stmt) = 1;
return stmt;
}
/* OpenMP 2.5:
# pragma omp single single-clause[optseq] new-line
structured-block */
#define OMP_SINGLE_CLAUSE_MASK \
( (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_COPYPRIVATE) \
| (1u << PRAGMA_OMP_CLAUSE_NOWAIT))
static tree
cp_parser_omp_single (cp_parser *parser, cp_token *pragma_tok)
{
tree stmt = make_node (OMP_SINGLE);
TREE_TYPE (stmt) = void_type_node;
OMP_SINGLE_CLAUSES (stmt)
= cp_parser_omp_all_clauses (parser, OMP_SINGLE_CLAUSE_MASK,
"#pragma omp single", pragma_tok);
OMP_SINGLE_BODY (stmt) = cp_parser_omp_structured_block (parser);
return add_stmt (stmt);
}
/* OpenMP 2.5:
# pragma omp threadprivate (variable-list) */
static void
cp_parser_omp_threadprivate (cp_parser *parser, cp_token *pragma_tok)
{
tree vars;
vars = cp_parser_omp_var_list (parser, 0, NULL);
cp_parser_require_pragma_eol (parser, pragma_tok);
if (!targetm.have_tls)
sorry ("threadprivate variables not supported in this target");
finish_omp_threadprivate (vars);
}
/* Main entry point to OpenMP statement pragmas. */
static void
cp_parser_omp_construct (cp_parser *parser, cp_token *pragma_tok)
{
tree stmt;
switch (pragma_tok->pragma_kind)
{
case PRAGMA_OMP_ATOMIC:
cp_parser_omp_atomic (parser, pragma_tok);
return;
case PRAGMA_OMP_CRITICAL:
stmt = cp_parser_omp_critical (parser, pragma_tok);
break;
case PRAGMA_OMP_FOR:
stmt = cp_parser_omp_for (parser, pragma_tok);
break;
case PRAGMA_OMP_MASTER:
stmt = cp_parser_omp_master (parser, pragma_tok);
break;
case PRAGMA_OMP_ORDERED:
stmt = cp_parser_omp_ordered (parser, pragma_tok);
break;
case PRAGMA_OMP_PARALLEL:
stmt = cp_parser_omp_parallel (parser, pragma_tok);
break;
case PRAGMA_OMP_SECTIONS:
stmt = cp_parser_omp_sections (parser, pragma_tok);
break;
case PRAGMA_OMP_SINGLE:
stmt = cp_parser_omp_single (parser, pragma_tok);
break;
default:
gcc_unreachable ();
}
if (stmt)
SET_EXPR_LOCATION (stmt, pragma_tok->location);
}
/* The parser. */
static GTY (()) cp_parser *the_parser;
/* Special handling for the first token or line in the file. The first
thing in the file might be #pragma GCC pch_preprocess, which loads a
PCH file, which is a GC collection point. So we need to handle this
first pragma without benefit of an existing lexer structure.
Always returns one token to the caller in *FIRST_TOKEN. This is
either the true first token of the file, or the first token after
the initial pragma. */
static void
cp_parser_initial_pragma (cp_token *first_token)
{
tree name = NULL;
cp_lexer_get_preprocessor_token (NULL, first_token);
/* APPLE LOCAL begin 4137741 */
while (first_token->type == CPP_BINCL
|| first_token->type == CPP_EINCL)
{
if (first_token->type == CPP_BINCL)
(*debug_hooks->start_source_file) (TREE_INT_CST_LOW (first_token->u.value),
first_token->location.file);
else
(*debug_hooks->end_source_file) (TREE_INT_CST_LOW (first_token->u.value));
cp_lexer_get_preprocessor_token (NULL, first_token);
}
/* APPLE LOCAL end 4137741 */
if (first_token->pragma_kind != PRAGMA_GCC_PCH_PREPROCESS)
return;
cp_lexer_get_preprocessor_token (NULL, first_token);
if (first_token->type == CPP_STRING)
{
name = first_token->u.value;
cp_lexer_get_preprocessor_token (NULL, first_token);
if (first_token->type != CPP_PRAGMA_EOL)
error ("junk at end of %<#pragma GCC pch_preprocess%>");
}
else
error ("expected string literal");
/* Skip to the end of the pragma. */
while (first_token->type != CPP_PRAGMA_EOL && first_token->type != CPP_EOF)
cp_lexer_get_preprocessor_token (NULL, first_token);
/* Now actually load the PCH file. */
if (name)
c_common_pch_pragma (parse_in, TREE_STRING_POINTER (name));
/* Read one more token to return to our caller. We have to do this
after reading the PCH file in, since its pointers have to be
live. */
cp_lexer_get_preprocessor_token (NULL, first_token);
}
/* Normal parsing of a pragma token. Here we can (and must) use the
regular lexer. */
static bool
cp_parser_pragma (cp_parser *parser, enum pragma_context context)
{
cp_token *pragma_tok;
unsigned int id;
pragma_tok = cp_lexer_consume_token (parser->lexer);
gcc_assert (pragma_tok->type == CPP_PRAGMA);
parser->lexer->in_pragma = true;
id = pragma_tok->pragma_kind;
switch (id)
{
case PRAGMA_GCC_PCH_PREPROCESS:
error ("%<#pragma GCC pch_preprocess%> must be first");
break;
case PRAGMA_OMP_BARRIER:
switch (context)
{
case pragma_compound:
cp_parser_omp_barrier (parser, pragma_tok);
return false;
case pragma_stmt:
error ("%<#pragma omp barrier%> may only be "
"used in compound statements");
break;
default:
goto bad_stmt;
}
break;
case PRAGMA_OMP_FLUSH:
switch (context)
{
case pragma_compound:
cp_parser_omp_flush (parser, pragma_tok);
return false;
case pragma_stmt:
error ("%<#pragma omp flush%> may only be "
"used in compound statements");
break;
default:
goto bad_stmt;
}
break;
case PRAGMA_OMP_THREADPRIVATE:
cp_parser_omp_threadprivate (parser, pragma_tok);
return false;
case PRAGMA_OMP_ATOMIC:
case PRAGMA_OMP_CRITICAL:
case PRAGMA_OMP_FOR:
case PRAGMA_OMP_MASTER:
case PRAGMA_OMP_ORDERED:
case PRAGMA_OMP_PARALLEL:
case PRAGMA_OMP_SECTIONS:
case PRAGMA_OMP_SINGLE:
if (context == pragma_external)
goto bad_stmt;
cp_parser_omp_construct (parser, pragma_tok);
return true;
case PRAGMA_OMP_SECTION:
error ("%<#pragma omp section%> may only be used in "
"%<#pragma omp sections%> construct");
break;
default:
gcc_assert (id >= PRAGMA_FIRST_EXTERNAL);
c_invoke_pragma_handler (id);
break;
bad_stmt:
cp_parser_error (parser, "expected declaration specifiers");
break;
}
cp_parser_skip_to_pragma_eol (parser, pragma_tok);
return false;
}
/* The interface the pragma parsers have to the lexer. */
enum cpp_ttype
pragma_lex (tree *value)
{
cp_token *tok;
enum cpp_ttype ret;
tok = cp_lexer_peek_token (the_parser->lexer);
ret = tok->type;
*value = tok->u.value;
if (ret == CPP_PRAGMA_EOL || ret == CPP_EOF)
ret = CPP_EOF;
else if (ret == CPP_STRING)
*value = cp_parser_string_literal (the_parser, false, false);
else
{
cp_lexer_consume_token (the_parser->lexer);
if (ret == CPP_KEYWORD)
ret = CPP_NAME;
}
return ret;
}
/* External interface. */
/* Parse one entire translation unit. */
void
c_parse_file (void)
{
bool error_occurred;
static bool already_called = false;
if (already_called)
{
sorry ("inter-module optimizations not implemented for C++");
return;
}
already_called = true;
the_parser = cp_parser_new ();
push_deferring_access_checks (flag_access_control
? dk_no_deferred : dk_no_check);
error_occurred = cp_parser_translation_unit (the_parser);
the_parser = NULL;
/* APPLE LOCAL begin radar 4874613 */
/* Bad parse errors. Just forget about it. */
if (! global_bindings_p () || current_class_type || decl_namespace_list)
return;
if (pch_file)
c_common_write_pch ();
/* APPLE LOCAL end radar 4874613 */
}
/* This variable must be provided by every front end. */
int yydebug;
#include "gt-cp-parser.h"
|
omp_for_schedule_auto.c | <ompts:test>
<ompts:testdescription>Test with omp for schedule auto</ompts:testdescription>
<ompts:ompversion>3.0</ompts:ompversion>
<ompts:directive>omp for auto</ompts:directive>
<ompts:dependences>omp critical,omp parallel firstprivate</ompts:dependences>
<ompts:testcode>
#include <stdio.h>
#include <math.h>
#include "omp_testsuite.h"
int sum1;
#pragma omp threadprivate(sum1)
int <ompts:testcode:functionname>omp_for_auto</ompts:testcode:functionname> (FILE * logFile)
{
int sum;
<ompts:orphan:vars>
int sum0;
</ompts:orphan:vars>
int known_sum;
int threadsnum;
sum = 0;
sum0 = 12345;
sum1 = 0;
#pragma omp parallel
{
#pragma omp single
{
threadsnum=omp_get_num_threads();
}
/* sum0 = 0; */
<ompts:orphan>
int i;
#pragma omp for <ompts:check>firstprivate(sum0) schedule(auto)</ompts:check><ompts:crosscheck>private(sum0)</ompts:crosscheck>
for (i = 1; i <= LOOPCOUNT; i++)
{
sum0 = sum0 + i;
sum1 = sum0;
} /* end of for */
</ompts:orphan>
#pragma omp critical
{
sum = sum + sum1;
} /* end of critical */
} /* end of parallel */
known_sum = 12345* threadsnum+ (LOOPCOUNT * (LOOPCOUNT + 1)) / 2;
return (known_sum == sum);
}
</ompts:testcode>
</ompts:test>
|
ch_common.h | #ifndef _BENCH_CHOLESKY_COMMON_
#define _BENCH_CHOLESKY_COMMON_
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sys/syscall.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <mkl.h>
#include <mpi.h>
#include <omp.h>
#ifdef TRACE
#include "VT.h"
#endif
#ifdef MAIN
int np;
int mype;
int num_threads;
#else
extern int np;
extern int mype;
extern int num_threads;
#endif
#if defined(USE_TIMING)
void helper_start_timing(int tt);
void helper_end_timing(int tt, double elapsed);
#endif
// #define SPEC_RESTRICT __restrict__
#define SPEC_RESTRICT restrict
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
#include "chameleon.h"
#endif
#ifndef DPxMOD
#define DPxMOD "0x%0*" PRIxPTR
#endif
#ifndef DPxPTR
#define DPxPTR(ptr) ((int)(2*sizeof(uintptr_t))), ((uintptr_t) (ptr))
#endif
#ifdef DEBUG
int* __task_depth_counter;
#define TASK_DEPTH_OFFSET 32
#define TASK_DEPTH_INIT do { \
__task_depth_counter = (int*) malloc((omp_get_max_threads()+1)*TASK_DEPTH_OFFSET*sizeof(int)); \
for (int i = 0; i < omp_get_max_threads(); i++) { \
__task_depth_counter[i*TASK_DEPTH_OFFSET] = 0; \
} \
} while(0)
#define TASK_DEPTH_FINALIZE \
if(__task_depth_counter) \
free(__task_depth_counter);
#define TASK_DEPTH_INCR ++__task_depth_counter[omp_get_thread_num()*TASK_DEPTH_OFFSET]
#define TASK_DEPTH_DECR --__task_depth_counter[omp_get_thread_num()*TASK_DEPTH_OFFSET]
#define TASK_DEPTH_GET __task_depth_counter[omp_get_thread_num()*TASK_DEPTH_OFFSET]
#define DEBUG_PRINT(STR, ...) do { \
char* tmp_str = malloc(sizeof(char)*512); \
tmp_str[0] = '\0'; \
strcat(tmp_str,"R#%02d T#%02d (OS_TID:%06ld) Task-Depth:%02d : --> "); \
strcat(tmp_str,STR); \
fprintf(stderr, tmp_str, mype, omp_get_thread_num(), syscall(SYS_gettid), TASK_DEPTH_GET, __VA_ARGS__); \
free(tmp_str); \
} while(0)
#else
#define TASK_DEPTH_INIT
#define TASK_DEPTH_FINALIZE
#define TASK_DEPTH_INCR
#define TASK_DEPTH_DECR
#define TASK_DEPTH_GET 0
#define DEBUG_PRINT(STR, ...)
#endif
#ifdef _USE_HBW
#include <hbwmalloc.h>
#endif
void dgemm_ (const char *transa, const char *transb, int *l, int *n, int *m, double *alpha,
const void *a, int *lda, void *b, int *ldb, double *beta, void *c, int *ldc);
void dtrsm_ (char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha,
double *a, int *lda, double *b, int *ldb);
void dsyrk_ (char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda,
double *beta, double *c, int *ldc);
void cholesky_single(const int ts, const int nt, double* A[nt][nt]);
void cholesky_mpi(const int ts, const int nt, double *A[nt][nt], double *B, double *C[nt], int *block_rank);
void omp_potrf(double * SPEC_RESTRICT const A, int ts, int ld);
void omp_trsm(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, int ts, int ld);
void omp_gemm(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, double * SPEC_RESTRICT C, int ts, int ld);
void omp_syrk(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, int ts, int ld);
int get_send_flags(char *send_flags, int *block_rank, int itr1_str, int itr1_end, int itr2_str, int itr2_end, int n);
void get_recv_flag(char *recv_flag, int *block_rank, int itr1_str, int itr1_end, int itr2_str, int itr2_end, int n);
void wait(MPI_Request *comm_req);
inline static void waitall(MPI_Request *comm_req, int n)
{
#ifdef TRACE
static int event_waitall = -1;
if(event_waitall == -1) {
char* event_name = "waitall";
int ierr;
ierr = VT_funcdef(event_name, VT_NOCLASS, &event_waitall);
}
VT_begin(event_waitall);
#endif
#ifdef DISABLE_TASKYIELD
MPI_Waitall(n, comm_req, MPI_STATUSES_IGNORE);
#else
while (1) {
int flag = 0;
MPI_Testall(n, comm_req, &flag, MPI_STATUSES_IGNORE);
if (flag) break;
(void)flag; // <-- make the Cray compiler happy
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
int32_t res = chameleon_taskyield();
#else
#pragma omp taskyield
#endif
}
#endif
#ifdef TRACE
VT_end(event_waitall);
#endif
}
void reset_send_flags(char *send_flags);
#endif
|
Softmax.h | // --------------------------------------------------------------------------
// Binary Brain -- binary neural net framework
//
// Copyright (C) 2018-2019 by Ryuji Fuchikami
// https://github.com/ryuz
// ryuji.fuchikami@nifty.com
// --------------------------------------------------------------------------
#pragma once
#include "bb/Manager.h"
#include "bb/Activation.h"
namespace bb {
// Sigmoid(活性化層)
template <typename T = float>
class Softmax: public Activation
{
using _super = Activation;
public:
static inline std::string ModelName(void) { return "Softmax"; }
static inline std::string ObjectName(void){ return ModelName() + "_" + DataType<T>::Name(); }
std::string GetModelName(void) const override { return ModelName(); }
std::string GetObjectName(void) const override { return ObjectName(); }
protected:
indices_t m_shape;
bool m_host_only = false;
FrameBuffer m_y_buf;
protected:
Softmax() {
}
/**
* @brief コマンド処理
* @detail コマンド処理
* @param args コマンド
*/
void CommandProc(std::vector<std::string> args) override
{
// HostOnlyモード設定
if (args.size() == 2 && args[0] == "host_only")
{
m_host_only = EvalBool(args[1]);
}
}
public:
static std::shared_ptr<Softmax> Create(void)
{
return std::shared_ptr<Softmax>(new Softmax);
}
~Softmax() {}
/**
* @brief 入力形状設定
* @detail 入力形状を設定する
* 内部変数を初期化し、以降、GetOutputShape()で値取得可能となることとする
* 同一形状を指定しても内部変数は初期化されるものとする
* @param shape 1フレームのノードを構成するshape
* @return 出力形状を返す
*/
indices_t SetInputShape(indices_t shape) override
{
// 設定済みなら何もしない
if ( shape == this->GetInputShape() ) {
return this->GetOutputShape();
}
m_shape = shape;
return m_shape;
}
/**
* @brief 入力形状取得
* @detail 入力形状を取得する
* @return 入力形状を返す
*/
indices_t GetInputShape(void) const override
{
return m_shape;
}
/**
* @brief 出力形状取得
* @detail 出力形状を取得する
* @return 出力形状を返す
*/
indices_t GetOutputShape(void) const override
{
return m_shape;
}
// 1ノードのみForward計算
std::vector<double> ForwardNode(index_t node, std::vector<double> x_vec) const
{
std::vector<double> y_vec(x_vec.size());
double max_x = 0;
for ( auto x : x_vec ) {
max_x = std::max(max_x, x);
}
double sum = 0;
for ( size_t i=0; i < x_vec.size(); ++i ) {
auto x = x_vec[i] - max_x;
y_vec[i] = std::exp(x);
sum += y_vec[i];
}
sum = std::max(sum, 1.0e-7);
for ( auto& y : y_vec ) {
y /= sum;
}
return y_vec;
}
/**
* @brief forward演算
* @detail forward演算を行う
* @param x 入力データ
* @param train 学習時にtrueを指定
* @return forward演算結果
*/
inline FrameBuffer Forward(FrameBuffer x_buf, bool train = true) override
{
// binaryモード
BB_ASSERT(x_buf.GetType() == DataType<T>::type);
// 戻り値のサイズ設定
FrameBuffer y_buf(x_buf.GetFrameSize(), x_buf.GetShape(), x_buf.GetType());
// ローカルに保存
if ( train ) {
m_y_buf = y_buf;
}
{
// 汎用版
auto frame_size = x_buf.GetFrameSize();
auto node_size = x_buf.GetNodeSize();
auto shape = x_buf.GetShape();
auto ch_size = shape[0];
auto pix_size = node_size / ch_size;
auto x_ptr = x_buf.LockConst<T>();
auto y_ptr = y_buf.Lock<T>(true);
// #pragma omp parallel for
for (index_t frame = 0; frame < frame_size; ++frame) {
for (index_t pix = 0; pix < pix_size; ++pix) {
// max
T c = 0;
for (index_t ch = 0; ch < ch_size; ++ch) {
auto node = ch * pix_size + pix;
c = std::max(c, x_ptr.Get(frame, node));
}
// sum(exp(x - c))
T sum = 0;
for (index_t ch = 0; ch < ch_size; ++ch) {
auto node = ch * pix_size + pix;
sum += std::exp(x_ptr.Get(frame, node) - c);
}
sum = std::max(sum, (T)1.0e-7);
for (index_t ch = 0; ch < ch_size; ++ch) {
auto node = ch * pix_size + pix;
auto y = std::exp(x_ptr.Get(frame, node) - c) / sum;
y_ptr.Set(frame, node, y);
}
}
}
return y_buf;
}
}
/**
* @brief backward演算
* @detail backward演算を行う
*
* @return backward演算結果
*/
inline FrameBuffer Backward(FrameBuffer dy_buf) override
{
BB_ASSERT(dy_buf.GetType() == DataType<T>::type);
// 戻り値のサイズ設定
FrameBuffer dx_buf(dy_buf.GetFrameSize(), dy_buf.GetShape(), dy_buf.GetType());
FrameBuffer y_buf = m_y_buf;
m_y_buf = FrameBuffer();
{
auto frame_size = dy_buf.GetFrameSize();
auto node_size = dy_buf.GetNodeSize();
auto shape = dy_buf.GetShape();
auto ch_size = shape[0];
auto pix_size = node_size / ch_size;
auto y_ptr = y_buf.LockConst<T>();
auto dy_ptr = dy_buf.LockConst<T>();
auto dx_ptr = dx_buf.Lock<T>(true);
// #pragma omp parallel for
for (index_t frame = 0; frame < frame_size; ++frame) {
for (index_t pix = 0; pix < pix_size; ++pix) {
// sum(dy*y)
T sum = 0;
for (index_t ch = 0; ch < ch_size; ++ch) {
auto node = ch * pix_size + pix;
auto dy = dy_ptr.Get(frame, node);
auto y = y_ptr.Get(frame, node);
sum += dy * y;
}
for (index_t ch = 0; ch < ch_size; ++ch) {
auto node = ch * pix_size + pix;
auto dy = dy_ptr.Get(frame, node);
auto y = y_ptr.Get(frame, node);
dx_ptr.Set(frame, node, (dy - sum)*y);
}
}
}
return dx_buf;
}
}
// シリアライズ
protected:
void DumpObjectData(std::ostream &os) const override
{
// バージョン
std::int64_t ver = 1;
bb::SaveValue(os, ver);
// 親クラス
_super::DumpObjectData(os);
}
void LoadObjectData(std::istream &is) override
{
// バージョン
std::int64_t ver;
bb::LoadValue(is, ver);
BB_ASSERT(ver == 1);
// 親クラス
_super::LoadObjectData(is);
}
};
}
|
omp_simd.c | //Variable examples of using simd directives
void foo (int n, double *a, double* b)
{
#pragma omp simd
for (int i=0; i<n; i++)
a[i]=b[i];
}
|
3d25pt.c | /*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 16;
tile_size[1] = 16;
tile_size[2] = 24;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*(
coef0* A[t%2][i ][j ][k ] +
coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] +
A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] +
A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) +
coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] +
A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] +
A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) +
coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] +
A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] +
A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) +
coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] +
A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] +
A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) );
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
par_csr_matop_device.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)
******************************************************************************/
#include "_hypre_utilities.h"
#include "_hypre_parcsr_mv.h"
#include "_hypre_utilities.hpp"
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_Int
hypre_ParcsrGetExternalRowsDeviceInit( hypre_ParCSRMatrix *A,
HYPRE_Int indices_len,
HYPRE_BigInt *indices,
hypre_ParCSRCommPkg *comm_pkg,
HYPRE_Int want_data,
void **request_ptr)
{
HYPRE_Int i, j;
HYPRE_Int num_sends, num_rows_send, num_nnz_send, num_recvs, num_rows_recv, num_nnz_recv;
HYPRE_Int *d_send_i, *send_i, *d_send_map, *d_recv_i, *recv_i;
HYPRE_BigInt *d_send_j, *d_recv_j;
HYPRE_Int *send_jstarts, *recv_jstarts;
HYPRE_Complex *d_send_a = NULL, *d_recv_a = NULL;
hypre_ParCSRCommPkg *comm_pkg_j;
hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a;
/* HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); */
/* diag part of A */
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
/* HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); */
/* off-diag part of A */
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
/* HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); */
/* HYPRE_Int first_row = hypre_ParCSRMatrixFirstRowIndex(A); */
HYPRE_Int first_col = hypre_ParCSRMatrixFirstColDiag(A);
HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *d_col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A);
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
HYPRE_Int num_procs;
HYPRE_Int my_id;
void **vrequest;
hypre_CSRMatrix *A_ext;
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm, &my_id);
/* number of sends (#procs) */
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
/* number of rows to send */
num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends);
/* number of recvs (#procs) */
num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg);
/* number of rows to recv */
num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs);
/* must be true if indices contains proper offd indices */
hypre_assert(indices_len == num_rows_recv);
/* send_i/recv_i:
* the arrays to send and recv: we first send and recv the row lengths */
d_send_i = hypre_TAlloc(HYPRE_Int, num_rows_send + 1, HYPRE_MEMORY_DEVICE);
d_send_map = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_DEVICE);
send_i = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST);
recv_i = hypre_TAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_HOST);
d_recv_i = hypre_TAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_DEVICE);
/* fill the send array with row lengths */
hypre_TMemcpy(d_send_map, hypre_ParCSRCommPkgSendMapElmts(comm_pkg), HYPRE_Int,
num_rows_send, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST);
hypre_Memset(d_send_i, 0, sizeof(HYPRE_Int), HYPRE_MEMORY_DEVICE);
hypreDevice_GetRowNnz(num_rows_send, d_send_map, A_diag_i, A_offd_i, d_send_i + 1);
/* send array send_i out: deviceTohost first and MPI (async)
* note the shift in recv_i by one */
hypre_TMemcpy(send_i, d_send_i + 1, HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST,
HYPRE_MEMORY_DEVICE);
comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_i, recv_i + 1);
hypreDevice_IntegerInclusiveScan(num_rows_send + 1, d_send_i);
/* total number of nnz to send */
hypre_TMemcpy(&num_nnz_send, d_send_i + num_rows_send, HYPRE_Int, 1, HYPRE_MEMORY_HOST,
HYPRE_MEMORY_DEVICE);
/* prepare data to send out. overlap with the above commmunication */
d_send_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_send, HYPRE_MEMORY_DEVICE);
if (want_data)
{
d_send_a = hypre_TAlloc(HYPRE_Complex, num_nnz_send, HYPRE_MEMORY_DEVICE);
}
if (d_col_map_offd_A == NULL)
{
d_col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(d_col_map_offd_A, col_map_offd_A, HYPRE_BigInt, num_cols_A_offd,
HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDeviceColMapOffd(A) = d_col_map_offd_A;
}
/* job == 2, d_send_i is input that contains row ptrs (length num_rows_send) */
hypreDevice_CopyParCSRRows(num_rows_send, d_send_map, 2, num_procs > 1,
first_col, d_col_map_offd_A,
A_diag_i, A_diag_j, A_diag_a,
A_offd_i, A_offd_j, A_offd_a,
d_send_i, d_send_j, d_send_a);
/* pointers to each proc in send_j */
send_jstarts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST);
send_jstarts[0] = 0;
for (i = 1; i <= num_sends; i++)
{
send_jstarts[i] = send_jstarts[i - 1];
for ( j = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i - 1);
j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
j++ )
{
send_jstarts[i] += send_i[j];
}
}
hypre_assert(send_jstarts[num_sends] == num_nnz_send);
/* finish the above communication: send_i/recv_i */
hypre_ParCSRCommHandleDestroy(comm_handle);
/* adjust recv_i to ptrs */
recv_i[0] = 0;
for (i = 1; i <= num_rows_recv; i++)
{
recv_i[i] += recv_i[i - 1];
}
num_nnz_recv = recv_i[num_rows_recv];
/* allocate device memory for j and a */
d_recv_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_recv, HYPRE_MEMORY_DEVICE);
if (want_data)
{
d_recv_a = hypre_TAlloc(HYPRE_Complex, num_nnz_recv, HYPRE_MEMORY_DEVICE);
}
recv_jstarts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST);
recv_jstarts[0] = 0;
for (i = 1; i <= num_recvs; i++)
{
j = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i);
recv_jstarts[i] = recv_i[j];
}
/* ready to send and recv: create a communication package for data */
comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST);
hypre_ParCSRCommPkgComm (comm_pkg_j) = comm;
hypre_ParCSRCommPkgNumSends (comm_pkg_j) = num_sends;
hypre_ParCSRCommPkgSendProcs (comm_pkg_j) = hypre_ParCSRCommPkgSendProcs(comm_pkg);
hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = send_jstarts;
hypre_ParCSRCommPkgNumRecvs (comm_pkg_j) = num_recvs;
hypre_ParCSRCommPkgRecvProcs (comm_pkg_j) = hypre_ParCSRCommPkgRecvProcs(comm_pkg);
hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = recv_jstarts;
/* init communication */
/* ja */
comm_handle_j = hypre_ParCSRCommHandleCreate_v2(21, comm_pkg_j,
HYPRE_MEMORY_DEVICE, d_send_j,
HYPRE_MEMORY_DEVICE, d_recv_j);
if (want_data)
{
/* a */
comm_handle_a = hypre_ParCSRCommHandleCreate_v2(1, comm_pkg_j,
HYPRE_MEMORY_DEVICE, d_send_a,
HYPRE_MEMORY_DEVICE, d_recv_a);
}
else
{
comm_handle_a = NULL;
}
hypre_TMemcpy(d_recv_i, recv_i, HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_DEVICE,
HYPRE_MEMORY_HOST);
/* create A_ext: on device */
A_ext = hypre_CSRMatrixCreate(num_rows_recv, hypre_ParCSRMatrixGlobalNumCols(A), num_nnz_recv);
hypre_CSRMatrixI (A_ext) = d_recv_i;
hypre_CSRMatrixBigJ(A_ext) = d_recv_j;
hypre_CSRMatrixData(A_ext) = d_recv_a;
hypre_CSRMatrixMemoryLocation(A_ext) = HYPRE_MEMORY_DEVICE;
/* output */
vrequest = hypre_TAlloc(void *, 3, HYPRE_MEMORY_HOST);
vrequest[0] = (void *) comm_handle_j;
vrequest[1] = (void *) comm_handle_a;
vrequest[2] = (void *) A_ext;
*request_ptr = (void *) vrequest;
/* free */
hypre_TFree(send_i, HYPRE_MEMORY_HOST);
hypre_TFree(recv_i, HYPRE_MEMORY_HOST);
hypre_TFree(d_send_i, HYPRE_MEMORY_DEVICE);
hypre_TFree(d_send_map, HYPRE_MEMORY_DEVICE);
hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST);
hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST);
hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
hypre_CSRMatrix*
hypre_ParcsrGetExternalRowsDeviceWait(void *vrequest)
{
void **request = (void **) vrequest;
hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0];
hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1];
hypre_CSRMatrix *A_ext = (hypre_CSRMatrix *) request[2];
HYPRE_BigInt *send_j = comm_handle_j ? (HYPRE_BigInt *)
hypre_ParCSRCommHandleSendData(comm_handle_j) : NULL;
HYPRE_Complex *send_a = comm_handle_a ? (HYPRE_Complex *)
hypre_ParCSRCommHandleSendData(comm_handle_a) : NULL;
hypre_ParCSRCommHandleDestroy(comm_handle_j);
hypre_ParCSRCommHandleDestroy(comm_handle_a);
hypre_TFree(send_j, HYPRE_MEMORY_DEVICE);
hypre_TFree(send_a, HYPRE_MEMORY_DEVICE);
hypre_TFree(request, HYPRE_MEMORY_HOST);
return A_ext;
}
hypre_CSRMatrix*
hypre_MergeDiagAndOffdDevice(hypre_ParCSRMatrix *A)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Complex *A_diag_a = 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_Complex *A_offd_a = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt glbal_num_cols = hypre_ParCSRMatrixGlobalNumCols(A);
HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A);
HYPRE_BigInt *d_col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A);
hypre_CSRMatrix *B;
HYPRE_Int B_nrows = local_num_rows;
HYPRE_BigInt B_ncols = glbal_num_cols;
HYPRE_Int *B_i = hypre_TAlloc(HYPRE_Int, B_nrows + 1, HYPRE_MEMORY_DEVICE);
HYPRE_BigInt *B_j;
HYPRE_Complex *B_a;
HYPRE_Int B_nnz;
HYPRE_Int num_procs;
hypre_MPI_Comm_size(comm, &num_procs);
hypre_Memset(B_i, 0, sizeof(HYPRE_Int), HYPRE_MEMORY_DEVICE);
hypreDevice_GetRowNnz(B_nrows, NULL, A_diag_i, A_offd_i, B_i + 1);
hypreDevice_IntegerInclusiveScan(B_nrows + 1, B_i);
/* total number of nnz */
hypre_TMemcpy(&B_nnz, B_i + B_nrows, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
B_j = hypre_TAlloc(HYPRE_BigInt, B_nnz, HYPRE_MEMORY_DEVICE);
B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE);
if (d_col_map_offd_A == NULL)
{
d_col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(d_col_map_offd_A, col_map_offd_A, HYPRE_BigInt, num_cols_A_offd,
HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDeviceColMapOffd(A) = d_col_map_offd_A;
}
hypreDevice_CopyParCSRRows(B_nrows, NULL, 2, num_procs > 1, first_col, d_col_map_offd_A,
A_diag_i, A_diag_j, A_diag_a, A_offd_i, A_offd_j, A_offd_a,
B_i, B_j, B_a);
/* output */
B = hypre_CSRMatrixCreate(B_nrows, B_ncols, B_nnz);
hypre_CSRMatrixI (B) = B_i;
hypre_CSRMatrixBigJ(B) = B_j;
hypre_CSRMatrixData(B) = B_a;
hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE;
hypre_SyncComputeStream(hypre_handle());
return B;
}
HYPRE_Int
hypre_ExchangeExternalRowsDeviceInit( hypre_CSRMatrix *B_ext,
hypre_ParCSRCommPkg *comm_pkg_A,
HYPRE_Int want_data,
void **request_ptr)
{
MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_A);
HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A);
HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A);
HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A);
HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_A);
HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_A);
HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A);
HYPRE_Int num_elmts_send = send_map_starts[num_sends];
HYPRE_Int num_elmts_recv = recv_vec_starts[num_recvs];
HYPRE_Int *B_ext_i_d = hypre_CSRMatrixI(B_ext);
HYPRE_BigInt *B_ext_j_d = hypre_CSRMatrixBigJ(B_ext);
HYPRE_Complex *B_ext_a_d = hypre_CSRMatrixData(B_ext);
HYPRE_Int B_ext_ncols = hypre_CSRMatrixNumCols(B_ext);
HYPRE_Int B_ext_nrows = hypre_CSRMatrixNumRows(B_ext);
HYPRE_Int B_ext_nnz = hypre_CSRMatrixNumNonzeros(B_ext);
HYPRE_Int *B_ext_rownnz_d = hypre_TAlloc(HYPRE_Int, B_ext_nrows + 1, HYPRE_MEMORY_DEVICE);
HYPRE_Int *B_ext_rownnz_h = hypre_TAlloc(HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST);
HYPRE_Int *B_ext_i_h = hypre_TAlloc(HYPRE_Int, B_ext_nrows + 1, HYPRE_MEMORY_HOST);
hypre_assert(num_elmts_recv == B_ext_nrows);
/* output matrix */
hypre_CSRMatrix *B_int_d;
HYPRE_Int B_int_nrows = num_elmts_send;
HYPRE_Int B_int_ncols = B_ext_ncols;
HYPRE_Int *B_int_i_h = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_HOST);
HYPRE_Int *B_int_i_d = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_DEVICE);
HYPRE_BigInt *B_int_j_d = NULL;
HYPRE_Complex *B_int_a_d = NULL;
HYPRE_Int B_int_nnz;
hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a;
hypre_ParCSRCommPkg *comm_pkg_j;
HYPRE_Int *jdata_recv_vec_starts;
HYPRE_Int *jdata_send_map_starts;
HYPRE_Int i;
HYPRE_Int num_procs, my_id;
void **vrequest;
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm, &my_id);
jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST);
/*--------------------------------------------------------------------------
* B_ext_rownnz contains the number of elements of row j
* (to be determined through send_map_elmnts on the receiving end)
*--------------------------------------------------------------------------*/
HYPRE_THRUST_CALL(adjacent_difference, B_ext_i_d, B_ext_i_d + B_ext_nrows + 1, B_ext_rownnz_d);
hypre_TMemcpy(B_ext_rownnz_h, B_ext_rownnz_d + 1, HYPRE_Int, B_ext_nrows,
HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
/*--------------------------------------------------------------------------
* initialize communication: send/recv the row nnz
* (note the use of comm_pkg_A, mode 12, as in transpose matvec
*--------------------------------------------------------------------------*/
comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_A, B_ext_rownnz_h, B_int_i_h + 1);
jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST);
jdata_recv_vec_starts[0] = 0;
B_ext_i_h[0] = 0;
hypre_TMemcpy(B_ext_i_h + 1, B_ext_rownnz_h, HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST,
HYPRE_MEMORY_HOST);
for (i = 1; i <= B_ext_nrows; i++)
{
B_ext_i_h[i] += B_ext_i_h[i - 1];
}
hypre_assert(B_ext_i_h[B_ext_nrows] == B_ext_nnz);
for (i = 1; i <= num_recvs; i++)
{
jdata_recv_vec_starts[i] = B_ext_i_h[recv_vec_starts[i]];
}
comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST);
hypre_ParCSRCommPkgComm(comm_pkg_j) = comm;
hypre_ParCSRCommPkgNumSends(comm_pkg_j) = num_recvs;
hypre_ParCSRCommPkgNumRecvs(comm_pkg_j) = num_sends;
hypre_ParCSRCommPkgSendProcs(comm_pkg_j) = recv_procs;
hypre_ParCSRCommPkgRecvProcs(comm_pkg_j) = send_procs;
hypre_ParCSRCommHandleDestroy(comm_handle);
/*--------------------------------------------------------------------------
* compute B_int: row nnz to row ptrs
*--------------------------------------------------------------------------*/
B_int_i_h[0] = 0;
for (i = 1; i <= B_int_nrows; i++)
{
B_int_i_h[i] += B_int_i_h[i - 1];
}
B_int_nnz = B_int_i_h[B_int_nrows];
B_int_j_d = hypre_TAlloc(HYPRE_BigInt, B_int_nnz, HYPRE_MEMORY_DEVICE);
if (want_data)
{
B_int_a_d = hypre_TAlloc(HYPRE_Complex, B_int_nnz, HYPRE_MEMORY_DEVICE);
}
for (i = 0; i <= num_sends; i++)
{
jdata_send_map_starts[i] = B_int_i_h[send_map_starts[i]];
}
/* note the order of send/recv is reversed */
hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = jdata_send_map_starts;
hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = jdata_recv_vec_starts;
/* send/recv CSR rows */
if (want_data)
{
comm_handle_a = hypre_ParCSRCommHandleCreate_v2( 1, comm_pkg_j,
HYPRE_MEMORY_DEVICE, B_ext_a_d,
HYPRE_MEMORY_DEVICE, B_int_a_d );
}
else
{
comm_handle_a = NULL;
}
comm_handle_j = hypre_ParCSRCommHandleCreate_v2(21, comm_pkg_j,
HYPRE_MEMORY_DEVICE, B_ext_j_d,
HYPRE_MEMORY_DEVICE, B_int_j_d );
hypre_TMemcpy(B_int_i_d, B_int_i_h, HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_DEVICE,
HYPRE_MEMORY_HOST);
/* create CSR: on device */
B_int_d = hypre_CSRMatrixCreate(B_int_nrows, B_int_ncols, B_int_nnz);
hypre_CSRMatrixI(B_int_d) = B_int_i_d;
hypre_CSRMatrixBigJ(B_int_d) = B_int_j_d;
hypre_CSRMatrixData(B_int_d) = B_int_a_d;
hypre_CSRMatrixMemoryLocation(B_int_d) = HYPRE_MEMORY_DEVICE;
/* output */
vrequest = hypre_TAlloc(void *, 3, HYPRE_MEMORY_HOST);
vrequest[0] = (void *) comm_handle_j;
vrequest[1] = (void *) comm_handle_a;
vrequest[2] = (void *) B_int_d;
*request_ptr = (void *) vrequest;
/* free */
hypre_TFree(B_ext_rownnz_d, HYPRE_MEMORY_DEVICE);
hypre_TFree(B_ext_rownnz_h, HYPRE_MEMORY_HOST);
hypre_TFree(B_ext_i_h, HYPRE_MEMORY_HOST);
hypre_TFree(B_int_i_h, HYPRE_MEMORY_HOST);
hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST);
hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST);
hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
hypre_CSRMatrix*
hypre_ExchangeExternalRowsDeviceWait(void *vrequest)
{
void **request = (void **) vrequest;
hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0];
hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1];
hypre_CSRMatrix *B_int_d = (hypre_CSRMatrix *) request[2];
/* communication done */
hypre_ParCSRCommHandleDestroy(comm_handle_j);
hypre_ParCSRCommHandleDestroy(comm_handle_a);
hypre_TFree(request, HYPRE_MEMORY_HOST);
return B_int_d;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
HYPRE_Int
hypre_ParCSRMatrixExtractBExtDeviceInit( hypre_ParCSRMatrix *B,
hypre_ParCSRMatrix *A,
HYPRE_Int want_data,
void **request_ptr)
{
hypre_assert( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B)) ==
hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(B)) );
/*
hypre_assert( hypre_GetActualMemLocation(
hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B))) == HYPRE_MEMORY_DEVICE );
*/
if (!hypre_ParCSRMatrixCommPkg(A))
{
hypre_MatvecCommPkgCreate(A);
}
hypre_ParcsrGetExternalRowsDeviceInit(B,
hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)),
hypre_ParCSRMatrixColMapOffd(A),
hypre_ParCSRMatrixCommPkg(A),
want_data,
request_ptr);
return hypre_error_flag;
}
hypre_CSRMatrix*
hypre_ParCSRMatrixExtractBExtDeviceWait(void *request)
{
return hypre_ParcsrGetExternalRowsDeviceWait(request);
}
hypre_CSRMatrix*
hypre_ParCSRMatrixExtractBExtDevice( hypre_ParCSRMatrix *B,
hypre_ParCSRMatrix *A,
HYPRE_Int want_data )
{
void *request;
hypre_ParCSRMatrixExtractBExtDeviceInit(B, A, want_data, &request);
return hypre_ParCSRMatrixExtractBExtDeviceWait(request);
}
/* return B = [Adiag, Aoffd] */
#if 1
__global__ void
hypreCUDAKernel_ConcatDiagAndOffd(HYPRE_Int nrows, HYPRE_Int diag_ncol,
HYPRE_Int *d_diag_i, HYPRE_Int *d_diag_j, HYPRE_Complex *d_diag_a,
HYPRE_Int *d_offd_i, HYPRE_Int *d_offd_j, HYPRE_Complex *d_offd_a,
HYPRE_Int *cols_offd_map,
HYPRE_Int *d_ib, HYPRE_Int *d_jb, HYPRE_Complex *d_ab)
{
const HYPRE_Int row = hypre_cuda_get_grid_warp_id<1, 1>();
if (row >= nrows)
{
return;
}
/* lane id inside the warp */
const HYPRE_Int lane_id = hypre_cuda_get_lane_id<1>();
HYPRE_Int i, j, k, p, istart, iend, bstart;
/* diag part */
if (lane_id < 2)
{
j = read_only_load(d_diag_i + row + lane_id);
}
if (lane_id == 0)
{
k = read_only_load(d_ib + row);
}
istart = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 0);
iend = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 1);
bstart = __shfl_sync(HYPRE_WARP_FULL_MASK, k, 0);
p = bstart - istart;
for (i = istart + lane_id; i < iend; i += HYPRE_WARP_SIZE)
{
d_jb[p + i] = read_only_load(d_diag_j + i);
d_ab[p + i] = read_only_load(d_diag_a + i);
}
/* offd part */
if (lane_id < 2)
{
j = read_only_load(d_offd_i + row + lane_id);
}
bstart += iend - istart;
istart = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 0);
iend = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 1);
p = bstart - istart;
for (i = istart + lane_id; i < iend; i += HYPRE_WARP_SIZE)
{
const HYPRE_Int t = read_only_load(d_offd_j + i);
d_jb[p + i] = (cols_offd_map ? read_only_load(&cols_offd_map[t]) : t) + diag_ncol;
d_ab[p + i] = read_only_load(d_offd_a + i);
}
}
hypre_CSRMatrix*
hypre_ConcatDiagAndOffdDevice(hypre_ParCSRMatrix *A)
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
hypre_CSRMatrix *B = hypre_CSRMatrixCreate( hypre_CSRMatrixNumRows(A_diag),
hypre_CSRMatrixNumCols(A_diag) + hypre_CSRMatrixNumCols(A_offd),
hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd) );
hypre_CSRMatrixInitialize_v2(B, 0, HYPRE_MEMORY_DEVICE);
hypreDevice_GetRowNnz(hypre_CSRMatrixNumRows(B), NULL, hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixI(A_offd), hypre_CSRMatrixI(B));
HYPRE_THRUST_CALL( exclusive_scan,
hypre_CSRMatrixI(B),
hypre_CSRMatrixI(B) + hypre_CSRMatrixNumRows(B) + 1,
hypre_CSRMatrixI(B) );
const dim3 bDim = hypre_GetDefaultDeviceBlockDimension();
const dim3 gDim = hypre_GetDefaultDeviceGridDimension(hypre_CSRMatrixNumRows(A_diag), "warp", bDim);
HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd,
gDim, bDim,
hypre_CSRMatrixNumRows(A_diag),
hypre_CSRMatrixNumCols(A_diag),
hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixJ(A_diag),
hypre_CSRMatrixData(A_diag),
hypre_CSRMatrixI(A_offd),
hypre_CSRMatrixJ(A_offd),
hypre_CSRMatrixData(A_offd),
NULL,
hypre_CSRMatrixI(B),
hypre_CSRMatrixJ(B),
hypre_CSRMatrixData(B) );
return B;
}
#else
hypre_CSRMatrix*
hypre_ConcatDiagAndOffdDevice(hypre_ParCSRMatrix *A)
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag);
HYPRE_Int A_diag_nnz = hypre_CSRMatrixNumNonzeros(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd);
HYPRE_Int A_offd_nnz = hypre_CSRMatrixNumNonzeros(A_offd);
hypre_CSRMatrix *B;
HYPRE_Int B_nrows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int B_ncols = hypre_CSRMatrixNumCols(A_diag) + hypre_CSRMatrixNumCols(A_offd);
HYPRE_Int B_nnz = A_diag_nnz + A_offd_nnz;
HYPRE_Int *B_ii = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE);
HYPRE_Int *B_j = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE);
HYPRE_Complex *B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE);
// Adiag
HYPRE_Int *A_diag_ii = hypreDevice_CsrRowPtrsToIndices(B_nrows, A_diag_nnz, A_diag_i);
HYPRE_THRUST_CALL( copy_n,
thrust::make_zip_iterator(thrust::make_tuple(A_diag_ii, A_diag_j, A_diag_a)),
A_diag_nnz,
thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_j, B_a)) );
hypre_TFree(A_diag_ii, HYPRE_MEMORY_DEVICE);
// Aoffd
HYPRE_Int *A_offd_ii = hypreDevice_CsrRowPtrsToIndices(B_nrows, A_offd_nnz, A_offd_i);
HYPRE_THRUST_CALL( copy_n,
thrust::make_zip_iterator(thrust::make_tuple(A_offd_ii, A_offd_a)),
A_offd_nnz,
thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_a)) + A_diag_nnz );
hypre_TFree(A_offd_ii, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( transform,
A_offd_j,
A_offd_j + A_offd_nnz,
thrust::make_constant_iterator(hypre_CSRMatrixNumCols(A_diag)),
B_j + A_diag_nnz,
thrust::plus<HYPRE_Int>() );
// B
HYPRE_THRUST_CALL( stable_sort_by_key,
B_ii,
B_ii + B_nnz,
thrust::make_zip_iterator(thrust::make_tuple(B_j, B_a)) );
HYPRE_Int *B_i = hypreDevice_CsrRowIndicesToPtrs(B_nrows, B_nnz, B_ii);
hypre_TFree(B_ii, HYPRE_MEMORY_DEVICE);
B = hypre_CSRMatrixCreate(B_nrows, B_ncols, B_nnz);
hypre_CSRMatrixI(B) = B_i;
hypre_CSRMatrixJ(B) = B_j;
hypre_CSRMatrixData(B) = B_a;
hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE;
return B;
}
#endif
/* return B = [Adiag, Aoffd; E] */
#if 1
HYPRE_Int
hypre_ConcatDiagOffdAndExtDevice(hypre_ParCSRMatrix *A,
hypre_CSRMatrix *E,
hypre_CSRMatrix **B_ptr,
HYPRE_Int *num_cols_offd_ptr,
HYPRE_BigInt **cols_map_offd_ptr)
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
hypre_CSRMatrix *E_diag, *E_offd, *B;
HYPRE_Int *cols_offd_map, num_cols_offd;
HYPRE_BigInt *cols_map_offd;
hypre_CSRMatrixSplitDevice(E, hypre_ParCSRMatrixFirstColDiag(A), hypre_ParCSRMatrixLastColDiag(A),
hypre_CSRMatrixNumCols(A_offd), hypre_ParCSRMatrixDeviceColMapOffd(A),
&cols_offd_map, &num_cols_offd, &cols_map_offd, &E_diag, &E_offd);
B = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumRows(A) + hypre_CSRMatrixNumRows(E),
hypre_ParCSRMatrixNumCols(A) + num_cols_offd,
hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd) +
hypre_CSRMatrixNumNonzeros(E));
hypre_CSRMatrixInitialize_v2(B, 0, HYPRE_MEMORY_DEVICE);
hypreDevice_GetRowNnz(hypre_ParCSRMatrixNumRows(A), NULL, hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixI(A_offd), hypre_CSRMatrixI(B));
HYPRE_THRUST_CALL( exclusive_scan,
hypre_CSRMatrixI(B),
hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1,
hypre_CSRMatrixI(B) );
dim3 bDim = hypre_GetDefaultDeviceBlockDimension();
dim3 gDim = hypre_GetDefaultDeviceGridDimension(hypre_ParCSRMatrixNumRows(A), "warp", bDim);
HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd,
gDim, bDim,
hypre_CSRMatrixNumRows(A_diag),
hypre_CSRMatrixNumCols(A_diag),
hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixJ(A_diag),
hypre_CSRMatrixData(A_diag),
hypre_CSRMatrixI(A_offd),
hypre_CSRMatrixJ(A_offd),
hypre_CSRMatrixData(A_offd),
cols_offd_map,
hypre_CSRMatrixI(B),
hypre_CSRMatrixJ(B),
hypre_CSRMatrixData(B) );
hypre_TFree(cols_offd_map, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(E) + 1,
HYPRE_Int, hypre_CSRMatrixNumRows(E),
HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( transform,
hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1,
hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + hypre_CSRMatrixNumRows(E) + 1,
thrust::make_constant_iterator(hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(
A_offd)),
hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1,
thrust::plus<HYPRE_Int>() );
gDim = hypre_GetDefaultDeviceGridDimension(hypre_CSRMatrixNumRows(E), "warp", bDim);
hypre_assert(hypre_CSRMatrixNumCols(E_diag) == hypre_CSRMatrixNumCols(A_diag));
HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd,
gDim, bDim,
hypre_CSRMatrixNumRows(E_diag),
hypre_CSRMatrixNumCols(E_diag),
hypre_CSRMatrixI(E_diag),
hypre_CSRMatrixJ(E_diag),
hypre_CSRMatrixData(E_diag),
hypre_CSRMatrixI(E_offd),
hypre_CSRMatrixJ(E_offd),
hypre_CSRMatrixData(E_offd),
NULL,
hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A),
hypre_CSRMatrixJ(B),
hypre_CSRMatrixData(B) );
hypre_CSRMatrixDestroy(E_diag);
hypre_CSRMatrixDestroy(E_offd);
*B_ptr = B;
*num_cols_offd_ptr = num_cols_offd;
*cols_map_offd_ptr = cols_map_offd;
return hypre_error_flag;
}
#else
HYPRE_Int
hypre_ConcatDiagOffdAndExtDevice(hypre_ParCSRMatrix *A,
hypre_CSRMatrix *E,
hypre_CSRMatrix **B_ptr,
HYPRE_Int *num_cols_offd_ptr,
HYPRE_BigInt **cols_map_offd_ptr)
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int A_nrows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int A_ncols = hypre_CSRMatrixNumCols(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag);
HYPRE_Int A_diag_nnz = hypre_CSRMatrixNumNonzeros(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd);
HYPRE_Int A_offd_nnz = hypre_CSRMatrixNumNonzeros(A_offd);
HYPRE_BigInt first_col_A = hypre_ParCSRMatrixFirstColDiag(A);
HYPRE_BigInt last_col_A = hypre_ParCSRMatrixLastColDiag(A);
HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A);
HYPRE_Int *E_i = hypre_CSRMatrixI(E);
HYPRE_BigInt *E_bigj = hypre_CSRMatrixBigJ(E);
HYPRE_Complex *E_a = hypre_CSRMatrixData(E);
HYPRE_Int E_nrows = hypre_CSRMatrixNumRows(E);
HYPRE_Int E_nnz = hypre_CSRMatrixNumNonzeros(E);
HYPRE_Int E_diag_nnz, E_offd_nnz;
hypre_CSRMatrix *B;
HYPRE_Int B_nnz = A_diag_nnz + A_offd_nnz + E_nnz;
HYPRE_Int *B_ii = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE);
HYPRE_Int *B_j = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE);
HYPRE_Complex *B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE);
// E
hypre_CSRMatrixSplitDevice_core(0, E_nrows, E_nnz, NULL, E_bigj, NULL, NULL, first_col_A,
last_col_A, num_cols_offd_A,
NULL, NULL, NULL, NULL, &E_diag_nnz, NULL, NULL, NULL, NULL, &E_offd_nnz,
NULL, NULL, NULL, NULL);
HYPRE_Int *cols_offd_map, num_cols_offd;
HYPRE_BigInt *cols_map_offd;
HYPRE_Int *E_ii = hypreDevice_CsrRowPtrsToIndices(E_nrows, E_nnz, E_i);
hypre_CSRMatrixSplitDevice_core(1,
E_nrows, E_nnz, E_ii, E_bigj, E_a, NULL,
first_col_A, last_col_A, num_cols_offd_A, col_map_offd_A,
&cols_offd_map, &num_cols_offd, &cols_map_offd,
&E_diag_nnz,
B_ii + A_diag_nnz + A_offd_nnz,
B_j + A_diag_nnz + A_offd_nnz,
B_a + A_diag_nnz + A_offd_nnz,
NULL,
&E_offd_nnz,
B_ii + A_diag_nnz + A_offd_nnz + E_diag_nnz,
B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz,
B_a + A_diag_nnz + A_offd_nnz + E_diag_nnz,
NULL);
hypre_TFree(E_ii, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( transform,
B_ii + A_diag_nnz + A_offd_nnz,
B_ii + B_nnz,
thrust::make_constant_iterator(A_nrows),
B_ii + A_diag_nnz + A_offd_nnz,
thrust::plus<HYPRE_Int>() );
// Adiag
HYPRE_Int *A_diag_ii = hypreDevice_CsrRowPtrsToIndices(A_nrows, A_diag_nnz, A_diag_i);
HYPRE_THRUST_CALL( copy_n,
thrust::make_zip_iterator(thrust::make_tuple(A_diag_ii, A_diag_j, A_diag_a)),
A_diag_nnz,
thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_j, B_a)) );
hypre_TFree(A_diag_ii, HYPRE_MEMORY_DEVICE);
// Aoffd
HYPRE_Int *A_offd_ii = hypreDevice_CsrRowPtrsToIndices(A_nrows, A_offd_nnz, A_offd_i);
HYPRE_THRUST_CALL( copy_n,
thrust::make_zip_iterator(thrust::make_tuple(A_offd_ii, A_offd_a)),
A_offd_nnz,
thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_a)) + A_diag_nnz );
hypre_TFree(A_offd_ii, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( gather,
A_offd_j,
A_offd_j + A_offd_nnz,
cols_offd_map,
B_j + A_diag_nnz);
hypre_TFree(cols_offd_map, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( transform,
B_j + A_diag_nnz,
B_j + A_diag_nnz + A_offd_nnz,
thrust::make_constant_iterator(A_ncols),
B_j + A_diag_nnz,
thrust::plus<HYPRE_Int>() );
HYPRE_THRUST_CALL( transform,
B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz,
B_j + B_nnz,
thrust::make_constant_iterator(A_ncols),
B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz,
thrust::plus<HYPRE_Int>() );
// B
HYPRE_THRUST_CALL( stable_sort_by_key,
B_ii,
B_ii + B_nnz,
thrust::make_zip_iterator(thrust::make_tuple(B_j, B_a)) );
HYPRE_Int *B_i = hypreDevice_CsrRowIndicesToPtrs(A_nrows + E_nrows, B_nnz, B_ii);
hypre_TFree(B_ii, HYPRE_MEMORY_DEVICE);
B = hypre_CSRMatrixCreate(A_nrows + E_nrows, A_ncols + num_cols_offd, B_nnz);
hypre_CSRMatrixI(B) = B_i;
hypre_CSRMatrixJ(B) = B_j;
hypre_CSRMatrixData(B) = B_a;
hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE;
*B_ptr = B;
*num_cols_offd_ptr = num_cols_offd;
*cols_map_offd_ptr = cols_map_offd;
return hypre_error_flag;
}
#endif
HYPRE_Int
hypre_ParCSRMatrixGetRowDevice( hypre_ParCSRMatrix *mat,
HYPRE_BigInt row,
HYPRE_Int *size,
HYPRE_BigInt **col_ind,
HYPRE_Complex **values )
{
HYPRE_Int nrows, local_row;
HYPRE_BigInt row_start, row_end;
hypre_CSRMatrix *Aa;
hypre_CSRMatrix *Ba;
if (!mat)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
Aa = (hypre_CSRMatrix *) hypre_ParCSRMatrixDiag(mat);
Ba = (hypre_CSRMatrix *) hypre_ParCSRMatrixOffd(mat);
if (hypre_ParCSRMatrixGetrowactive(mat))
{
return (-1);
}
hypre_ParCSRMatrixGetrowactive(mat) = 1;
row_start = hypre_ParCSRMatrixFirstRowIndex(mat);
row_end = hypre_ParCSRMatrixLastRowIndex(mat) + 1;
nrows = row_end - row_start;
if (row < row_start || row >= row_end)
{
return (-1);
}
local_row = row - row_start;
/* if buffer is not allocated and some information is requested, allocate buffer with the max row_nnz */
if ( !hypre_ParCSRMatrixRowvalues(mat) && (col_ind || values) )
{
HYPRE_Int max_row_nnz;
HYPRE_Int *row_nnz = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_DEVICE);
hypreDevice_GetRowNnz(nrows, NULL, hypre_CSRMatrixI(Aa), hypre_CSRMatrixI(Ba), row_nnz);
hypre_TMemcpy(size, row_nnz + local_row, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
max_row_nnz = HYPRE_THRUST_CALL(reduce, row_nnz, row_nnz + nrows, 0, thrust::maximum<HYPRE_Int>());
/*
HYPRE_Int *max_row_nnz_d = HYPRE_THRUST_CALL(max_element, row_nnz, row_nnz + nrows);
hypre_TMemcpy( &max_row_nnz, max_row_nnz_d,
HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE );
*/
hypre_TFree(row_nnz, HYPRE_MEMORY_DEVICE);
hypre_ParCSRMatrixRowvalues(mat) =
(HYPRE_Complex *) hypre_TAlloc(HYPRE_Complex, max_row_nnz, hypre_ParCSRMatrixMemoryLocation(mat));
hypre_ParCSRMatrixRowindices(mat) =
(HYPRE_BigInt *) hypre_TAlloc(HYPRE_BigInt, max_row_nnz, hypre_ParCSRMatrixMemoryLocation(mat));
}
else
{
HYPRE_Int *size_d = hypre_TAlloc(HYPRE_Int, 1, HYPRE_MEMORY_DEVICE);
hypreDevice_GetRowNnz(1, NULL, hypre_CSRMatrixI(Aa) + local_row, hypre_CSRMatrixI(Ba) + local_row,
size_d);
hypre_TMemcpy(size, size_d, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
hypre_TFree(size_d, HYPRE_MEMORY_DEVICE);
}
if (col_ind || values)
{
if (hypre_ParCSRMatrixDeviceColMapOffd(mat) == NULL)
{
hypre_ParCSRMatrixDeviceColMapOffd(mat) =
hypre_TAlloc(HYPRE_BigInt, hypre_CSRMatrixNumCols(Ba), HYPRE_MEMORY_DEVICE);
hypre_TMemcpy( hypre_ParCSRMatrixDeviceColMapOffd(mat),
hypre_ParCSRMatrixColMapOffd(mat),
HYPRE_BigInt,
hypre_CSRMatrixNumCols(Ba),
HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST );
}
hypreDevice_CopyParCSRRows( 1, NULL, -1, Ba != NULL,
hypre_ParCSRMatrixFirstColDiag(mat),
hypre_ParCSRMatrixDeviceColMapOffd(mat),
hypre_CSRMatrixI(Aa) + local_row,
hypre_CSRMatrixJ(Aa),
hypre_CSRMatrixData(Aa),
hypre_CSRMatrixI(Ba) + local_row,
hypre_CSRMatrixJ(Ba),
hypre_CSRMatrixData(Ba),
NULL,
hypre_ParCSRMatrixRowindices(mat),
hypre_ParCSRMatrixRowvalues(mat) );
}
if (col_ind)
{
*col_ind = hypre_ParCSRMatrixRowindices(mat);
}
if (values)
{
*values = hypre_ParCSRMatrixRowvalues(mat);
}
hypre_SyncComputeStream(hypre_handle());
return hypre_error_flag;
}
/* Get element-wise tolerances based on row norms for ParCSRMatrix
* NOTE: Keep the diagonal, i.e. elmt_tol = 0.0 for diagonals
* Output vectors have size nnz:
* elmt_tols_diag[j] = tol * (norm of row i) for j in [ A_diag_i[i] , A_diag_i[i+1] )
* elmt_tols_offd[j] = tol * (norm of row i) for j in [ A_offd_i[i] , A_offd_i[i+1] )
* type == -1, infinity norm,
* 1, 1-norm
* 2, 2-norm
*/
template<HYPRE_Int type>
__global__ void
hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols( HYPRE_Int nrows,
HYPRE_Real tol,
HYPRE_Int *A_diag_i,
HYPRE_Int *A_diag_j,
HYPRE_Complex *A_diag_a,
HYPRE_Int *A_offd_i,
HYPRE_Complex *A_offd_a,
HYPRE_Real *elmt_tols_diag,
HYPRE_Real *elmt_tols_offd)
{
HYPRE_Int row_i = hypre_cuda_get_grid_warp_id<1, 1>();
if (row_i >= nrows)
{
return;
}
HYPRE_Int lane = hypre_cuda_get_lane_id<1>();
HYPRE_Int p_diag, p_offd, q_diag, q_offd;
/* sum row norm over diag part */
if (lane < 2)
{
p_diag = read_only_load(A_diag_i + row_i + lane);
}
q_diag = __shfl_sync(HYPRE_WARP_FULL_MASK, p_diag, 1);
p_diag = __shfl_sync(HYPRE_WARP_FULL_MASK, p_diag, 0);
HYPRE_Real row_norm_i = 0.0;
for (HYPRE_Int j = p_diag + lane; j < q_diag; j += HYPRE_WARP_SIZE)
{
HYPRE_Complex val = A_diag_a[j];
if (type == -1)
{
row_norm_i = hypre_max(row_norm_i, hypre_cabs(val));
}
else if (type == 1)
{
row_norm_i += hypre_cabs(val);
}
else if (type == 2)
{
row_norm_i += val * val;
}
}
/* sum row norm over offd part */
if (lane < 2)
{
p_offd = read_only_load(A_offd_i + row_i + lane);
}
q_offd = __shfl_sync(HYPRE_WARP_FULL_MASK, p_offd, 1);
p_offd = __shfl_sync(HYPRE_WARP_FULL_MASK, p_offd, 0);
for (HYPRE_Int j = p_offd + lane; j < q_offd; j += HYPRE_WARP_SIZE)
{
HYPRE_Complex val = A_offd_a[j];
if (type == -1)
{
row_norm_i = hypre_max(row_norm_i, hypre_cabs(val));
}
else if (type == 1)
{
row_norm_i += hypre_cabs(val);
}
else if (type == 2)
{
row_norm_i += val * val;
}
}
/* allreduce to get the row norm on all threads */
if (type == -1)
{
row_norm_i = warp_allreduce_max(row_norm_i);
}
else
{
row_norm_i = warp_allreduce_sum(row_norm_i);
}
if (type == 2)
{
row_norm_i = sqrt(row_norm_i);
}
/* set elmt_tols_diag */
for (HYPRE_Int j = p_diag + lane; j < q_diag; j += HYPRE_WARP_SIZE)
{
HYPRE_Int col = A_diag_j[j];
/* elmt_tol = 0.0 ensures diagonal will be kept */
if (col == row_i)
{
elmt_tols_diag[j] = 0.0;
}
else
{
elmt_tols_diag[j] = tol * row_norm_i;
}
}
/* set elmt_tols_offd */
for (HYPRE_Int j = p_offd + lane; j < q_offd; j += HYPRE_WARP_SIZE)
{
elmt_tols_offd[j] = tol * row_norm_i;
}
}
/* drop the entries that are not on the diagonal and smaller than:
* type 0: tol
* type 1: tol*(1-norm of row)
* type 2: tol*(2-norm of row)
* type -1: tol*(infinity norm of row) */
HYPRE_Int
hypre_ParCSRMatrixDropSmallEntriesDevice( hypre_ParCSRMatrix *A,
HYPRE_Complex tol,
HYPRE_Int type)
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *h_col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A);
HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A);
HYPRE_Real *elmt_tols_diag = NULL;
HYPRE_Real *elmt_tols_offd = NULL;
if (col_map_offd_A == NULL)
{
col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(col_map_offd_A, h_col_map_offd_A, HYPRE_BigInt, num_cols_A_offd,
HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDeviceColMapOffd(A) = col_map_offd_A;
}
/* get elmement-wise tolerances if needed */
if (type != 0)
{
elmt_tols_diag = hypre_TAlloc(HYPRE_Real, hypre_CSRMatrixNumNonzeros(A_diag), HYPRE_MEMORY_DEVICE);
elmt_tols_offd = hypre_TAlloc(HYPRE_Real, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE);
}
dim3 bDim = hypre_GetDefaultDeviceBlockDimension();
dim3 gDim = hypre_GetDefaultDeviceGridDimension(hypre_CSRMatrixNumRows(A_diag), "warp", bDim);
if (type == -1)
{
HYPRE_CUDA_LAUNCH( hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols < -1 >, gDim, bDim,
hypre_CSRMatrixNumRows(A_diag), tol, hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd),
hypre_CSRMatrixData(A_offd), elmt_tols_diag, elmt_tols_offd);
}
if (type == 1)
{
HYPRE_CUDA_LAUNCH( hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols<1>, gDim, bDim,
hypre_CSRMatrixNumRows(A_diag), tol, hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd),
hypre_CSRMatrixData(A_offd), elmt_tols_diag, elmt_tols_offd);
}
if (type == 2)
{
HYPRE_CUDA_LAUNCH( hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols<2>, gDim, bDim,
hypre_CSRMatrixNumRows(A_diag), tol, hypre_CSRMatrixI(A_diag),
hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd),
hypre_CSRMatrixData(A_offd), elmt_tols_diag, elmt_tols_offd);
}
/* drop entries from diag and offd CSR matrices */
hypre_CSRMatrixDropSmallEntriesDevice(A_diag, tol, elmt_tols_diag);
hypre_CSRMatrixDropSmallEntriesDevice(A_offd, tol, elmt_tols_offd);
hypre_ParCSRMatrixSetNumNonzeros(A);
hypre_ParCSRMatrixDNumNonzeros(A) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(A);
/* squeeze out zero columns of A_offd */
HYPRE_Int *tmp_j, *tmp_end, num_cols_A_offd_new;
tmp_j = hypre_TAlloc(HYPRE_Int, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(tmp_j, hypre_CSRMatrixJ(A_offd), HYPRE_Int, hypre_CSRMatrixNumNonzeros(A_offd),
HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( sort,
tmp_j,
tmp_j + hypre_CSRMatrixNumNonzeros(A_offd) );
tmp_end = HYPRE_THRUST_CALL( unique,
tmp_j,
tmp_j + hypre_CSRMatrixNumNonzeros(A_offd) );
num_cols_A_offd_new = tmp_end - tmp_j;
hypre_assert(num_cols_A_offd_new <= num_cols_A_offd);
if (num_cols_A_offd_new < num_cols_A_offd)
{
hypre_CSRMatrixNumCols(A_offd) = num_cols_A_offd_new;
HYPRE_Int *offd_mark = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_DEVICE);
HYPRE_BigInt *col_map_offd_A_new = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd_new,
HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( scatter,
thrust::counting_iterator<HYPRE_Int>(0),
thrust::counting_iterator<HYPRE_Int>(num_cols_A_offd_new),
tmp_j,
offd_mark );
HYPRE_THRUST_CALL( gather,
hypre_CSRMatrixJ(A_offd),
hypre_CSRMatrixJ(A_offd) + hypre_CSRMatrixNumNonzeros(A_offd),
offd_mark,
hypre_CSRMatrixJ(A_offd) );
HYPRE_THRUST_CALL( gather,
tmp_j,
tmp_j + num_cols_A_offd_new,
col_map_offd_A,
col_map_offd_A_new );
hypre_TFree(offd_mark, HYPRE_MEMORY_DEVICE);
hypre_TFree(col_map_offd_A, HYPRE_MEMORY_DEVICE);
hypre_TFree(h_col_map_offd_A, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDeviceColMapOffd(A) = col_map_offd_A_new;
hypre_ParCSRMatrixColMapOffd(A) = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd_new,
HYPRE_MEMORY_HOST);
hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(A), col_map_offd_A_new, HYPRE_BigInt,
num_cols_A_offd_new,
HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
}
if (type != 0)
{
hypre_TFree(elmt_tols_diag, HYPRE_MEMORY_DEVICE);
hypre_TFree(elmt_tols_offd, HYPRE_MEMORY_DEVICE);
}
hypre_TFree(tmp_j, HYPRE_MEMORY_DEVICE);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixTransposeDevice
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRMatrixTransposeDevice( hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix **AT_ptr,
HYPRE_Int data )
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
hypre_CSRMatrix *A_diagT;
hypre_CSRMatrix *AT_offd;
HYPRE_Int num_procs;
HYPRE_Int num_cols_offd_AT = 0;
HYPRE_BigInt *col_map_offd_AT = NULL;
hypre_ParCSRMatrix *AT;
hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs);
if (num_procs > 1)
{
void *request;
hypre_CSRMatrix *A_offdT, *Aext;
HYPRE_Int *Aext_ii, *Aext_j, Aext_nnz;
HYPRE_Complex *Aext_data;
HYPRE_BigInt *tmp_bigj;
hypre_CSRMatrixTranspose(A_offd, &A_offdT, data);
hypre_CSRMatrixBigJ(A_offdT) = hypre_TAlloc(HYPRE_BigInt, hypre_CSRMatrixNumNonzeros(A_offdT),
HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( transform,
hypre_CSRMatrixJ(A_offdT),
hypre_CSRMatrixJ(A_offdT) + hypre_CSRMatrixNumNonzeros(A_offdT),
thrust::make_constant_iterator(hypre_ParCSRMatrixFirstRowIndex(A)),
hypre_CSRMatrixBigJ(A_offdT),
thrust::plus<HYPRE_BigInt>() );
if (!hypre_ParCSRMatrixCommPkg(A))
{
hypre_MatvecCommPkgCreate(A);
}
hypre_ExchangeExternalRowsDeviceInit(A_offdT, hypre_ParCSRMatrixCommPkg(A), data, &request);
hypre_CSRMatrixTranspose(A_diag, &A_diagT, data);
Aext = hypre_ExchangeExternalRowsDeviceWait(request);
hypre_CSRMatrixDestroy(A_offdT);
// Aext contains offd of AT
Aext_nnz = hypre_CSRMatrixNumNonzeros(Aext);
Aext_ii = hypreDevice_CsrRowPtrsToIndices(hypre_CSRMatrixNumRows(Aext), Aext_nnz,
hypre_CSRMatrixI(Aext));
hypre_ParCSRCommPkgCopySendMapElmtsToDevice(hypre_ParCSRMatrixCommPkg(A));
HYPRE_THRUST_CALL( gather,
Aext_ii,
Aext_ii + Aext_nnz,
hypre_ParCSRCommPkgDeviceSendMapElmts(hypre_ParCSRMatrixCommPkg(A)),
Aext_ii );
tmp_bigj = hypre_TAlloc(HYPRE_BigInt, Aext_nnz, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(tmp_bigj, hypre_CSRMatrixBigJ(Aext), HYPRE_BigInt, Aext_nnz, HYPRE_MEMORY_DEVICE,
HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( sort,
tmp_bigj,
tmp_bigj + Aext_nnz );
HYPRE_BigInt *new_end = HYPRE_THRUST_CALL( unique,
tmp_bigj,
tmp_bigj + Aext_nnz );
num_cols_offd_AT = new_end - tmp_bigj;
col_map_offd_AT = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(col_map_offd_AT, tmp_bigj, HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_DEVICE,
HYPRE_MEMORY_DEVICE);
hypre_TFree(tmp_bigj, HYPRE_MEMORY_DEVICE);
Aext_j = hypre_TAlloc(HYPRE_Int, Aext_nnz, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( lower_bound,
col_map_offd_AT,
col_map_offd_AT + num_cols_offd_AT,
hypre_CSRMatrixBigJ(Aext),
hypre_CSRMatrixBigJ(Aext) + Aext_nnz,
Aext_j );
Aext_data = hypre_CSRMatrixData(Aext);
hypre_CSRMatrixData(Aext) = NULL;
hypre_CSRMatrixDestroy(Aext);
if (data)
{
hypreDevice_StableSortByTupleKey(Aext_nnz, Aext_ii, Aext_j, Aext_data, 0);
}
else
{
HYPRE_THRUST_CALL( stable_sort,
thrust::make_zip_iterator(thrust::make_tuple(Aext_ii, Aext_j)),
thrust::make_zip_iterator(thrust::make_tuple(Aext_ii, Aext_j)) + Aext_nnz );
}
AT_offd = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumCols(A), num_cols_offd_AT, Aext_nnz);
hypre_CSRMatrixJ(AT_offd) = Aext_j;
hypre_CSRMatrixData(AT_offd) = Aext_data;
hypre_CSRMatrixInitialize_v2(AT_offd, 0, HYPRE_MEMORY_DEVICE);
hypreDevice_CsrRowIndicesToPtrs_v2(hypre_CSRMatrixNumRows(AT_offd), Aext_nnz, Aext_ii,
hypre_CSRMatrixI(AT_offd));
hypre_TFree(Aext_ii, HYPRE_MEMORY_DEVICE);
}
else
{
hypre_CSRMatrixTransposeDevice(A_diag, &A_diagT, data);
AT_offd = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumCols(A), 0, 0);
hypre_CSRMatrixInitialize_v2(AT_offd, 0, HYPRE_MEMORY_DEVICE);
}
AT = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumCols(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixColStarts(A),
hypre_ParCSRMatrixRowStarts(A),
num_cols_offd_AT,
hypre_CSRMatrixNumNonzeros(A_diagT),
hypre_CSRMatrixNumNonzeros(AT_offd));
hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(AT));
hypre_ParCSRMatrixDiag(AT) = A_diagT;
hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(AT));
hypre_ParCSRMatrixOffd(AT) = AT_offd;
if (num_cols_offd_AT)
{
hypre_ParCSRMatrixDeviceColMapOffd(AT) = col_map_offd_AT;
hypre_ParCSRMatrixColMapOffd(AT) = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST);
hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(AT), col_map_offd_AT, HYPRE_BigInt, num_cols_offd_AT,
HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
}
*AT_ptr = AT;
return hypre_error_flag;
}
HYPRE_Int
hypre_ParCSRMatrixAddDevice( HYPRE_Complex alpha,
hypre_ParCSRMatrix *A,
HYPRE_Complex beta,
hypre_ParCSRMatrix *B,
hypre_ParCSRMatrix **C_ptr )
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B);
hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B);
HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd);
HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd);
HYPRE_Int num_cols_offd_C = 0;
HYPRE_BigInt *d_col_map_offd_C = NULL;
HYPRE_Int num_procs;
hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs);
hypre_CSRMatrix *C_diag = hypre_CSRMatrixAddDevice(alpha, A_diag, beta, B_diag);
hypre_CSRMatrix *C_offd;
//if (num_cols_offd_A || num_cols_offd_B)
if (num_procs > 1)
{
hypre_ParCSRMatrixCopyColMapOffdToDevice(A);
hypre_ParCSRMatrixCopyColMapOffdToDevice(B);
HYPRE_BigInt *tmp = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A + num_cols_offd_B,
HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(tmp, hypre_ParCSRMatrixDeviceColMapOffd(A), HYPRE_BigInt,
num_cols_offd_A, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(tmp + num_cols_offd_A, hypre_ParCSRMatrixDeviceColMapOffd(B), HYPRE_BigInt,
num_cols_offd_B, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE);
HYPRE_THRUST_CALL( sort, tmp, tmp + num_cols_offd_A + num_cols_offd_B );
HYPRE_BigInt *new_end = HYPRE_THRUST_CALL( unique, tmp, tmp + num_cols_offd_A + num_cols_offd_B );
num_cols_offd_C = new_end - tmp;
d_col_map_offd_C = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(d_col_map_offd_C, tmp, HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_DEVICE,
HYPRE_MEMORY_DEVICE);
/* reuse memory of tmp */
HYPRE_Int *offd_A2C = (HYPRE_Int *) tmp;
HYPRE_Int *offd_B2C = offd_A2C + num_cols_offd_A;
HYPRE_THRUST_CALL( lower_bound,
d_col_map_offd_C,
d_col_map_offd_C + num_cols_offd_C,
hypre_ParCSRMatrixDeviceColMapOffd(A),
hypre_ParCSRMatrixDeviceColMapOffd(A) + num_cols_offd_A,
offd_A2C );
HYPRE_THRUST_CALL( lower_bound,
d_col_map_offd_C,
d_col_map_offd_C + num_cols_offd_C,
hypre_ParCSRMatrixDeviceColMapOffd(B),
hypre_ParCSRMatrixDeviceColMapOffd(B) + num_cols_offd_B,
offd_B2C );
HYPRE_Int *C_offd_i, *C_offd_j, nnzC_offd;
HYPRE_Complex *C_offd_a;
hypreDevice_CSRSpAdd( hypre_CSRMatrixNumRows(A_offd),
hypre_CSRMatrixNumRows(B_offd),
num_cols_offd_C,
hypre_CSRMatrixNumNonzeros(A_offd),
hypre_CSRMatrixNumNonzeros(B_offd),
hypre_CSRMatrixI(A_offd),
hypre_CSRMatrixJ(A_offd),
alpha,
hypre_CSRMatrixData(A_offd),
offd_A2C,
hypre_CSRMatrixI(B_offd),
hypre_CSRMatrixJ(B_offd),
beta,
hypre_CSRMatrixData(B_offd),
offd_B2C,
NULL,
&nnzC_offd,
&C_offd_i,
&C_offd_j,
&C_offd_a );
hypre_TFree(tmp, HYPRE_MEMORY_DEVICE);
C_offd = hypre_CSRMatrixCreate(hypre_CSRMatrixNumRows(A_offd), num_cols_offd_C, nnzC_offd);
hypre_CSRMatrixI(C_offd) = C_offd_i;
hypre_CSRMatrixJ(C_offd) = C_offd_j;
hypre_CSRMatrixData(C_offd) = C_offd_a;
hypre_CSRMatrixMemoryLocation(C_offd) = HYPRE_MEMORY_DEVICE;
}
else
{
C_offd = hypre_CSRMatrixCreate(hypre_CSRMatrixNumRows(A_offd), 0, 0);
hypre_CSRMatrixInitialize_v2(C_offd, 0, HYPRE_MEMORY_DEVICE);
}
/* Create ParCSRMatrix C */
hypre_ParCSRMatrix *C = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixGlobalNumCols(A),
hypre_ParCSRMatrixRowStarts(A),
hypre_ParCSRMatrixColStarts(A),
num_cols_offd_C,
hypre_CSRMatrixNumNonzeros(C_diag),
hypre_CSRMatrixNumNonzeros(C_offd));
hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C));
hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C));
hypre_ParCSRMatrixDiag(C) = C_diag;
hypre_ParCSRMatrixOffd(C) = C_offd;
if (num_cols_offd_C)
{
hypre_ParCSRMatrixDeviceColMapOffd(C) = d_col_map_offd_C;
hypre_ParCSRMatrixColMapOffd(C) = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST);
hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(C), d_col_map_offd_C, HYPRE_BigInt, num_cols_offd_C,
HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE);
}
hypre_ParCSRMatrixSetNumNonzeros(C);
hypre_ParCSRMatrixDNumNonzeros(C) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(C);
/* create CommPkg of C */
hypre_MatvecCommPkgCreate(C);
*C_ptr = C;
return hypre_error_flag;
}
#endif // #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
/*--------------------------------------------------------------------------
* HYPRE_ParCSRDiagScale
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRDiagScaleVector( HYPRE_ParCSRMatrix HA,
HYPRE_ParVector Hy,
HYPRE_ParVector Hx )
{
hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) HA;
hypre_ParVector *y = (hypre_ParVector *) Hy;
hypre_ParVector *x = (hypre_ParVector *) Hx;
HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x));
HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y));
HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A));
HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A));
HYPRE_Int local_size = hypre_VectorSize(hypre_ParVectorLocalVector(x));
HYPRE_Int ierr = 0;
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypreDevice_DiagScaleVector(local_size, A_i, A_data, y_data, 0.0, x_data);
//hypre_SyncComputeStream(hypre_handle());
#else /* #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) */
HYPRE_Int i;
#if defined(HYPRE_USING_DEVICE_OPENMP)
#pragma omp target teams distribute parallel for private(i) is_device_ptr(x_data,y_data,A_data,A_i)
#elif defined(HYPRE_USING_OPENMP)
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < local_size; i++)
{
x_data[i] = y_data[i] / A_data[A_i[i]];
}
#endif /* #if defined(HYPRE_USING_CUDA) */
return ierr;
}
|
nr_direct.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
//#include <omp.h>
#include "config.h"
#include "cint.h"
#include "cint_funcs.h"
#include "vhf/nr_direct.h"
#define MIN(I,J) ((I) < (J) ? (I) : (J))
#define MAX(I,J) ((I) > (J) ? (I) : (J))
int GTOmax_shell_dim(const int *ao_loc, const int *shls_slice, int ncenter);
static int _max_cache_size(int (*intor)(), int *shls_slice, int *images_loc,
int *atm, int natm, int *bas, int nbas, double *env)
{
int i, n;
int i0 = shls_slice[0];
int i1 = shls_slice[1];
int shls[4];
int cache_size = 0;
for (i = i0; i < i1; i++) {
shls[0] = images_loc[i];
shls[1] = images_loc[i];
shls[2] = images_loc[i];
shls[3] = images_loc[i];
n = (*intor)(NULL, NULL, shls, atm, natm, bas, nbas, env, NULL, NULL);
cache_size = MAX(cache_size, n);
}
return cache_size;
}
static int _assemble_eris(double *eri_buf, int *images_loc,
int ishell, int jshell, int kshell, int lshell,
double cutoff, CVHFOpt *vhfopt, IntorEnvs *envs)
{
int *atm = envs->atm;
int *bas = envs->bas;
double *env = envs->env;
int natm = envs->natm;
int nbas = envs->nbas;
CINTOpt *cintopt = envs->cintopt;
const size_t Nbas = nbas;
const int *ao_loc = envs->ao_loc;
const int ish0 = images_loc[ishell];
const int jsh0 = images_loc[jshell];
const int ksh0 = images_loc[kshell];
const int lsh0 = images_loc[lshell];
const int jsh1 = images_loc[jshell+1];
const int ksh1 = images_loc[kshell+1];
const int lsh1 = images_loc[lshell+1];
const int i0 = ao_loc[ishell];
const int j0 = ao_loc[jshell];
const int k0 = ao_loc[kshell];
const int l0 = ao_loc[lshell];
const int i1 = ao_loc[ishell+1];
const int j1 = ao_loc[jshell+1];
const int k1 = ao_loc[kshell+1];
const int l1 = ao_loc[lshell+1];
const int di = i1 - i0;
const int dj = j1 - j0;
const int dk = k1 - k0;
const int dl = l1 - l0;
const int dijkl = di * dj * dk * dl;
double *q_cond_ijij = vhfopt->q_cond;
double *q_cond_iijj = vhfopt->q_cond + Nbas*Nbas;
double *q_cond_ij, *q_cond_kl, *q_cond_ik, *q_cond_jk;
double *eri = eri_buf;
double *bufL = eri_buf + dijkl;
double *cache = bufL + dijkl;
int shls[4] = {ish0};
int n, jsh, ksh, lsh;
double kl_cutoff, jl_cutoff, il_cutoff;
int empty = 1;
for (n = 0; n < dijkl; n++) {
eri[n] = 0;
}
q_cond_ij = q_cond_ijij + ish0 * Nbas;
q_cond_ik = q_cond_iijj + ish0 * Nbas;
for (jsh = jsh0; jsh < jsh1; jsh++) {
if (q_cond_ij[jsh] < cutoff) {
continue;
}
kl_cutoff = cutoff / q_cond_ij[jsh];
q_cond_jk = q_cond_iijj + jsh * Nbas;
for (ksh = ksh0; ksh < ksh1; ksh++) {
if (q_cond_ik[ksh] < cutoff ||
q_cond_jk[ksh] < cutoff) {
continue;
}
q_cond_kl = q_cond_ijij + ksh * Nbas;
jl_cutoff = cutoff / q_cond_ik[ksh];
il_cutoff = cutoff / q_cond_jk[ksh];
for (lsh = lsh0; lsh < lsh1; lsh++) {
if (q_cond_kl[lsh] < kl_cutoff ||
q_cond_jk[lsh] < jl_cutoff ||
q_cond_ik[lsh] < il_cutoff) {
continue;
}
shls[1] = jsh;
shls[2] = ksh;
shls[3] = lsh;
if (int2e_sph(bufL, NULL, shls, atm, natm,
bas, nbas, env, cintopt, cache)) {
for (n = 0; n < dijkl; n++) {
eri[n] += bufL[n];
}
empty = 0;
}
}
}
}
return !empty;
}
void PBCVHF_contract_k_s1(double *vk, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
const int cell_j = bvk_cell_id[jsh];
const int cell_k = bvk_cell_id[ksh];
const int cell_l = bvk_cell_id[lsh];
const int jshp = cell0_shl_id[jsh];
const int kshp = cell0_shl_id[ksh];
const int lshp = cell0_shl_id[lsh];
const int dm_jk_off = dm_translation[cell_j * nkpts + cell_k];
const int nn0 = nbasp * nbasp;
double direct_scf_cutoff = vhfopt->direct_scf_cutoff;
double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp];
if (dm_jk_cond < direct_scf_cutoff) {
return;
} else {
direct_scf_cutoff /= dm_jk_cond;
}
if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh,
direct_scf_cutoff, vhfopt, envs)) {
return;
}
const int *ao_loc = envs->ao_loc;
const int naop = ao_loc[nbasp];
const int nn = naop * naop;
const int bn = naop * nbands;
const int knn = nn * nkpts;
const int bnn = bn * naop;
const int i0 = ao_loc[ish];
const int jp0 = ao_loc[jshp];
const int kp0 = ao_loc[kshp];
const int lp0 = ao_loc[lshp];
const int i1 = ao_loc[ish+1];
const int jp1 = ao_loc[jshp+1];
const int kp1 = ao_loc[kshp+1];
const int lp1 = ao_loc[lshp+1];
int idm, i, jp, kp, lp, n;
double sjk, qijkl;
double *dm_jk;
vk += cell_l * naop;
for (idm = 0; idm < n_dm; idm++) {
dm_jk = dms + dm_jk_off * nn + idm * knn;
n = 0;
for (lp = lp0; lp < lp1; lp++) {
for (kp = kp0; kp < kp1; kp++) {
for (jp = jp0; jp < jp1; jp++) {
sjk = dm_jk[jp*naop+kp];
for (i = i0; i < i1; i++, n++) {
qijkl = buf[n];
vk[i*bn+lp] += qijkl * sjk;
} } }
}
vk += bnn;
}
}
static void contract_k_s2_kgtl(double *vk, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
const int cell_j = bvk_cell_id[jsh];
const int cell_k = bvk_cell_id[ksh];
const int cell_l = bvk_cell_id[lsh];
const int jshp = cell0_shl_id[jsh];
const int kshp = cell0_shl_id[ksh];
const int lshp = cell0_shl_id[lsh];
const int dm_jk_off = dm_translation[cell_j*nkpts+cell_k];
const int dm_jl_off = dm_translation[cell_j*nkpts+cell_l];
const int nn0 = nbasp * nbasp;
double direct_scf_cutoff = vhfopt->direct_scf_cutoff;
double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp];
double dm_jl_cond = vhfopt->dm_cond[dm_jl_off*nn0 + jshp*nbasp+lshp];
double dm_cond_max = MAX(dm_jk_cond, dm_jl_cond);
if (dm_cond_max < direct_scf_cutoff) {
return;
} else {
direct_scf_cutoff /= dm_cond_max;
}
if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh,
direct_scf_cutoff, vhfopt, envs)) {
return;
}
const int *ao_loc = envs->ao_loc;
const int naop = ao_loc[nbasp];
const int nn = naop * naop;
const int bn = naop * nbands;
const int knn = nn * nkpts;
const int bnn = bn * naop;
const int i0 = ao_loc[ish];
const int jp0 = ao_loc[jshp];
const int kp0 = ao_loc[kshp];
const int lp0 = ao_loc[lshp];
const int i1 = ao_loc[ish+1];
const int jp1 = ao_loc[jshp+1];
const int kp1 = ao_loc[kshp+1];
const int lp1 = ao_loc[lshp+1];
int idm, i, jp, kp, lp, n;
double sjk, sjl, qijkl;
double *dm_jk, *dm_jl;
double *vk_ik = vk + cell_k * naop;
double *vk_il = vk + cell_l * naop;
for (idm = 0; idm < n_dm; idm++) {
dm_jk = dms + dm_jk_off * nn + idm * knn;
dm_jl = dms + dm_jl_off * nn + idm * knn;
n = 0;
for (lp = lp0; lp < lp1; lp++) {
for (kp = kp0; kp < kp1; kp++) {
for (jp = jp0; jp < jp1; jp++) {
sjk = dm_jk[jp*naop+kp];
sjl = dm_jl[jp*naop+lp];
for (i = i0; i < i1; i++, n++) {
qijkl = buf[n];
vk_il[i*bn+lp] += qijkl * sjk;
vk_ik[i*bn+kp] += qijkl * sjl;
} } }
}
vk_ik += bnn;
vk_il += bnn;
}
}
void PBCVHF_contract_k_s2kl(double *vk, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
if (ksh > lsh) {
contract_k_s2_kgtl(vk, dms, buf, n_dm, nkpts, nbands, nbasp,
ish, jsh, ksh, lsh, bvk_cell_id,
cell0_shl_id, images_loc,
dm_translation, vhfopt, envs);
} else if (ksh == lsh) {
PBCVHF_contract_k_s1(vk, dms, buf, n_dm, nkpts, nbands, nbasp,
ish, jsh, ksh, lsh, bvk_cell_id,
cell0_shl_id, images_loc,
dm_translation, vhfopt, envs);
}
}
void PBCVHF_contract_j_s1(double *vj, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
const int cell_j = bvk_cell_id[jsh];
const int cell_k = bvk_cell_id[ksh];
const int cell_l = bvk_cell_id[lsh];
const int jshp = cell0_shl_id[jsh];
const int kshp = cell0_shl_id[ksh];
const int lshp = cell0_shl_id[lsh];
const int dm_lk_off = dm_translation[cell_l * nkpts + cell_k];
const int nn0 = nbasp * nbasp;
double direct_scf_cutoff = vhfopt->direct_scf_cutoff;
double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp];
if (dm_lk_cond < direct_scf_cutoff) {
return;
} else {
direct_scf_cutoff /= dm_lk_cond;
}
if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh,
direct_scf_cutoff, vhfopt, envs)) {
return;
}
const int *ao_loc = envs->ao_loc;
const int naop = ao_loc[nbasp];
const int nn = naop * naop;
const int bn = naop * nbands;
const int knn = nn * nkpts;
const int bnn = bn * naop;
const int i0 = ao_loc[ish];
const int jp0 = ao_loc[jshp];
const int kp0 = ao_loc[kshp];
const int lp0 = ao_loc[lshp];
const int i1 = ao_loc[ish+1];
const int jp1 = ao_loc[jshp+1];
const int kp1 = ao_loc[kshp+1];
const int lp1 = ao_loc[lshp+1];
int idm, i, jp, kp, lp, n;
double slk, qijkl;
double *dm_lk;
vj += cell_j * naop;
for (idm = 0; idm < n_dm; idm++) {
dm_lk = dms + dm_lk_off * nn + idm * knn;
n = 0;
for (lp = lp0; lp < lp1; lp++) {
for (kp = kp0; kp < kp1; kp++) {
slk = dm_lk[lp*naop+kp];
for (jp = jp0; jp < jp1; jp++) {
for (i = i0; i < i1; i++, n++) {
qijkl = buf[n];
vj[i*bn+jp] += qijkl * slk;
} }
} }
vj += bnn;
}
}
static void contract_j_s2_kgtl(double *vj, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
const int cell_j = bvk_cell_id[jsh];
const int cell_k = bvk_cell_id[ksh];
const int cell_l = bvk_cell_id[lsh];
const int jshp = cell0_shl_id[jsh];
const int kshp = cell0_shl_id[ksh];
const int lshp = cell0_shl_id[lsh];
const int dm_lk_off = dm_translation[cell_l * nkpts + cell_k];
const int dm_kl_off = dm_translation[cell_k * nkpts + cell_l];
const int nn0 = nbasp * nbasp;
double direct_scf_cutoff = vhfopt->direct_scf_cutoff;
double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp];
double dm_kl_cond = vhfopt->dm_cond[dm_kl_off*nn0 + kshp*nbasp+lshp];
double dm_cond_max = dm_lk_cond + dm_kl_cond;
if (dm_cond_max < direct_scf_cutoff) {
return;
} else {
direct_scf_cutoff /= dm_cond_max;
}
if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh,
direct_scf_cutoff, vhfopt, envs)) {
return;
}
const int *ao_loc = envs->ao_loc;
const int naop = ao_loc[nbasp];
const int nn = naop * naop;
const int bn = naop * nbands;
const int knn = nn * nkpts;
const int bnn = bn * naop;
const int i0 = ao_loc[ish];
const int jp0 = ao_loc[jshp];
const int kp0 = ao_loc[kshp];
const int lp0 = ao_loc[lshp];
const int i1 = ao_loc[ish+1];
const int jp1 = ao_loc[jshp+1];
const int kp1 = ao_loc[kshp+1];
const int lp1 = ao_loc[lshp+1];
int idm, i, jp, kp, lp, n;
double slk, qijkl;
double *dm_lk, *dm_kl;
vj += cell_j * naop;
for (idm = 0; idm < n_dm; idm++) {
dm_lk = dms + dm_lk_off * nn + idm * knn;
dm_kl = dms + dm_kl_off * nn + idm * knn;
n = 0;
for (lp = lp0; lp < lp1; lp++) {
for (kp = kp0; kp < kp1; kp++) {
slk = dm_lk[lp*naop+kp] + dm_kl[kp*naop+lp];
for (jp = jp0; jp < jp1; jp++) {
for (i = i0; i < i1; i++, n++) {
qijkl = buf[n];
vj[i*bn+jp] += qijkl * slk;
} }
} }
vj += bnn;
}
}
void PBCVHF_contract_j_s2kl(double *vj, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
if (ksh > lsh) {
contract_j_s2_kgtl(vj, dms, buf, n_dm, nkpts, nbands, nbasp,
ish, jsh, ksh, lsh, bvk_cell_id,
cell0_shl_id, images_loc,
dm_translation, vhfopt, envs);
} else if (ksh == lsh) {
PBCVHF_contract_j_s1(vj, dms, buf, n_dm, nkpts, nbands, nbasp,
ish, jsh, ksh, lsh, bvk_cell_id,
cell0_shl_id, images_loc,
dm_translation, vhfopt, envs);
}
}
void PBCVHF_contract_jk_s1(double *jk, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
const int cell_j = bvk_cell_id[jsh];
const int cell_k = bvk_cell_id[ksh];
const int cell_l = bvk_cell_id[lsh];
const int jshp = cell0_shl_id[jsh];
const int kshp = cell0_shl_id[ksh];
const int lshp = cell0_shl_id[lsh];
const int dm_lk_off = dm_translation[cell_l * nkpts + cell_k];
const int dm_jk_off = dm_translation[cell_j * nkpts + cell_k];
const int nn0 = nbasp * nbasp;
double direct_scf_cutoff = vhfopt->direct_scf_cutoff;
double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp];
double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp];
double dm_cond_max = MAX(dm_lk_cond, dm_jk_cond);
if (dm_cond_max < direct_scf_cutoff) {
return;
} else {
direct_scf_cutoff /= dm_cond_max;
}
if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh,
direct_scf_cutoff, vhfopt, envs)) {
return;
}
const int *ao_loc = envs->ao_loc;
const int naop = ao_loc[nbasp];
const int nn = naop * naop;
const int bn = naop * nbands;
const int knn = nn * nkpts;
const int bnn = bn * naop;
const int i0 = ao_loc[ish];
const int jp0 = ao_loc[jshp];
const int kp0 = ao_loc[kshp];
const int lp0 = ao_loc[lshp];
const int i1 = ao_loc[ish+1];
const int jp1 = ao_loc[jshp+1];
const int kp1 = ao_loc[kshp+1];
const int lp1 = ao_loc[lshp+1];
double *vj = jk + cell_j * naop;
double *vk = jk + n_dm * bnn + cell_l * naop;
int idm, i, jp, kp, lp, n;
double slk, sjk, qijkl;
double *dm_lk, *dm_jk;
for (idm = 0; idm < n_dm; idm++) {
dm_lk = dms + dm_lk_off * nn + idm * knn;
dm_jk = dms + dm_jk_off * nn + idm * knn;
n = 0;
for (lp = lp0; lp < lp1; lp++) {
for (kp = kp0; kp < kp1; kp++) {
slk = dm_lk[lp*naop+kp];
for (jp = jp0; jp < jp1; jp++) {
sjk = dm_jk[jp*naop+kp];
for (i = i0; i < i1; i++, n++) {
qijkl = buf[n];
vj[i*bn+jp] += qijkl * slk;
vk[i*bn+lp] += qijkl * sjk;
}
}
} }
vj += bnn;
vk += bnn;
}
}
static void contract_jk_s2_kgtl(double *jk, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
const int cell_j = bvk_cell_id[jsh];
const int cell_k = bvk_cell_id[ksh];
const int cell_l = bvk_cell_id[lsh];
const int jshp = cell0_shl_id[jsh];
const int kshp = cell0_shl_id[ksh];
const int lshp = cell0_shl_id[lsh];
const int dm_jk_off = dm_translation[cell_j*nkpts+cell_k];
const int dm_jl_off = dm_translation[cell_j*nkpts+cell_l];
const int dm_lk_off = dm_translation[cell_l*nkpts+cell_k];
const int dm_kl_off = dm_translation[cell_k*nkpts+cell_l];
const int nn0 = nbasp * nbasp;
double direct_scf_cutoff = vhfopt->direct_scf_cutoff;
double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp];
double dm_jl_cond = vhfopt->dm_cond[dm_jl_off*nn0 + jshp*nbasp+lshp];
double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp];
double dm_kl_cond = vhfopt->dm_cond[dm_kl_off*nn0 + kshp*nbasp+lshp];
double dm_cond_max = MAX(dm_jk_cond, dm_jl_cond);
dm_cond_max = MAX(dm_cond_max, dm_lk_cond + dm_kl_cond);
if (dm_cond_max < direct_scf_cutoff) {
return;
} else {
direct_scf_cutoff /= dm_cond_max;
}
if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh,
direct_scf_cutoff, vhfopt, envs)) {
return;
}
const int *ao_loc = envs->ao_loc;
const int naop = ao_loc[nbasp];
const int nn = naop * naop;
const int bn = naop * nbands;
const int knn = nn * nkpts;
const int bnn = bn * naop;
const int i0 = ao_loc[ish];
const int jp0 = ao_loc[jshp];
const int kp0 = ao_loc[kshp];
const int lp0 = ao_loc[lshp];
const int i1 = ao_loc[ish+1];
const int jp1 = ao_loc[jshp+1];
const int kp1 = ao_loc[kshp+1];
const int lp1 = ao_loc[lshp+1];
double *vj = jk + cell_j * naop;
double *vk_ik = jk + n_dm * bnn + cell_k * naop;
double *vk_il = jk + n_dm * bnn + cell_l * naop;
int idm, i, jp, kp, lp, n;
double sjk, sjl, slk, qijkl;
double *dm_jk, *dm_jl, *dm_lk, *dm_kl;
for (idm = 0; idm < n_dm; idm++) {
dm_lk = dms + dm_lk_off * nn + idm * knn;
dm_kl = dms + dm_kl_off * nn + idm * knn;
dm_jk = dms + dm_jk_off * nn + idm * knn;
dm_jl = dms + dm_jl_off * nn + idm * knn;
n = 0;
for (lp = lp0; lp < lp1; lp++) {
for (kp = kp0; kp < kp1; kp++) {
slk = dm_lk[lp*naop+kp] + dm_kl[kp*naop+lp];
for (jp = jp0; jp < jp1; jp++) {
sjk = dm_jk[jp*naop+kp];
sjl = dm_jl[jp*naop+lp];
for (i = i0; i < i1; i++, n++) {
qijkl = buf[n];
vj[i*bn+jp] += qijkl * slk;
vk_il[i*bn+lp] += qijkl * sjk;
vk_ik[i*bn+kp] += qijkl * sjl;
} }
}
}
vj += bnn;
vk_ik += bnn;
vk_il += bnn;
}
}
void PBCVHF_contract_jk_s2kl(double *jk, double *dms, double *buf,
int n_dm, int nkpts, int nbands, int nbasp,
int ish, int jsh, int ksh, int lsh,
int *bvk_cell_id, int *cell0_shl_id,
int *images_loc, int *dm_translation,
CVHFOpt *vhfopt, IntorEnvs *envs)
{
if (ksh > lsh) {
contract_jk_s2_kgtl(jk, dms, buf, n_dm, nkpts, nbands, nbasp,
ish, jsh, ksh, lsh, bvk_cell_id,
cell0_shl_id, images_loc,
dm_translation, vhfopt, envs);
} else if (ksh == lsh) {
PBCVHF_contract_jk_s1(jk, dms, buf, n_dm, nkpts, nbands, nbasp,
ish, jsh, ksh, lsh, bvk_cell_id,
cell0_shl_id, images_loc,
dm_translation, vhfopt, envs);
}
}
/*
* shls_slice refers to the shells of entire sup-mol.
* bvk_ao_loc are ao_locs of bvk-cell basis appeared in supmol (some basis are removed)
* nbasp is the number of basis in primitive cell
* dm_translation utilizes the translation symmetry for density matrices (wrt the full bvk-cell)
* DM[M,N] = DM[N-M] by mapping the 2D subscripts to 1D subscripts
*/
void PBCVHF_direct_drv(void (*fdot)(), double *out, double *dms,
int n_dm, int nkpts, int nbands, int nbasp,
char *ovlp_mask, int *bvk_cell_id,
int *cell0_shl_id, int *images_loc,
int *shls_slice, int *bvk_ao_loc,
int *dm_translation, CINTOpt *cintopt, CVHFOpt *vhfopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
IntorEnvs envs = {natm, nbas, atm, bas, env, shls_slice, bvk_ao_loc,
NULL, cintopt, 1};
const size_t ish0 = shls_slice[0];
const size_t ish1 = shls_slice[1];
const size_t jsh0 = shls_slice[2];
const size_t jsh1 = shls_slice[3];
const size_t ksh0 = shls_slice[4];
const size_t ksh1 = shls_slice[5];
const size_t lsh0 = shls_slice[6];
const size_t lsh1 = shls_slice[7];
const size_t nish = ish1 - ish0;
const size_t njsh = jsh1 - jsh0;
const size_t nksh = ksh1 - ksh0;
const size_t nlsh = lsh1 - lsh0;
const int di = GTOmax_shell_dim(bvk_ao_loc, shls_slice, 1);
const int cache_size = _max_cache_size(int2e_sph, shls_slice, images_loc,
atm, natm, bas, nbas, env);
const size_t nij = nish * njsh;
const int naop = bvk_ao_loc[nbasp];
#pragma omp parallel
{
size_t ij, n;
int i, j, k, l;
size_t size = n_dm * naop * naop * nbands;
if (fdot == &PBCVHF_contract_jk_s2kl || fdot == &PBCVHF_contract_jk_s1) {
size *= 2; // vj and vk
}
double *v_priv = calloc(size, sizeof(double));
double *buf = malloc(sizeof(double) * (di*di*di*di*2 + cache_size));
#pragma omp for schedule(dynamic, 1)
for (ij = 0; ij < nij; ij++) {
i = ij / njsh;
j = ij % njsh;
if (!ovlp_mask[i*njsh+j]) {
continue;
}
for (k = 0; k < nksh; k++) {
for (l = 0; l < nlsh; l++) {
if (!ovlp_mask[k*nlsh+l]) {
continue;
}
(*fdot)(v_priv, dms, buf, n_dm, nkpts, nbands, nbasp,
i, j, k, l, bvk_cell_id, cell0_shl_id, images_loc,
dm_translation, vhfopt, &envs);
} }
}
#pragma omp critical
{
for (n = 0; n < size; n++) {
out[n] += v_priv[n];
}
}
free(buf);
free(v_priv);
}
}
/************************************************/
void CVHFset_int2e_q_cond(int (*intor)(), CINTOpt *cintopt, double *q_cond,
int *ao_loc, int *atm, int natm,
int *bas, int nbas, double *env);
static int _int2e_swap_jk(double *buf, int *dims, int *shls,
int *atm, int natm, int *bas, int nbas, double *env,
CINTOpt *cintopt, double *cache)
{
int shls_swap_jk[4] = {shls[0], shls[2], shls[1], shls[3]};
return int2e_sph(buf, dims, shls_swap_jk, atm, natm, bas, nbas, env, cintopt, cache);
}
void PBCVHFsetnr_direct_scf(CVHFOpt *opt, int (*intor)(), CINTOpt *cintopt,
int *ao_loc, int *atm, int natm,
int *bas, int nbas, double *env)
{
/* This memory is released in void CVHFdel_optimizer, Don't know
* why valgrind raises memory leak here */
if (opt->q_cond) {
free(opt->q_cond);
}
// nbas in the input arguments may different to opt->nbas.
// Use opt->nbas because it is used in the prescreen function
nbas = opt->nbas;
size_t Nbas = nbas;
opt->q_cond = (double *)malloc(sizeof(double) * Nbas * Nbas * 2);
double *qcond_ijij = opt->q_cond;
double *qcond_iijj = qcond_ijij + Nbas * Nbas;
CVHFset_int2e_q_cond(intor, cintopt, qcond_ijij, ao_loc,
atm, natm, bas, nbas, env);
CVHFset_int2e_q_cond(_int2e_swap_jk, cintopt, qcond_iijj, ao_loc,
atm, natm, bas, nbas, env);
}
|
GB_binop__min_uint8.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__min_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__min_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__min_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__min_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__min_uint8)
// A*D function (colscale): GB (_AxD__min_uint8)
// D*A function (rowscale): GB (_DxB__min_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__min_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__min_uint8)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_uint8)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_uint8)
// C=scalar+B GB (_bind1st__min_uint8)
// C=scalar+B' GB (_bind1st_tran__min_uint8)
// C=A+scalar GB (_bind2nd__min_uint8)
// C=A'+scalar GB (_bind2nd_tran__min_uint8)
// C type: uint8_t
// A type: uint8_t
// A pattern? 0
// B type: uint8_t
// B pattern? 0
// BinaryOp: cij = GB_IMIN (aij, bij)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint8_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) \
uint8_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) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_IMIN (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MIN || GxB_NO_UINT8 || GxB_NO_MIN_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__min_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__min_uint8)
(
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__min_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__min_uint8)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint8_t
uint8_t bwork = (*((uint8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__min_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
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
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__min_uint8)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_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__min_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
uint8_t alpha_scalar ;
uint8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint8_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__min_uint8)
(
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__min_uint8)
(
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__min_uint8)
(
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__min_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__min_uint8)
(
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
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_IMIN (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__min_uint8)
(
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 ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_IMIN (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMIN (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__min_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *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 \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMIN (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__min_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
repeat_base.h | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
#ifndef SEQAN_HEADER_REPEAT_BASE_H
#define SEQAN_HEADER_REPEAT_BASE_H
#if SEQAN_ENABLE_PARALLELISM
#include <seqan/parallel.h>
#endif // #if SEQAN_ENABLE_PARALLELISM
namespace seqan {
/**
.Class.Repeat
..summary:Store information about a repeat.
..cat:Index
..signature:Repeat<TPos, TPeriod>
..param.TPos:Type to use for storing positions.
...metafunction:Metafunction.Value
..param.TPeriod:Type to use for storing the repeat period.
...default:1
...metafunction:Metafunction.Size
..include:seqan/index.h
..see:Function.findRepeats
.Memvar.Repeat#beginPosition
..summary:The begin position of the repeat of type $TPos$.
..class:Class.Repeat
.Memvar.Repeat#endPosition
..summary:The end position of the repeat of type $TPos$.
..class:Class.Repeat
.Memvar.Repeat#period
..summary:The period of the repeat of type $TSize$.
..class:Class.Repeat
*/
/*!
* @class Repeat
* @headerfile <seqan/index.h>
* @brief Store information about a repeat.
*
* @signature template <typename TPos, typename TPeriod>
* struct Repeat;
*
* @tparam TPeriod Type to use for storing the repeat period. Default: 1
* @tparam TPos Type to use for storing positions.
*
* @see findRepeats
*
* @var TPos Repeat::endPosition;
* @brief The end position of the repeat of type <tt>TPos</tt>.
*
* @var TPos Repeat::beginPosition;
* @brief The begin position of the repeat of type <tt>TPos</tt>.
*
* @var TPeriod Repeat::period;
* @brief The period of the repeat of type <tt>TPeriod</tt>.
*/
template <typename TPos, typename TPeriod>
struct Repeat {
TPos beginPosition;
TPos endPosition;
TPeriod period;
};
template <typename TPos, typename TPeriod>
struct Value< Repeat<TPos, TPeriod> > {
typedef TPos Type;
};
template <typename TPos, typename TPeriod>
struct Size< Repeat<TPos, TPeriod> > {
typedef TPeriod Type;
};
template <typename TSize>
struct RepeatFinderParams {
TSize minRepeatLen;
TSize maxPeriod;
};
// custom TSpec for our customized wotd-Index
struct TRepeatFinder;
template <typename TText>
struct Cargo<Index<TText, IndexWotd<TRepeatFinder> > >
{
typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex;
typedef typename Size<TIndex>::Type TSize;
typedef RepeatFinderParams<TSize> Type;
};
// node predicate
template <typename TText, typename TSpec>
bool nodePredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it)
{
// return countOccurrences(it) * nodeDepth(it) >= cargo(container(it)).minRepeatLen;
return countOccurrences(it) * repLength(it) >= cargo(container(it)).minRepeatLen;
}
// monotonic hull
template <typename TText, typename TSpec>
bool nodeHullPredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it)
{
// return nodeDepth(it) <= cargo(container(it)).maxPeriod;
return repLength(it) <= cargo(container(it)).maxPeriod;
}
template <typename TPos>
struct RepeatLess_ : public ::std::binary_function<TPos, TPos, bool>
{
// key less
inline bool operator() (TPos const &a, TPos const &b) const {
return posLess(a, b);
}
};
template <typename TValue>
inline bool _repeatMaskValue(TValue const &)
{
// TODO(holtgrew): Maybe use unknownValue<TValue>() instead of specializing for all alphabets, especially since we have Rna5 now and might want Rna5Q later.
return false;
}
template <>
inline bool _repeatMaskValue(Dna5 const &val)
{
return val == unknownValue<Dna5>(); // 'N'
}
template <>
inline bool _repeatMaskValue(Dna5Q const &val)
{
return val == unknownValue<Dna5Q>(); // 'N'
}
template <>
inline bool _repeatMaskValue(Iupac const &val)
{
return val == unknownValue<Iupac>(); // 'N'
}
/*
template <>
inline bool _repeatMaskValue(AminoAcid val)
{
return val == 'X';
}
*/
/**
.Function.findRepeats
..summary:Search for repeats in a text.
..cat:Index
..signature:findRepeats(repeatString, text, minRepeatLength[, maxPeriod])
..param.repeatString:A @Class.String@ of @Class.Repeat@ objects.
..param.text:The text to search repeats in.
...type:Class.String
...type:Class.StringSet
..param.minRepeatLength:The minimum length each reported repeat must have.
..param.maxPeriod:Optionally, the maximal period that reported repeats can have.
...default:1
..remarks:Subsequences of undefined values/$N$s will always be reported.
..example.text:The following demonstrates finding repeats of period 1.
..example.code:
String<Repeat<unsigned, unsigned> > repeats;
Dna5String text = "CGATAAAACTNN";
// repeat 0 AAAA
// repeat 1 NN
findRepeats(repeats, text, 3);
// ==> length(repeats) == 2
// ==> repeats[0] == {beginPosition: 4, endPosition: 8, period: 1}
// ==> repeats[1] == {beginPosition: 11, endPosition: 13, period: 1}
..see:Function.unknownValue
..include:seqan/index.h
..see:Class.Repeat
*/
/*!
* @fn findRepeats
* @headerfile <seqan/index.h>
* @brief Search for repeats in a text.
*
* @signature void findRepeats(repeatString, text, minRepeatLength[, maxPeriod]);
*
* @param[out] repeatString A @link String @endlink of @link Repeat @endlink objects.
* @param[in] text The text to search repeats in. Types: @link SequenceConcept @endlink
* @param[in] minRepeatLength The minimum length each reported repeat must have.
* @param[in] maxPeriod Optionally, the maximal period that reported repeats can have. Default: 1
*
* Subsequences of undefined values/<tt>N</tt>s will always be reported.
*
* @section Examples
*
* The following demonstrates finding repeats of period 3.
*
* @include demos/index/find_repeats.cpp
*
* @code{.console}
* # of repeats: 15
* i == 0, beginPosition = 3, endPosition = 7, period = 1
* i == 1, beginPosition = 46, endPosition = 53, period = 1
* i == 2, beginPosition = 101, endPosition = 105, period = 1
* i == 3, beginPosition = 105, endPosition = 109, period = 1
* i == 4, beginPosition = 164, endPosition = 169, period = 1
* i == 5, beginPosition = 291, endPosition = 297, period = 1
* i == 6, beginPosition = 319, endPosition = 327, period = 1
* i == 7, beginPosition = 400, endPosition = 404, period = 1
* i == 8, beginPosition = 442, endPosition = 446, period = 1
* i == 9, beginPosition = 468, endPosition = 473, period = 1
* i == 10, beginPosition = 476, endPosition = 480, period = 1
* i == 11, beginPosition = 507, endPosition = 513, period = 1
* i == 12, beginPosition = 561, endPosition = 566, period = 1
* i == 13, beginPosition = 623, endPosition = 627, period = 1
* i == 14, beginPosition = 655, endPosition = 659, period = 1
* @endcode
*
* @see AlphabetWithUnknownValueConcept#unknownValue
* @see Repeat
*/
// TODO(holtgrew): minRepeatLength is 1-off.
// period-1 optimization
template <typename TRepeatStore, typename TString, typename TRepeatSize>
inline void findRepeats(TRepeatStore &repString, TString const &text, TRepeatSize minRepeatLen)
{
typedef typename Value<TRepeatStore>::Type TRepeat;
typedef typename Iterator<TString const>::Type TIterator;
typedef typename Size<TString>::Type TSize;
#if SEQAN_ENABLE_PARALLELISM
typedef typename Value<TString>::Type TValue;
if (length(text) > (TSize)(omp_get_max_threads() * 2 * minRepeatLen)) {
// std::cerr << ">>> PARALLEL WABOOGIE!" << std::endl;
// std::cerr << "omp_get_max_threads() == " << omp_get_max_threads() << std::endl;
// Parallel case.
// NOTE(holtgrew): The minimum text length check above makes it impossible that more than two chunks are
// required to form an otherwise too short repeat.
// TODO(holtgrew): Load balancing? Probably not worth it.
String<TSize> splitters;
String<TRepeatStore> threadLocalStores;
// Each threads finds repeats on its chunk in parallel.
#pragma omp parallel
{
// We have to determine the number of available threads at this point. We will use the number of thread
// local stores to determin the number of available threads later on.
#pragma omp master
{
// std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl;
computeSplitters(splitters, length(text), omp_get_num_threads());
resize(threadLocalStores, omp_get_num_threads());
} // end of #pragma omp master
#pragma omp barrier
int const t = omp_get_thread_num();
TRepeatStore & store = threadLocalStores[t];
TRepeat rep;
rep.beginPosition = 0;
rep.endPosition = 0;
rep.period = 1;
// Flags used for force-adding repeats for the chunks that have a left/right neighbour.
bool forceFirst = t > 0;
bool forceLast = (t + 1) < omp_get_num_threads();
// #pragma omp critical
// std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl;
TIterator it = iter(text, splitters[t], Standard());
TIterator itEnd = iter(text, splitters[t + 1], Standard());
if (it != itEnd)
{
TValue last = *it;
TSize repLeft = 0;
TSize repRight = 1;
for (++it; it != itEnd; ++it, ++repRight)
{
if (*it != last)
{
// #pragma omp critical
// std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceFirst = " << forceFirst << std::endl;
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceFirst)
{
forceFirst = false;
// insert repeat
rep.beginPosition = splitters[t] + repLeft;
rep.endPosition = splitters[t] + repRight;
// #pragma omp critical
// std::cerr << " t == " << t << ", append" << std::endl;
appendValue(store, rep);
}
repLeft = repRight;
last = *it;
}
}
// #pragma omp critical
// std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceLast = " << forceLast << std::endl;
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceLast)
{
// Insert repeat but only if it is not already in there.
if (empty(store) || (back(store).beginPosition != repLeft && back(store).endPosition != repRight))
{
rep.beginPosition = splitters[t] + repLeft;
rep.endPosition = splitters[t] + repRight;
// #pragma omp critical
// std::cerr << " t == " << t << ", append" << std::endl;
appendValue(store, rep);
}
}
}
} // end of #pragma omp parallel
// std::cerr << ",-- REPEATS BEFORE MENDING\n";
// for (unsigned i = 0; i < length(threadLocalStores); ++i)
// {
// std::cerr << "| i = " << i << std::endl;
// for (unsigned j = 0; j < length(threadLocalStores[i]); ++j)
// std::cerr << "| threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl;
// }
// std::cerr << "`--" << std::endl;
// Mend the splice points.
//
// We will copy out infixes described by fromPositions.
String<Pair<TSize> > fromPositions;
resize(fromPositions, length(threadLocalStores));
for (unsigned i = 0; i < length(fromPositions); ++i)
{
fromPositions[i].i1 = 0;
fromPositions[i].i2 = length(threadLocalStores[i]);
}
// First, merge repeats spanning blocks. Do this iteratively until all has been merged.
bool anyChange;
do
{
anyChange = false;
int lastNonEmpty = -1;
for (unsigned i = 0; i < length(threadLocalStores); ++i)
{
if (fromPositions[i].i1 == fromPositions[i].i2)
continue; // Skip empty buckets.
if (lastNonEmpty != -1)
{
bool const adjacent = back(threadLocalStores[lastNonEmpty]).endPosition == front(threadLocalStores[i]).beginPosition;
bool const charsEqual = text[back(threadLocalStores[lastNonEmpty]).beginPosition] == text[front(threadLocalStores[i]).beginPosition];
if (adjacent && charsEqual)
{
anyChange = true;
back(threadLocalStores[lastNonEmpty]).endPosition = front(threadLocalStores[i]).endPosition;
fromPositions[i].i1 += 1;
}
}
if (fromPositions[i].i1 != fromPositions[i].i2)
lastNonEmpty = i;
}
}
while (anyChange);
// Then, remove any repeats in the beginning and end of blocks that are too short.
for (unsigned i = 0; i < length(threadLocalStores); ++i)
{
if (fromPositions[i].i1 == fromPositions[i].i2)
continue;
unsigned j = fromPositions[i].i1;
TRepeatSize len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition;
if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value.
len <= minRepeatLen)
fromPositions[i].i1 += 1;
if (fromPositions[i].i1 == fromPositions[i].i2)
continue;
j = fromPositions[i].i2 - 1;
len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition;
if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value.
len <= minRepeatLen)
fromPositions[i].i2 -= 1;
}
// Last, build splitters for output in parallel.
String<unsigned> outSplitters;
appendValue(outSplitters, 0);
for (unsigned i = 0; i < length(threadLocalStores); ++i)
appendValue(outSplitters, back(outSplitters) + fromPositions[i].i2 - fromPositions[i].i1);
// std::cerr << ",-- REPEATS AFTER MENDING\n";
// for (unsigned i = 0; i < length(threadLocalStores); ++i)
// {
// std::cerr << "| i = " << i << std::endl;
// std::cerr << "`--, fromPositions[" << i << "] = (" << fromPositions[i].i1 << ", " << fromPositions[i].i2 << std::endl;
// for (unsigned j = 0; j < length(threadLocalStores[i]); ++j)
// std::cerr << " | threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl;
// }
// std::cerr << " `--" << std::endl;
// Allocate memory.
clear(repString);
resize(repString, back(outSplitters));
// Copy back the repeats in parallel.
unsigned nt = length(threadLocalStores);
(void) nt; // Otherwise, GCC 4.6 warns, does not see it used in pragma clause below.
#pragma omp parallel num_threads(nt)
{
int const t = omp_get_thread_num();
arrayCopy(iter(threadLocalStores[t], fromPositions[t].i1, Standard()),
iter(threadLocalStores[t], fromPositions[t].i2, Standard()),
iter(repString, outSplitters[t], Standard()));
} // end of #pragma omp parallel
} else {
#endif // #if SEQAN_ENABLE_PARALLELISM
// Sequential case.
TRepeat rep;
rep.period = 1;
clear(repString);
TIterator it = begin(text, Standard());
TIterator itEnd = end(text, Standard());
if (it == itEnd) return;
TSize repLen = 1;
for (++it; it != itEnd; ++it)
{
if (*it != *(it-1))
{
if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen)
{
// insert repeat
rep.endPosition = it - begin(text, Standard());
rep.beginPosition = rep.endPosition - repLen;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
repLen = 1;
} else
++repLen;
}
if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen)
{
// insert repeat
rep.endPosition = length(text);
rep.beginPosition = rep.endPosition - repLen;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
#if SEQAN_ENABLE_PARALLELISM
}
#endif // #if SEQAN_ENABLE_PARALLELISM
// #pragma omp critical
// {
// std::cerr << "thread #" << omp_get_thread_num() << " REPEATS:";
// for (unsigned i = 0; i < length(repString); ++i) {
// std::cerr << " (" << repString[i].beginPosition << ", " << repString[i].endPosition << ", " << repString[i].period << ")";
// }
// std::cerr << std::endl;
// }
}
// TODO(holtgrew): Why for TString const and StringSet<> const?
template <typename TRepeatStore, typename TString, typename TSpec, typename TRepeatSize>
inline void findRepeats(TRepeatStore &repString, StringSet<TString, TSpec> const &text, TRepeatSize minRepeatLen)
{
typedef typename Value<TRepeatStore>::Type TRepeat;
typedef typename Iterator<TString>::Type TIterator;
typedef typename Value<TString>::Type TValue;
typedef typename Size<TString>::Type TSize;
TRepeat rep;
rep.period = 1;
clear(repString);
for (unsigned i = 0; i < length(text); ++i)
{
TIterator it = begin(text[i], Standard());
TIterator itEnd = end(text[i], Standard());
if (it == itEnd) continue;
TValue last = *it;
TSize repLeft = 0;
TSize repRight = 1;
rep.beginPosition.i1 = i;
rep.endPosition.i1 = i;
for (++it; it != itEnd; ++it, ++repRight)
{
if (last != *it)
{
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen)
{
// insert repeat
rep.beginPosition.i2 = repLeft;
rep.endPosition.i2 = repRight;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
repLeft = repRight;
last = *it;
}
}
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen)
{
// insert repeat
rep.beginPosition.i2 = repLeft;
rep.endPosition.i2 = repRight;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
}
}
// main function
template <typename TRepeatStore, typename TText, typename TRepeatSize, typename TPeriodSize>
void findRepeats(TRepeatStore &repString, TText const &text, TRepeatSize minRepeatLen, TPeriodSize maxPeriod)
{
typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex;
typedef typename Size<TIndex>::Type TSize;
typedef typename Iterator<TIndex, TopDown<ParentLinks<> > >::Type TNodeIterator;
typedef typename Fibre<TIndex, FibreSA>::Type const TSA;
typedef typename Infix<TSA>::Type TOccString;
typedef typename Iterator<TOccString>::Type TOccIterator;
typedef typename Value<TRepeatStore>::Type TRepeat;
typedef typename Value<TOccString>::Type TOcc;
typedef ::std::map<TOcc,TRepeat,RepeatLess_<TOcc> > TRepeatList;
if (maxPeriod < 1) return;
if (maxPeriod == 1)
{
findRepeats(repString, text, minRepeatLen);
return;
}
TIndex index(text);
TRepeatList list;
// set repeat finder parameters
cargo(index).minRepeatLen = minRepeatLen;
cargo(index).maxPeriod = maxPeriod;
TNodeIterator nodeIt(index);
TOccIterator itA, itB, itRepBegin, itEnd;
TRepeat rep;
for (; !atEnd(nodeIt); goNext(nodeIt))
{
if (isRoot(nodeIt)) continue;
// get occurrences
TOccString occ = getOccurrences(nodeIt);
itA = begin(occ, Standard());
itEnd = end(occ, Standard());
itRepBegin = itB = itA;
TSize repLen = repLength(nodeIt); // representative length
if ((TSize)minRepeatLen <= repLen) continue;
TSize diff, period = 0; // period of current repeat
TSize repeatLen = 0; // overall length of current repeat
TSize minLen = minRepeatLen - repLen; // minimum repeat length minus length of representative
for (++itB; itB != itEnd; ++itB)
{
diff = posSub(*itB, *itA);
if (diff != period || getSeqNo(*itA) != getSeqNo(*itB))
{
// is the repeat long enough?
if (repeatLen >= minLen)
// is the repeat self overlapping or connected?
if (parentRepLength(nodeIt) < period && period <= repLen)
{
// insert repeat
rep.beginPosition = *itRepBegin;
rep.endPosition = posAdd(*itA, period);
rep.period = period;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep));
}
itRepBegin = itA;
period = diff;
repeatLen = 0;
}
repeatLen += period;
itA = itB;
}
// is the last repeat long enough?
if (repeatLen >= minLen)
// is the repeat self overlapping or connected?
if (parentRepLength(nodeIt) < period && period <= repLen)
{
// insert repeat
rep.beginPosition = *itRepBegin;
rep.endPosition = posAdd(*itA, period);
rep.period = period;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep));
}
}
// copy low-complex regions to result string
clear(repString);
reserve(repString, list.size(), Exact());
typename TRepeatList::const_iterator lit = list.begin();
typename TRepeatList::const_iterator litEnd = list.end();
for (TSize i = 0; lit != litEnd; ++lit, ++i)
appendValue(repString, (*lit).second);
}
} // namespace seqan
#endif
|
tree.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_TREE_H_
#define LIGHTGBM_TREE_H_
#include <LightGBM/dataset.h>
#include <LightGBM/meta.h>
#include <string>
#include <map>
#include <memory>
#include <unordered_map>
#include <vector>
namespace LightGBM {
#define kCategoricalMask (1)
#define kDefaultLeftMask (2)
/*!
* \brief Tree model
*/
class Tree {
public:
/*!
* \brief Constructor
* \param max_leaves The number of max leaves
*/
explicit Tree(int max_leaves);
/*!
* \brief Construtor, from a string
* \param str Model string
* \param used_len used count of str
*/
Tree(const char* str, size_t* used_len);
~Tree();
/*!
* \brief Performing a split on tree leaves.
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split
* \param threshold_double Threshold on feature value
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \param missing_type missing type
* \param default_left default direction for missing value
* \return The index of new leaf.
*/
int Split(int leaf, int feature, int real_feature, uint32_t threshold_bin,
double threshold_double, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight,
float gain, MissingType missing_type, bool default_left);
/*!
* \brief Performing a split on tree leaves, with categorical feature
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split, use bitset to represent
* \param num_threshold_bin size of threshold_bin
* \param threshold Thresholds of real feature value, use bitset to represent
* \param num_threshold size of threshold
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \return The index of new leaf.
*/
int SplitCategorical(int leaf, int feature, int real_feature, const uint32_t* threshold_bin, int num_threshold_bin,
const uint32_t* threshold, int num_threshold, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight, float gain, MissingType missing_type);
/*! \brief Get the output of one leaf */
inline double LeafOutput(int leaf) const { return leaf_value_[leaf]; }
/*! \brief Set the output of one leaf */
inline void SetLeafOutput(int leaf, double output) {
leaf_value_[leaf] = output;
}
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
data_size_t num_data,
double* score) const;
/*!
* \brief Adding prediction value of this tree model to scorese
* \param data The dataset
* \param used_data_indices Indices of used data
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
const data_size_t* used_data_indices,
data_size_t num_data, double* score) const;
/*!
* \brief Prediction on one record
* \param feature_values Feature value of this record
* \return Prediction result
*/
inline double Predict(const double* feature_values) const;
inline double PredictByMap(const std::unordered_map<int, double>& feature_values) const;
inline int PredictLeafIndex(const double* feature_values) const;
inline int PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const;
inline void PredictContrib(const double* feature_values, int num_features, double* output);
/*! \brief Get Number of leaves*/
inline int num_leaves() const { return num_leaves_; }
/*! \brief Get depth of specific leaf*/
inline int leaf_depth(int leaf_idx) const { return leaf_depth_[leaf_idx]; }
/*! \brief Get feature of specific split*/
inline int split_feature(int split_idx) const { return split_feature_[split_idx]; }
inline double split_gain(int split_idx) const { return split_gain_[split_idx]; }
/*! \brief Get the number of data points that fall at or below this node*/
inline int data_count(int node) const { return node >= 0 ? internal_count_[node] : leaf_count_[~node]; }
/*!
* \brief Shrinkage for the tree's output
* shrinkage rate (a.k.a learning rate) is used to tune the traning process
* \param rate The factor of shrinkage
*/
inline void Shrinkage(double rate) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_; ++i) {
leaf_value_[i] *= rate;
}
shrinkage_ *= rate;
}
inline double shrinkage() const {
return shrinkage_;
}
inline void AddBias(double val) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_; ++i) {
leaf_value_[i] = val + leaf_value_[i];
}
// force to 1.0
shrinkage_ = 1.0f;
}
inline void AsConstantTree(double val) {
num_leaves_ = 1;
shrinkage_ = 1.0f;
leaf_value_[0] = val;
}
/*! \brief Serialize this object to string*/
std::string ToString() const;
/*! \brief Serialize this object to json*/
std::string ToJSON() const;
/*! \brief Serialize this object to if-else statement*/
std::string ToIfElse(int index, bool predict_leaf_index) const;
inline static bool IsZero(double fval) {
if (fval > -kZeroThreshold && fval <= kZeroThreshold) {
return true;
} else {
return false;
}
}
inline static bool GetDecisionType(int8_t decision_type, int8_t mask) {
return (decision_type & mask) > 0;
}
inline static void SetDecisionType(int8_t* decision_type, bool input, int8_t mask) {
if (input) {
(*decision_type) |= mask;
} else {
(*decision_type) &= (127 - mask);
}
}
inline static int8_t GetMissingType(int8_t decision_type) {
return (decision_type >> 2) & 3;
}
inline static void SetMissingType(int8_t* decision_type, int8_t input) {
(*decision_type) &= 3;
(*decision_type) |= (input << 2);
}
void RecomputeMaxDepth();
private:
std::string NumericalDecisionIfElse(int node) const;
std::string CategoricalDecisionIfElse(int node) const;
inline int NumericalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if (std::isnan(fval)) {
if (missing_type != 2) {
fval = 0.0f;
}
}
if ((missing_type == 1 && IsZero(fval))
|| (missing_type == 2 && std::isnan(fval))) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int NumericalDecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if ((missing_type == 1 && fval == default_bin)
|| (missing_type == 2 && fval == max_bin)) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_in_bin_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int CategoricalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
int int_fval = static_cast<int>(fval);
if (int_fval < 0) {
return right_child_[node];;
} else if (std::isnan(fval)) {
// NaN is always in the right
if (missing_type == 2) {
return right_child_[node];
}
int_fval = 0;
}
int cat_idx = static_cast<int>(threshold_[node]);
if (Common::FindInBitset(cat_threshold_.data() + cat_boundaries_[cat_idx],
cat_boundaries_[cat_idx + 1] - cat_boundaries_[cat_idx], int_fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int CategoricalDecisionInner(uint32_t fval, int node) const {
int cat_idx = static_cast<int>(threshold_in_bin_[node]);
if (Common::FindInBitset(cat_threshold_inner_.data() + cat_boundaries_inner_[cat_idx],
cat_boundaries_inner_[cat_idx + 1] - cat_boundaries_inner_[cat_idx], fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int Decision(double fval, int node) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecision(fval, node);
} else {
return NumericalDecision(fval, node);
}
}
inline int DecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecisionInner(fval, node);
} else {
return NumericalDecisionInner(fval, node, default_bin, max_bin);
}
}
inline void Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain);
/*!
* \brief Find leaf index of which record belongs by features
* \param feature_values Feature value of this record
* \return Leaf index
*/
inline int GetLeaf(const double* feature_values) const;
inline int GetLeafByMap(const std::unordered_map<int, double>& feature_values) const;
/*! \brief Serialize one node to json*/
std::string NodeToJSON(int index) const;
/*! \brief Serialize one node to if-else statement*/
std::string NodeToIfElse(int index, bool predict_leaf_index) const;
std::string NodeToIfElseByMap(int index, bool predict_leaf_index) const;
double ExpectedValue() const;
/*! \brief This is used fill in leaf_depth_ after reloading a model*/
inline void RecomputeLeafDepths(int node = 0, int depth = 0);
/*!
* \brief Used by TreeSHAP for data we keep about our decision path
*/
struct PathElement {
int feature_index;
double zero_fraction;
double one_fraction;
// note that pweight is included for convenience and is not tied with the other attributes,
// the pweight of the i'th path element is the permuation weight of paths with i-1 ones in them
double pweight;
PathElement() {}
PathElement(int i, double z, double o, double w) : feature_index(i), zero_fraction(z), one_fraction(o), pweight(w) {}
};
/*! \brief Polynomial time algorithm for SHAP values (arXiv:1706.06060)*/
void TreeSHAP(const double *feature_values, double *phi,
int node, int unique_depth,
PathElement *parent_unique_path, double parent_zero_fraction,
double parent_one_fraction, int parent_feature_index) const;
/*! \brief Extend our decision path with a fraction of one and zero extensions for TreeSHAP*/
static void ExtendPath(PathElement *unique_path, int unique_depth,
double zero_fraction, double one_fraction, int feature_index);
/*! \brief Undo a previous extension of the decision path for TreeSHAP*/
static void UnwindPath(PathElement *unique_path, int unique_depth, int path_index);
/*! determine what the total permuation weight would be if we unwound a previous extension in the decision path*/
static double UnwoundPathSum(const PathElement *unique_path, int unique_depth, int path_index);
/*! \brief Number of max leaves*/
int max_leaves_;
/*! \brief Number of current levas*/
int num_leaves_;
// following values used for non-leaf node
/*! \brief A non-leaf node's left child */
std::vector<int> left_child_;
/*! \brief A non-leaf node's right child */
std::vector<int> right_child_;
/*! \brief A non-leaf node's split feature */
std::vector<int> split_feature_inner_;
/*! \brief A non-leaf node's split feature, the original index */
std::vector<int> split_feature_;
/*! \brief A non-leaf node's split threshold in bin */
std::vector<uint32_t> threshold_in_bin_;
/*! \brief A non-leaf node's split threshold in feature value */
std::vector<double> threshold_;
int num_cat_;
std::vector<int> cat_boundaries_inner_;
std::vector<uint32_t> cat_threshold_inner_;
std::vector<int> cat_boundaries_;
std::vector<uint32_t> cat_threshold_;
/*! \brief Store the information for categorical feature handle and mising value handle. */
std::vector<int8_t> decision_type_;
/*! \brief A non-leaf node's split gain */
std::vector<float> split_gain_;
// used for leaf node
/*! \brief The parent of leaf */
std::vector<int> leaf_parent_;
/*! \brief Output of leaves */
std::vector<double> leaf_value_;
/*! \brief weight of leaves */
std::vector<double> leaf_weight_;
/*! \brief DataCount of leaves */
std::vector<int> leaf_count_;
/*! \brief Output of non-leaf nodes */
std::vector<double> internal_value_;
/*! \brief weight of non-leaf nodes */
std::vector<double> internal_weight_;
/*! \brief DataCount of non-leaf nodes */
std::vector<int> internal_count_;
/*! \brief Depth for leaves */
std::vector<int> leaf_depth_;
double shrinkage_;
int max_depth_;
};
inline void Tree::Split(int leaf, int feature, int real_feature,
double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain) {
int new_node_idx = num_leaves_ - 1;
// update parent info
int parent = leaf_parent_[leaf];
if (parent >= 0) {
// if cur node is left child
if (left_child_[parent] == ~leaf) {
left_child_[parent] = new_node_idx;
} else {
right_child_[parent] = new_node_idx;
}
}
// add new node
split_feature_inner_[new_node_idx] = feature;
split_feature_[new_node_idx] = real_feature;
split_gain_[new_node_idx] = Common::AvoidInf(gain);
// add two new leaves
left_child_[new_node_idx] = ~leaf;
right_child_[new_node_idx] = ~num_leaves_;
// update new leaves
leaf_parent_[leaf] = new_node_idx;
leaf_parent_[num_leaves_] = new_node_idx;
// save current leaf value to internal node before change
internal_weight_[new_node_idx] = leaf_weight_[leaf];
internal_value_[new_node_idx] = leaf_value_[leaf];
internal_count_[new_node_idx] = left_cnt + right_cnt;
leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value;
leaf_weight_[leaf] = left_weight;
leaf_count_[leaf] = left_cnt;
leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value;
leaf_weight_[num_leaves_] = right_weight;
leaf_count_[num_leaves_] = right_cnt;
// update leaf depth
leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
leaf_depth_[leaf]++;
}
inline double Tree::Predict(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
inline double Tree::PredictByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
inline int Tree::PredictLeafIndex(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return leaf;
} else {
return 0;
}
}
inline int Tree::PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return leaf;
} else {
return 0;
}
}
inline void Tree::PredictContrib(const double* feature_values, int num_features, double* output) {
output[num_features] += ExpectedValue();
// Run the recursion with preallocated space for the unique path data
if (num_leaves_ > 1) {
CHECK(max_depth_ >= 0);
const int max_path_len = max_depth_ + 1;
std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2);
TreeSHAP(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1);
}
}
inline void Tree::RecomputeLeafDepths(int node, int depth) {
if (node == 0) leaf_depth_.resize(num_leaves());
if (node < 0) {
leaf_depth_[~node] = depth;
} else {
RecomputeLeafDepths(left_child_[node], depth + 1);
RecomputeLeafDepths(right_child_[node], depth + 1);
}
}
inline int Tree::GetLeaf(const double* feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values[split_feature_[node]], node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values[split_feature_[node]], node);
}
}
return ~node;
}
inline int Tree::GetLeafByMap(const std::unordered_map<int, double>& feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
}
return ~node;
}
} // namespace LightGBM
#endif // LightGBM_TREE_H_
|
ten_tusscher_2004_epi_S2_16.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S2_16.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
assert(cell_model);
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
//TODO: this should be called only once for the whole mesh, like in the GPU code
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5934020417845,0.00128316160896992,0.780329095939604,0.780220566229028,0.000174014290922046,0.485351964461050,0.00293503332848286,0.999998357040599,1.92538423669596e-08,1.88473554467734e-05,0.999772914410323,1.00703682498466,0.999994463032827,4.65490502991951e-05,0.633301730023318,9.92651972626448,139.581508364500};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) {
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++) {
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = i;
for (int j = 0; j < num_steps; ++j) {
solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu(real dt, real *sv, real stim_current) {
assert(sv);
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) {
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
///#ifdef EPI
real Gks=0.245;
///#endif
///#ifdef ENDO
/// real Gks=0.245;
///#endif
///#ifdef MCELL
/// real Gks=0.062;
///#endif
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
//#ifdef EPI
real Gto=0.294;
//#endif
// #ifdef ENDO
// real Gto=0.073;
//#endif
//#ifdef MCELL
// real Gto=0.294;
///#endif
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={14.1156251262174,0.000165810218046704,0.000133773186453739,0.000479110202185425,0.219374677494434,0.138025575941737,0.145074841732899,4.49439177041867,0.0150636017584010,1.81028903193328,1088.66028342185,0.000575512207306525,0.338168828687625,0.0190582202645448,0.00349417833561414,4.08648025582987e-05};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
///Ileak=0.00008f*(CaSR-Cai);
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
#ifdef EPI
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
#ifdef ENDO
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+28)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.;
#endif
#ifdef MCELL
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10));
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.