深度为64的(2,1)分支预测器
(2,1)分支预测器,使用两个变量存储全局前两个分支的跳转历史,记录该分支是否实际被执行。然后使用一个二维数组来存储4种历史情况下的64深度对应的简单预测器。PHT中简单预测器的bit数为1,也就是预测错误后就立即发生反转。
#include<stdio.h>
#define N 64
#define P 0//P为简单预测器初始值
/*(2,1)分支预测器*/
int main()
{
int hy_i[4][N], pt[4][N], ghr[2], max[4], j[4];//hy_i存储历史指令,pt存储对应的简单预测器的值,ghr记录前两位分支执行情况
int i, k, instr, addr, taken, ptaken, ic = 0, miss = 0;
FILE *fin;//读取文件
fin = fopen("history.txt", "r");
if(fin == NULL)
{
printf ("Failed to open the file !\n");
return 0;
}
ghr[0] = 0;//置零
ghr[1] = 0;
for(i = 0;i < 4;i++)
{
max[i] = 0;
j[i] = 0;
}
for(i = 0;i < N;i++)
for(k = 0;k < 4;k++)
pt[k][i] = 0;
while(!feof(fin))
{
fscanf(fin, "%x%x%d", &instr, &addr, &taken);
if(ghr[0] == 0 && ghr[1] == 0)//case1
{
for(i = 0;i < max[0];i++)
if(hy_i[0][i] == instr)//匹配到 PC
{
ptaken = pt[0][i];
if(ptaken != taken) //预测错误,翻转简单预测器
{
miss++;
pt[0][i] = (pt[0][i] + 1) % 2;
}
break;
}
if(i == max[0] && i < N) //未匹配到且深度未满,添加
{
hy_i[0][i] = instr;
if(P != taken)
{
miss++;
pt[0][i] = (pt[0][i] + 1) % 2;
}
max[0]++;
}
else if(i == N)//未匹配到且深度已满,更新
{
hy_i[0][j[0] % N] = instr;
if(P != taken)
{
miss++;
pt[0][j[0] % N] = (pt[0][j[0] % N] + 1) % 2;
}
j[0]++;
}
}
if(ghr[0] == 0 && ghr[1] == 1)//case2,后面三种同上
{
for(i = 0;i < max[1];i++)
if(hy_i[1][i] == instr)
{
ptaken = pt[1][i];
if(ptaken != taken)
{
miss++;
pt[1][i] = (pt[1][i] + 1) % 2;
}
break;
}
if(i == max[1] && i < N)
{
hy_i[1][i] = instr;
if(P != taken)
{
miss++;
pt[1][i] = (pt[1][i] + 1) % 2;
}
max[1]++;
}
else if(i == N)
{
hy_i[1][j[1] % N] = instr;
if(P != taken)
{
miss++;
pt[1][j[1] % N] = (pt[1][j[1] % N] + 1) % 2;
}
j[1]++;
}
}
if(ghr[0] == 1 && ghr[1] == 0)//case3
{
for(i = 0;i < max[2];i++)
if(hy_i[2][i] == instr)
{
ptaken = pt[2][i];
if(ptaken != taken)
{
miss++;
pt[2][i] = (pt[2][i] + 1) % 2;
}
break;
}
if(i == max[2] && i < N)
{
hy_i[2][i] = instr;
if(P != taken)
{
miss++;
pt[2][i] = (pt[2][i] + 1) % 2;
}
max[2]++;
}
else if(i == N)
{
hy_i[2][j[2] % N] = instr;
if(P != taken)
{
miss++;
pt[2][j[2] % N] = (pt[2][j[2] % N] + 1) % 2;
}
j[2]++;
}
}
if(ghr[0] == 1 && ghr[1] == 1)//case4
{
for(i = 0;i < max[3];i++)
if(hy_i[3][i] == instr)
{
ptaken = pt[3][i];
if(ptaken != taken)
{
miss++;
pt[3][i] = (pt[3][i] + 1) % 2;
}
break;
}
if(i == max[3] && i < N)
{
hy_i[3][i] = instr;
if(P != taken)
{
miss++;
pt[3][i] = (pt[3][i] + 1) % 2;
}
max[3]++;
}
else if(i == N)
{
hy_i[3][j[3] % N] = instr;
if(P != taken)
{
miss++;
pt[3][j[3] % N] = (pt[3][j[3] % N] + 1) % 2;
}
j[3]++;
}
}
ghr[0] = ghr[1];//更新
ghr[1] = taken;
ic++;
printf("ic = %d, miss = %d, miss/ic = %f\n", ic, miss, float(miss) / float(ic));
}
fclose(fin);
return 0;
}