code optimization techniques: a)strength reduction b) constant folding

, by Prashant Gunjal

### tac.txt #####
1 sq b - c
2 * 2 c c
3 := c - res
4 + a b no1
5 - res no1 res
6 + 3 5 pi
7 := pi - x
8 / x 2 res1

##### pr_11a.c ######
/*
10) WAP to implement following code optimization techniques:
a)strength reduction   b) constant folding
*/
#include<stdio.h>

struct holder
{
char seqno[3],op[3],arg1[8],arg2[8],result[8];
}tac[50];
int cnt=0,i,j,k;
char hunted[8];

int is_const(char arg[8])
{
for(j=0;j<strlen(arg);j++)
if(!isdigit(arg[j]))
return(0);
return(1);
}

void strength_red()
{
//check * sign and try to replace it by + and sq by *
for(i=0;i<cnt;i++)
{
if(strcmp(tac[i].op,"*")==0)
{
if(atoi(tac[i].arg1)==2 && !(is_const(tac[i].arg2)) )
{
strcpy(tac[i].op,"+");
strcpy(tac[i].arg1,tac[i].arg2);
}
else if(atoi(tac[i].arg2)==2 && !(is_const(tac[i].arg1)))
{
strcpy(tac[i].op,"+");
strcpy(tac[i].arg2,tac[i].arg1);
}
}
if(strcmp(tac[i].op,"/")==0 && atoi(tac[i].arg2)==2)
{
strcpy(tac[i].op,"*");
strcpy(tac[i].arg2,"0.5");

}
if(strcmp(tac[i].op,"sq")==0)
{
strcpy(tac[i].op,"*");
strcpy(tac[i].arg2,tac[i].arg1);

}
}
}
void const_folding()
{
//hunt var1 = const +/-/*// const and then  insted of arg1 place result replece const
int val=0;
for(i=0;i<cnt;i++)
{
if(is_const(tac[i].arg1)&&is_const(tac[i].arg2))
{
if(strcmp("+",tac[i].op)==0)
sprintf(tac[i].arg1,"%d",atoi(tac[i].arg1)+atoi(tac[i].arg2));
if(strcmp("-",tac[i].op)==0)
sprintf(tac[i].arg1,"%d",atoi(tac[i].arg1)-atoi(tac[i].arg2));
if(strcmp("*",tac[i].op)==0)
sprintf(tac[i].arg1,"%d",atoi(tac[i].arg1)*atoi(tac[i].arg2));
if(strcmp("/",tac[i].op)==0)
sprintf(tac[i].arg1,"%d",atoi(tac[i].arg1)/atoi(tac[i].arg2));

sprintf(tac[i].arg2,"-");
sprintf(tac[i].op,":=");
}
}

int main()
{
FILE * fin =fopen("tac.txt","r");
int i;
while(!feof(fin))
{
fscanf(fin,"%s%s%s%s%s",tac[cnt].seqno,tac[cnt].op,tac[cnt].arg1,tac[cnt].arg2,tac[cnt].result);
cnt++;
}
cnt--;
printf("\n\t\t*** $$ PURE INPUT $$ ****");
printf("\n\tIndex\tOP\tArg1\tArg2\tResult");
for(i=0;i<cnt;i++)
{
printf("\n\t%s\t%s\t%s\t%s\t%s",tac[i].seqno,tac[i].op,tac[i].arg1,tac[i].arg2,tac[i].result);
}
strength_red();
const_folding();
printf("\n\t\t*** After Process ****");
printf("\n\tIndex\tOP\tArg1\tArg2\tResult");
for(i=0;i<cnt;i++)
{
printf("\n\t%s\t%s\t%s\t%s\t%s",tac[i].seqno,tac[i].op,tac[i].arg1,tac[i].arg2,tac[i].result);
}
fclose(fin);
}

#### output #####

pr@prashant-HP:~/LEX&YACC/11$ cc pr_11a.c
pr@prashant-HP:~/LEX&YACC/11$ ./a.out

*** $$ PURE INPUT $$ ****
Index OP Arg1 Arg2 Result
1 sq b - c
2 * 2 c c
3 := c - res
4 + a b no1
5 - res no1 res
6 + 3 5 pi
7 := pi - x
8 / x 2 res1
*** After Process ****
Index OP Arg1 Arg2 Result
1 * b b c
2 + c c c
3 := c - res
4 + a b no1
5 - res no1 res
6 := 8 - pi
7 := pi - x
8 * x 0.5 res1pr@prashant-HP:~/LEX&YACC/11$ 

0 comments: