You are on page 1of 59

CS6612 – Compiler Design Lab Department of CSE 2016-2017

EX. NO: 1 LEXICAL ANALYZER

AIM: To write a C Program to implement a Lexical analyzer.


ALGORITHM:
1) Start the program.
2) Declare all the variables and file pointers.
3) Display the input program.
4) Separate the keyword in the program and display it.
5) Display the header files of the input program.
6) Separate the operators of the input program and display it.
7) Print the punctuation marks.
8) Print the constant that are present in input program.
9) Print the identifiers of the input program.
10) Stop the program.

PROGRAM:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main()
{
FILE *fp;
int i,j;
char arr[100],k;
char kw[10][10]={"int","float","double","end","main","void","include","printf","scanf"};
char hf[2][10]={"stdio.h","conio.h"};
char op[5]={'+','-','*','/','%'};
char punc[6]={'(',')','{','}',','};
clrscr();
fp=fopen("input.c","r");
printf("Input Program\n");
while(!feof(fp))
{
arr[0]=fgetc(fp);
printf("%c",arr[0]);
}

Page 1 of 59
fclose(fp);
printf("\nSymbol table\n");
fp=fopen("input.c","r");
printf("\nKeywords");
while(!feof(fp))
{
arr[0]=fgetc(fp);

fscanf(fp,"%s",arr);
for(i=0;i<10;i++)
{
if(strcmp(arr,kw[i])==0)
{
printf("\t%s",arr);
}
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nHeader files");
while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,hf[i])==0)
{
printf("\t%s",arr);
}
}}
fclose(fp);
fp=fopen("input.c","r");
printf("\nOperators");
while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<5;i++)
{
if(arr[0]==op[i])

St.Joseph’s College of Engineering Page 2 of 59


{
printf("\t%c",arr[0]);
}
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\npunctuation");
while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<6;i++)
{
if(arr[0]==punc[i])
{
printf("\t%c",arr[0]);
}
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nConstants");
while(!feof(fp))
{
arr[0]=fgetc(fp);
if(isdigit(arr[0]))
{
printf(" %c ",arr[0]);
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nidentifier ");
while(!feof(fp))
{
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,kw[i])==0)
{

St.Joseph’s College of Engineering Page 3 of 59


fscanf(fp,"%s",arr);
j=0;
while(j<strlen(arr) && arr[j]!=';')
{
printf("%c",arr[j]);
j++;
}}}}
fclose(fp);

// input.c

#include<stdio.h>
#include<conio.h>
void main()
{
int a,c,d;
float b=12.2;
char c='abcd';
clrscr();
a=10;
c=20;
d=a+b;
printf("D value is %d",d);
printf(" B value is %f",b);
printf("C value is %c",c);
getch();
}

OUTPUT:

[root@localhost ~]# vi ex2.c


[root@localhost ~]# cc ex2.c -o ex2.out
[root@localhost ~]# ./ex2.out
Symbol table
Keywords void int float
Header files
Operators + % % %
punctuation ( ) { , , ( , ) ( , ) ( , ) }

St.Joseph’s College of Engineering Page 4 of 59


Constants 1 2 2 1 0 2 0
identifier a,c,d
b=12.2
[root@localhost ~]#

RESULT:

Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 5 of 59


EX.NO: 2 LEXICAL ANALYZER USING LEX

AIM: To write a lex program to implement the lexical analyzer.


ALGORITHM:
1) Start the program
2) Open a file file.c in read and include the yylex() tool for input scanning.
3) Define the alphabets and numbers.
4) Print the preprocessor, function, keyword using yytext.lex tool.
5) Print the relational, assignment and all the operator using yytext() tool.
6) Also scan and print where the loop ends and begins.
7) Use yywrap() to enter an error.
8) Stop the program.

PROGRAM:
%{
int COMMENT=0;
%}
identifier [_a-zA-Z][_a-zA-Z0-9]*
%%
#.* {printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
float |
char |
while |
for |
do |
if |
break |
continue |
void |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT=1;
printf("\n\n\t COMMENT ENDS\n");}
St.Joseph’s College of Engineering Page 6 of 59
{identifier}\( {if(!COMMENT)
printf("\n\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}
\} {if(!COMMENT) printf("\n BLOCK ENDS");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT) printf("\n %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a NUMBER",yytext);}
\)(\;)? {if(!COMMENT) printf("\n\t");ECHO; printf("\n");}
\( ECHO;
= {if(!COMMENT) printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
.|\n ;
%%

int main(int argc,char **argv)


{
if(argc > 1)
{
FILE *file;
file=fopen(argv[1],"r");
if(!file)
{
printf("could not open %s\n",argv[1]);
exit(0);
}
yyin=file;
}
yylex();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0; }
// input.c
#include<stdio.h>

St.Joseph’s College of Engineering Page 7 of 59


#include<conio.h>
void main()
{
int a,c,d;
float b=12.2;
char c='abcd';
clrscr();
a=10;
c=20;
d=a+b;
printf("D value is %d",d);
printf(" B value is %f",b);
printf("C value is %c",c);
getch();
}
OUTPUT:
[root@localhost ~]# vi ex3.l
[root@localhost ~]# lex ex3.l
[root@localhost ~]# cc lex.yy.c -o ex3.out
[root@localhost ~]# ./ex3.out input.c
#include<stdio.h> is a PREPROCESSOR DIRECTIVE
void is a KEYWORD
FUNCTION
main(
)
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER
c IDENTIFIER
d IDENTIFIER
float is a KEYWORD
b IDENTIFIER
= is an ASSIGNMENT OPERATOR
12 is a NUMBER
2 is a NUMBER
char is a KEYWORD
c IDENTIFIER
= is an ASSIGNMENT OPERATOR
abcd IDENTIFIER
a IDENTIFIER

St.Joseph’s College of Engineering Page 8 of 59


= is an ASSIGNMENT OPERATOR
10 is a NUMBER
c IDENTIFIER
= is an ASSIGNMENT OPERATOR
20 is a NUMBER
d IDENTIFIER
= is an ASSIGNMENT OPERATOR
a IDENTIFIER
b IDENTIFIER
FUNCTION
printf(
"D value is %d" is a STRING
d IDENTIFIER
);
FUNCTION
printf(
" B value is %f" is a STRING
b IDENTIFIER
);
FUNCTION
printf(
"C value is %c" is a STRING
c IDENTIFIER
);

RESULT:
Thus the above program has been executed successfully

EX.NO:3A RECOGNIZE A VALID ARITHMETIC EXPRESSION

AIM: To write a program to recognize a valid arithmetic expression that uses operator +, - , *
and /.

St.Joseph’s College of Engineering Page 9 of 59


ALGORITHM:
1) Start the program.
2) Create a regular expression for recognize arithmetic expression in lex tool
3) In same way +,_,*,/ in yacc tool.
4) Evaluate the expression
5) Stop the program

PROGRAM:
Using Yacc Tool :
%{
#include<stdio.h>
%}
%token NUMBER ID
%left '+' '-'
%left '*' '/'
%%
exp: exp '+' exp
| exp '-' exp
| exp '*' exp
| exp '/' exp
|'_'NUMBER
|'_'ID
|'('exp')'
|NUMBER
|ID
%%
int yyerror(char *msg)
{
printf("Invalid Expression\n");
exit(0);
}
main ()
{
printf("Enter the expression\n");
yyparse();
printf("\n Expression is vaild\n");
exit(0);
}

Lex Part:
St.Joseph’s College of Engineering Page 10 of 59
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext);
return NUMBER; }
[a-zA-Z]+ {return ID;}
[\t]+;
\n { return 0 ;}
. { return yytext[0]; }
%%

OUTPUT:
root@localhost ~]# vi ex4a.l
[root@localhost ~]# lex ex4a.l
[root@localhost ~]# vi ex4a.y
[root@localhost ~]# yacc -d ex4a.y
[root@localhost ~]# cc y.tab.c lex.yy.c -ll -o ex4a.out
[root@localhost ~]# ./ex4a.out
Enter the expression
(a+c+e+40)
Expression is vaild
[root@localhost ~]# ./a.out
Enter the expression
(a++d+40)
Invalid Expression

RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 11 of 59


EX.NO:3B RECOGNIZE A VALID VARIABLE

AIM: To write a program to recognize a valid variable which starts with a letter followed by
any number of letters or digits.

ALGORITHM:
1) Start the program
2) Create a regular expression for identifier (letter)(letter/digit)*
3) In the same way,in yacc tool.
4) Stop the program

PROGRAM:
Using LEX:
%{
#include "y.tab.h"
%}
%%
[a-zA-Z] return LETTER ;
[0-9] return DIGIT ;
[\n] return 0;
. return yytext[0];
%%
Using YACC:
%{
#include<stdio.h>
int vaild=1;
%}
%token DIGIT LETTER
%%
start : LETTER s
s:LETTER s
| DIGIT s
|;
%%
int yyerror()
{
printf("Not a identifier\n");
vaild=0;
return 0;
}

St.Joseph’s College of Engineering Page 12 of 59


int main()
{
printf("Enter the variable name\n");
yyparse();
if(vaild)
{
printf("The string is vaild\n");
}
}

OUTPUT:
[root@localhost ~]# vi ex4b.l
[root@localhost ~]# lex ex4b.l
[root@localhost ~]# vi ex4b.y
[root@localhost ~]# yacc -d ex4b.y
[root@localhost ~]# cc y.tab.c lex.yy.c -ll -o ex4b.out
[root@localhost ~]# ./ex4b.out
Enter the variable name
Naveen
The string is vaild

[root@localhost ~]# ./a.out


Enter the variable name
$Naveen
Not a identifier

RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 13 of 59


EX.NO:3C CALCULATOR USING LEX AND YACC
AIM: To write a program to implement calculator using lex and yacc.

ALGORITHM:
1) Start the program.
2) Perform the calculation using both the lex and yacc.
3) In the lex tool, if the given expression contains numbers and letters then they are
displayed.
4) In the same way, the digits, letters and uminus are identified and displayed using yacc
tool.
5) The calculation is performed and the result is displayed.
6) Stop the program

PROGRAM:
Using LEX:
%{
#include <stdio.h>
#include "y.tab.h"
int c;
extern int yylval;
%}
%%
"" ;
[a-z] {
c = yytext[0];
yylval = c - 'a';
return(LETTER);
}
[0-9] {
c = yytext[0];
yylval = c - '0';
return(DIGIT);
}
[^a-z0-9\b] {
c = yytext[0];
return(c);
}
Using YACC:
%{
#include <stdio.h>
int regs[26];
St.Joseph’s College of Engineering Page 14 of 59
int base;
%}
%start list
%token DIGIT LETTER
%left '|'
%left '&'
%left '+' '-'
%left '*' '/' '%'
%left UMINUS /*supplies precedence for unary minus */
%% /* beginning of rules section */
list: /*empty */
|
list stat '\n'
|
list error '\n'
{
yyerrok;
}
;
stat: expr
{
printf("%d\n",$1);
}
|
LETTER '=' expr
{
regs[$1] = $3;
}
;
expr: '(' expr ')'
{
$$ = $2;
}
|
expr '*' expr
{
$$ = $1 * $3;
}
|
expr '/' expr

St.Joseph’s College of Engineering Page 15 of 59


{
$$ = $1 / $3;
}
|
expr '%' expr
{
$$ = $1 % $3;
}
|
expr '+' expr
{
$$ = $1 + $3;
}
|
expr '-' expr
{
$$ = $1 - $3;
}
|
expr '&' expr
{
$$ = $1 & $3;
}
|
expr '|' expr
{
$$ = $1 | $3;
}
|
'-' expr %prec UMINUS
{
$$ = -$2;
}
|
LETTER
{
$$ = regs[$1];
}
|
number

St.Joseph’s College of Engineering Page 16 of 59


;
number: DIGIT
{
$$ = $1;
base = ($1==0) ? 8 : 10;
} |
number DIGIT
{
$$ = base * $1 + $2;
}
;
%%
main()
{
return(yyparse());
}
yyerror(s)
char *s;
{
fprintf(stderr, "%s\n",s);
}
yywrap()
{
return(1);
}
OUTPUT:
[root@localhost ~]# vi ex4c.l
[root@localhost ~]# lex ex4c.l
[root@localhost ~]# vi ex4c.y
[root@localhost ~]# yacc -d ex4c.y
[root@localhost ~]# cc y.tab.c lex.yy.c -ll -o ex4c.out
[root@localhost ~]# ./ex4c.out

23+3
26
32-3
29
50/10
5
0

St.Joseph’s College of Engineering Page 17 of 59


RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 18 of 59


EX.NO:4 BNF RULES TO GENERATE ABSTRACT SYNTAX TREE

AIM: To write a program to convert the BNF rules into Yacc form and write code to generate
Abstract Syntax Tree.

ALGORITHM:
1) Include the necessary header files.
2) Declare the semantic rule for the identifier and number.
3) If the statement begins with main (), if else * while, the return as MAIN, IF ELSE and
WHILE.
4) If the variables are declared as int, float and char then return as VAR and NUM
5) Include the necessary header files. Initialize the err no=0 and declare like no as integer.
6) Declare the necessary tokens for the grammar.

PROGRAM:
USING LEX:
%{
#include"y.tab.h"
#include<stdio.h>
#include<string.h>
int LineNo=1;
%}
identifier [a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
main\(\) return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float return TYPE;
{identifier} {strcpy(yylval.var,yytext);
return VAR;}
{number} {strcpy(yylval.var,yytext);
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);

St.Joseph’s College of Engineering Page 19 of 59


return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
USING YACC:
%{
#include<string.h>
#include<stdio.h>
struct quad { char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int items[100];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;

St.Joseph’s College of Engineering Page 20 of 59


STATEMENT: DESCT ';'
| ASSIGNMENT ';'

| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '=' EXPR{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
| VAR
| NUM
;
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST: IF '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");

St.Joseph’s College of Engineering Page 21 of 59


strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;

}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop();
Ind=pop();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo); Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE '(' CONDITION ')'
{
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");

St.Joseph’s College of Engineering Page 22 of 59


strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
if(argc>1) {
fp=fopen(argv[1],"r");
if(!fp) {
printf("\n File not found");
exit(0);
}
yyin=fp;
}
yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t
--------------------");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t
%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
}printf("\n\t\t -----------------------");
printf("\n\n"); return 0; }
void push(int data)
{
stk.top++;
if(stk.top==100)

St.Joseph’s College of Engineering Page 23 of 59


{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0); }
data=stk.items[stk.top--];
return data;
}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
sprintf(QUAD[Index].result,"t%d",tIndex++); strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\n Error on line no:%d",LineNo);
}
{c=a-b;}
else
{c=a+b;}}

OUTPUT: INPUT: text.c


main()
{
int a,b,c;
if(a<b)
{ a=a+b; }
while(a<b)
{ a=a+b; }
if(a<=b)

St.Joseph’s College of Engineering Page 24 of 59


[root@localhost ~]# vi ex5.l
[root@localhost ~]# vi ex5.y
[root@localhost ~]# lex ex5.l
[root@localhost ~]# yacc -d ex5.y
[root@localhost ~]# cc y.tab.c lex.yy.c -ll
[root@localhost ~]# cc y.tab.c lex.yy.c -ll -o ex5.out
[root@localhost ~]# ./ex5.out text.c
--------------------------------------------------------
Pos Operator Arg1 Arg2 Result
---------------------------------------------------------
0 < a b t0
1 == t0 FALSE 5
2 + a b t1
3 = t1 a
4 GOTO 5
5 < a b t2
6 == t2 FALSE 10
7 + a b t3
8 = t3 a
9 GOTO 5
10 <= a b t4
11 == t4 FALSE 15
12 - a b t5
13 = t5 c
14 GOTO 17
15 + a b t6
16 = t6 c
-------------------------------------------------------
RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 25 of 59


EX. NO: 5 SYMBOL TABLE

AIM: To write a C program to implement a symbol table.


ALGORITHM:
1) Start the program.
2) Get the input from the user with the terminating symbol ‘$’.
3) Allocate memory for the variable by dynamic memory allocation function.
4) If the next character of the symbol is an operator then only the memory is allocated.
5) While reading, the input symbol is inserted into symbol table along with its memory
address.
6) The steps are repeated till ‘$’ is reached.
7) To reach a variable, enter the variable to the searched and symbol table has been checked
for corresponding variable, the variable along with its address is displayed as result.
8) Stop the program.
PROGRAM:
#include <stdio.h>
#include<ctype.h>
#include<malloc.h>
#include<string.h>
#include<math.h>
#include <termios.h>
#include <unistd.h>
void main()
{
int i=0,j=0,x=0,n,flag=0;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $ : ");
while((c=getche())!='$')
{
b[i]=c;
i++;
}
n=i-1;
printf("Given Expression : ");
i=0;
while(i<=n)
St.Joseph’s College of Engineering Page 26 of 59
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol\taddr\ttype");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
if(j==n)
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("%c\t%d\tidentifier",c,p);
}
else
{
ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c\t%d\tidentifier\n",c,p);
x++;
}}}
j++;
}
printf("\nThe symbol is to be searched");
srch=getche();
for(i=0;i<=x;i++)
{
if(srch==d[i])
{
printf("\nSymbol Found");
printf("\n%c%s%d\n",srch," @address ",add[i]);
flag=1;

St.Joseph’s College of Engineering Page 27 of 59


}
}
if(flag==0)
printf("\nSymbol Not Found");
getch();
}
int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
int getche(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}

OUTPUT:
[root@localhost ~]# vi ex1.c
[root@localhost ~]# cc ex1.c -o ex1.out
[root@localhost ~]# ./ex1.out
Expression terminated by $ : p+q+r $
Given Expression : p+q+r
Symbol Table
Symbol addr type
q 167063560 identifier

St.Joseph’s College of Engineering Page 28 of 59


r 167063664 identifier
The symbol is to be searched r
Symbol Found
r @address 167063664

RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 29 of 59


EX.NO:6 TYPE CHECKING

AIM:
To write a program to implement type checking

ALGORITHM:
1) Include the necessary header files.
2) Declare necessary data type(typecheck.l) for validating the type checking(eg
int,float,char ,etc)
3) Validate the given data type in parser(typecheck.y)

PROGRAM:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char* type(char[],int);
int main()
{
char a[10],b[10],mess[20],mess1[20];
int i,l;
printf( "\n\n int a,b;\n\n int c=a+b\n");
printf( "\n\n Enter a value for a\n");
scanf("%s",a);
l=strlen(a);
printf(" \n a is :");
strcpy(mess,type(a,l));
printf("%s",mess);
printf( "\n\n Enter a value for b\n\n");
scanf("%s",b);
l=strlen(b);
printf(" \n b is :");
strcpy(mess1,type(b,l));
printf("%s",mess1);
if((strcmp(mess,"int")==0)&&(strcmp(mess1,"int")==0))
printf("\n\n no type ...or");
else
printf("type error");
}
char* type(char x[],int m)
{
int i; char mes[20];
for(i=0;i<m;i++)
{
if(isalpha(x[i]))
St.Joseph’s College of Engineering Page 30 of 59
{
strcpy(mes,"alphanumeric");
goto x;
}
else if (x[i]=='.')
{
strcpy(mes,"float");
goto x;
}
}
strcpy(mes,"int");
x:
return mes;
}
OUTPUT:
int a.b:
int c=a+b;
Enter a value for a
21.5
a is ;float
Enter a value for b
35
b is ;int

type error

RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 31 of 59


EX.NO:7A CONTROL FLOW ANALYSIS

AIM:
To implement Control Flow Analysis and display the output graph as blocks using a C
program.

ALGORITHM:
1) Include the necessary header files.
2) Create a structure and include the pointers that are needed for operation in it.
3) Create three arrays for input data, label and for the target data.
4) Create a file pointer and read the file and copy it to the respective character arrays.
5) Get the three address code and put them in the respective blocks.
6) Print the basic blocks and output the control Flow in each blocks.

PROGRAM:
#include<stdio.h>
#include<curses.h>
#include<stdlib.h>
//#include<alloc.h>
#include<string.h>
struct Listnode
{
char data[500];
int leader,block,u_goto,c_goto;
struct Listnode *next;
char label[100],target[100];
}*temp,*cur,*first=NULL,*last=NULL,*cur1;
FILE *fpr;
void createnode(char code[500])
{
temp=(struct Listnode *)malloc(sizeof(struct Listnode));
strcpy(temp->data,code);
strcpy(temp->label,'\0');
strcpy(temp->target,'\0');
temp->leader=0;
temp->block=0;
temp->u_goto=0;
temp->c_goto=0;
temp->next=NULL;
if(first==NULL)
{
first=temp;
St.Joseph’s College of Engineering Page 32 of 59
last=temp;
}
else
{
last->next=temp;
last=temp;
}
}
void printlist()
{
cur=first;
printf("\nMIR code is \n\n");
while(cur!=NULL)
{
printf("\ncode:%s",cur->data);
printf("\nleader:%d\t",cur->leader);
printf("block:%d\t",cur->block);
printf("u_goto:%d\t",cur->u_goto);
printf("c_goto:%d\t",cur->c_goto);
printf("label:%s\t",cur->label);
printf("target:%s\n",cur->target);
cur=cur->next;
}
}
void main()
{
char codeline[50];
char c,dup[50],target[10];
char *substring,*token;
int i=0,block,block1;
int j=0;
fpr= fopen("input.txt","r");
//clrscr();
while((c=getc(fpr))!=EOF)
{
if(c!='\n')
{
codeline[i]=c;
i++;
}

St.Joseph’s College of Engineering Page 33 of 59


else
{
codeline[i]='\0';
createnode(codeline);
i=0;
}
}
//create last node
codeline[i]='\0';
createnode(codeline);
fclose(fpr);
// printlist();
// find out leaders,conditional stmts
cur=first;
cur->leader=1;
while(cur!=NULL)
{
substring=strstr((cur->data),"if");
if(substring==NULL)
{
if((strstr((cur->data),"goto"))!=NULL)
{
cur->u_goto=1;
(cur->next)->leader=1;
}
}
else
{
cur->c_goto=1;
(cur->next)->leader=1;
}
substring=strstr((cur->data),":");
if(substring!=NULL)
{
cur->leader=1;
}
substring=strstr((cur->data),"call");
if(substring!=NULL)
{
cur->leader=1;

St.Joseph’s College of Engineering Page 34 of 59


}
if(strstr(cur->data,"return")!=NULL)
{
cur->leader=1;
(cur->next)->leader=1;
}
cur=cur->next;
}
//to find labels and targets
cur=first;
while(cur!=NULL)
{
if((cur->u_goto==1)||(cur->c_goto==1))
{
substring=strstr(cur->data,":");
if(substring!=NULL)
{
token=strstr(substring,"L" );
if(token!=NULL)
strcpy(cur->target,token);
}
else
{
substring=strstr(cur->data,"L");
if(substring!=NULL)
strcpy(cur->target,substring);
}
}
if(strstr(cur->data,":")!=NULL)
{
strcpy(dup,cur->data);
token=strtok(dup,":");
// printf("\ntoken:%s",token);
if(token!=NULL)
strcpy(cur->label,token);
}
cur=cur->next;
}
// printlist();
//to identify blocks

St.Joseph’s College of Engineering Page 35 of 59


cur=first;
while(cur!= NULL)
{
cur=cur->next;
if((cur->leader)==1)
{
j++;
cur->block=j;
}
else
cur->block=j;
}
//printlist();
// print basic blocks
printf("\n\n......Basic Blocks......\n");
cur=first;
j=0;
printf("\nBlock %d:",j);
while(cur!=NULL)
{
if ((cur->block)==j)
{
printf("%s",cur->data);
printf("\n\t");
cur=cur->next;
}
else
{
j++;
printf("\nBlock %d:",j);
}
}
//to output the control flow from each block
printf ("\t\t.......Control Flow.......\n\n");
cur=first;
i=0;
while(cur!=NULL)
{
if((cur->block)!=(cur->next)->block)
{

St.Joseph’s College of Engineering Page 36 of 59


block=cur->block;
if(cur->u_goto==1)
{
strcpy(target,cur->target);
cur1=first;
while(cur1!=NULL)
{
if(strcmp(cur1->label,target)==0)
{
block1=cur1->block;
printf("\t\tBlock%d---------->Block%d\n",block,block1);
}
cur1=cur1->next;
}
}
else if(cur->c_goto==1)
{
strcpy(target,cur->target);
cur1=first;
while(cur1!=NULL)
{
if(strcmp(cur1->label,target)==0)
{
block1=cur1->block;
printf("\t\tBlock%d---TRUE--->Block%d---FALSE--->Block%d\n",block,block1,(block+1));
cur1=cur1->next;
}
}
}
else if(strstr(cur->data,"return")==NULL)
{
printf("\t\tBlock%d---------->Block%d\n",block,(block+1));
}
else
printf("\t\tBlock%d---------->NULL\n",block);
}
cur=cur->next;
}
cur=last;
block= cur->block;

St.Joseph’s College of Engineering Page 37 of 59


printf("\t\tBlock%d--------->NULL",block);
//getch();
}

Input (input.txt):
100 if a<=b goto 103
101 T:=0
102 goto 104
103 T:=1
104 return
OUTPUT:
[root@localhost ~]# vi ex7a.c
[root@localhost ~]# cc ex7a.c -o ex7a.out
[root@localhost ~]# ./ex7a.out input.txt
......Basic Blocks......
Block 0:100 if a<=b goto 103
Block 1:101 T:=0
102 goto 104
Block 2:103 T:=1
Block 3:104 return
.......Control Flow.......
Block0---TRUE--->Block0---FALSE--->Block1

RESULT:
Thus the above program has been executed successfully

Ex.NO:7b DATA FLOW ANALYSIS

AIM:
To implement Data Flow Analysis using a Available expression using a C program.

ALGORITHM:
1) Include the necessary header files.
St.Joseph’s College of Engineering Page 38 of 59
2) Declare necessary character arrays for input and output and also a structure to include
it.
3) Declare an array of structure variables to access the members.
4) Get the maximum number of expressions from the user.
5) If both the positions before and after the operand are digits store them.
6) Eliminate the expression and replace any operand that uses result of this expression.
7) If the variable is repeated again in the steps, then replace it with the expression obtained
above.
8) Print the optimized code.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void input();
void output();
void change(int p,int q,char *res);
void constant();
void expression();
struct expr
{
char op[2],op1[5],op2[5],res[5];
int flag;
}arr[10];
int n;
int main()
{
int ch=0;
input();
constant();
expression();
output();
}
void input()
{
int i;
printf("\n\nEnter the maximum number of expressions:");
scanf("%d",&n);
printf("\nEnter the input : \n");
for(i=0;i<n;i++)
{
scanf("%s",arr[i].op);

St.Joseph’s College of Engineering Page 39 of 59


scanf("%s",arr[i].op1);
scanf("%s",arr[i].op2);
scanf("%s",arr[i].res);
arr[i].flag=0;
}
}
void constant()
{
int i;
int op1,op2,res;
char op,res1[5];
for(i=0;i<n;i++)
{
if(isdigit(arr[i].op1[0]) && isdigit(arr[i].op2[0])) //if both digits, store them in variables
{
op1=atoi(arr[i].op1);
op2=atoi(arr[i].op2);
op=arr[i].op[0];
switch(op)
{
case '+':
res=op1+op2;
break;
case '-':
res=op1-op2;
break;
case '*':
res=op1*op2;
break;
case '/':
res=op1/op2;
break;
}
sprintf(res1,"%d",res);
arr[i].flag=1; //eliminate expr and replace any operand below that uses result of this expr
change(i,i,res1);
}}}
void expression()
{
int i,j;

St.Joseph’s College of Engineering Page 40 of 59


for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(arr[i].op,arr[j].op)==0) //if operators are same
{
if(strcmp(arr[i].op,"+")==0||strcmp(arr[i].op,"*")==0) //order doesn’t matter if operators are +
or *
{
if(strcmp(arr[i].op1,arr[j].op1)==0&&strcmp(arr[i].op2,arr[j].op2)==0 ||
strcmp(arr[i].op1,arr[j].op2)==0&&strcmp(arr[i].op2,arr[j].op1)==0)
{
arr[j].flag=1; //does’t print
change(i,j,NULL); //change any operand below that uses result of this expression
}
}
else
{
if(strcmp(arr[i].op1,arr[j].op1)==0&&strcmp(arr[i].op2,arr[j].op2)==0)
{
arr[j].flag=1;
change(i,j,NULL);
} } } } } }
void output()
{
int i=0;
printf("\nOptimized code is : ");
for(i=0;i<n;i++)
{
if(!arr[i].flag)
{
printf("\n%s %s %s %s",arr[i].op,arr[i].op1,arr[i].op2,arr[i].res);}
}}
void change(int p,int q,char *res)
{
int i;
for(i=q+1;i<n;i++)
{
if(strcmp(arr[q].res,arr[i].op1)==0)
if(res == NULL)

St.Joseph’s College of Engineering Page 41 of 59


strcpy(arr[i].op1,arr[p].res);
else
strcpy(arr[i].op1,res);
else if(strcmp(arr[q].res,arr[i].op2)==0)
if(res == NULL)
strcpy(arr[i].op2,arr[p].res);
else
strcpy(arr[i].op2,res);
}
}

OUTPUT:
[root@localhost ~]# vi ex7b.c
[root@localhost ~]# cc ex7b.c -o ex7b.out
[root@localhost ~]# ./ex7b.out

Enter the maximum number of expressions:5


Enter the input :
+ 4 4 t1
+ a t1 t2
- b a t3
+ a 8 t4
* t3 t4 t5
Optimized code is :
+ a 8 t2
- b a t3
* t3 t2 t5
RESULT:
Thus the above program has been executed successfully

EX.NO:8 STORAGE ALLOCATION STRATEGY


AIM:
To write a program to implement storage allocation strategies stack.

ALGORITHM:
Push:
Suppose STACK [SIZE] is a one dimensional array for implementing the stack, which will hold
the data items. TOP is the pointer that points to the top most element of the stack. Let DATA is
the data item to be pushed.
1. If TOP = SIZE – 1, then:
(a) Display “The stack is in overflow condition”

St.Joseph’s College of Engineering Page 42 of 59


(b) Exit
2. TOP = TOP + 1
3. STACK [TOP] = ITEM
4. Exit
Pop:
Suppose STACK [SIZE] is a one dimensional array for implementing the stack, which will hold
the data items. TOP is the pointer that points to the top most element of the stack. DATA is the
popped (or deleted) data item from the top of the stack.
1. If TOP < 0, then
(a) Display “The Stack is empty”
(b) Exit
2. Else remove the Top most element
3. DATA = STACK[TOP]
4. TOP = TOP – 1
5.Exit.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define size 5
struct stack {
int s[size];
int top;
} st;
int stfull() {
if (st.top >= size - 1)
return 1;
else
return 0;
}
void push(int item) {
st.top++;
st.s[st.top] = item;
}
int stempty() {
if (st.top == -1)
return 1;
else
return 0;
}
int pop() {
int item;
St.Joseph’s College of Engineering Page 43 of 59
item = st.s[st.top];
st.top--;
return (item);
}
void display() {
int i;
if (stempty())
printf("\nStack Is Empty!");
else {
for (i = st.top; i >= 0; i--)
printf("\n%d", st.s[i]);
}
}
int main() {
int item, choice,y;
char ans;
st.top = -1;
printf("\n\tImplementation Of Stack");
do {
printf("\nMain Menu");
printf("\n1.Push \n2.Pop \n3.Display \n4.exit");
printf("\nEnter Your Choice");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter The item to be pushed");
scanf("%d", &item);
if (stfull())
printf("\nStack is Full!");
else
push(item);
break;
case 2:
if (stempty())
printf("\nEmpty stack!Underflow !!");
else {
item = pop();
printf("\nThe popped element is %d", item);
}
break;

St.Joseph’s College of Engineering Page 44 of 59


case 3:
display();
break;
case 4:
exit(0);
}
printf("\nDo You want To Continue? ");
scanf(“%d”,&y);
} while (y==1);
return 0;
}
OUTPUT:
[root@localhost ~]# vi ex8.c
[root@localhost ~]# cc ex8.c -o ex8.out
[root@localhost ~]# ./ex8.out
Implementation Of Stack
Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1
Enter The item to be pushed 41
Do You want To Continue? 1
Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1

Enter The item to be pushed 54


Do You want To Continue? 1

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1

St.Joseph’s College of Engineering Page 45 of 59


Enter The item to be pushed 66
Do You want To Continue? 1

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 2

The popped element is 66


Do You want To Continue? 1

Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice3
54
41
Do You want To Continue? 0
RESULT
Thus the above program has been executed successfully

EX.NO: 9 DIRECTED ACYCLIC GRAPH (DAG)

AIM:
To write a program to construction of Directed Acyclic Graph(DAG)
ALGORITHM:
1)
Start the program
2)
Get the expression in the form of id1=id2 op1 id3 op2 id4.
3)
Get the expression like A=B+C+D.
4)
Leaf nodes represent identifiers, names or constants.
5)
Interior nodes represent operators.
6)
Interior nodes also represent the results of expressions or the identifiers/name
where the values are to be stored or assigned.
7) Stop the program
PROGRAM:
St.Joseph’s College of Engineering Page 46 of 59
#include<stdio.h>
#include<string.h>
struct node
{
char val;
node *rt,*lt;
};
char expr[20];
void rde()
{
printf(“\n enter the expression in the following form”);
printf(“\n\n id1=id2 op1 id3 op2 id4”);
printf(“\n\n Enter the expression:”);
scanf(“%s”,expr);
}
void main()
{
rde();
node *root=new node();
node *it1=new node();
node *newptr=new node();
node *l2=new node();
node *r2=new node();
node *newptr1=new node();
node *l3=new node();
for(int i=0;i<=strlen(expr);i++)
{
if(expr[i]==’=’)
{
root->val=expr[i];
root->lt=lt1;
lt1->val=expr[i-1];
it1->lt=NULL;
lt1->rt=NULL;
for(int j=I;j<=strlen(expr);j++)
{
if(expr[j]==’*’||expr[j]==’/’)
{
newptr->val=expr[j];
newptr->lt=l2;

St.Joseph’s College of Engineering Page 47 of 59


newptr->rt=r2;
l2->val=expr[j-1];
l2->lt=NULL;
l2->rt=NULL;
for(int k=0;k<=strlen(expr);k++)
{
if(expr[k]==’+’||expr[k]==’-‘)
{
newptr1->val=expr[k];
newptr1->lt=l3’
if(j<k)
l3->val=expr[k+1];
else
l3->val=expr[k-1];
l3->rt=NULL;
l3->lt=NULL;
newptr1->rt=newptr;
break;
}}}}
root->rt=newptr1;
}}
node *m=new node();
node *n=new node();
m=root;
n=NULL;
printf(“\n\n The DAG of the given expression id :\n\n”);
printf(“\n\n\tNode\tLeft\t Right\n\n”)
while(m!=NULL)
{
printf(“\n\t %e \t %c\t%c\n”,m->val,m->lt->val,n->rt->val);
n=m;
n=n->lt;
(n!=NULL)
{
if(n->lt->val==NULL)
n->lt->val=’_’;
if(n->lt->val==NULL)
n->->val=’_’;
printf(“\n\t %c\t %c\t %c\n”,n->val,n->lt,n->val,n->rt->val);
}m=m->rt;

St.Joseph’s College of Engineering Page 48 of 59


}}
OUTPUT:
[root@localhost ~]# vi exer9.c
[root@localhost ~]# cc exer9.c -o exer9.out
[root@localhost ~]# ./exer9.out
enter the expression in the following form
0: pred=1: 1
1: pred=2:
2: pred=1: 0
3: pred=0: 2 1
4: pred=0:
5: pred=0:
6: pred=0:
7: pred=0:
8: pred=0:
9: pred=0:
10: pred=0:
zerolist: 10 9 8 7 6 5 4 3
graph contains no cycle.

RESULT:
Thus the above program has been executed successfully
EX.NO: 10 BACK END COMPILER – ASSEMBLY LANGUAGE GENERATION

AIM:
To implement the back end of the compiler which takes the three address code and produces
the 8086 assembly language instructions that can be assembled and run using a 8086 assembler.
The target assembly instructions can be simple move, add, sub, jump. Also simple addressing
modes are used.
ALGORITHM:
1) Declare the header file.
2) Create a text file for intermediate code.
3) Open a file using FILE pointer.
4) Using strcmp () to find the operator and operand.
5) If conditional statement valid print relevant assembly code.
6) Close the program.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>

St.Joseph’s College of Engineering Page 49 of 59


#include<string.h>
#include <termios.h>
#include <unistd.h>
int label[20];
int no=0;
int main()
{
FILE *fp1,*fp2;
int check_label(int n);
char fname[10],op[10];
char operand1[8],operand2[10],ch;
int i=0,j=0,result;
printf("\n\n Enter filename of the intermediate code:");
scanf("%s",&fname);
fp1=fopen(fname,"r");
fp2=fopen("target.txt","w");
if(fp1==NULL||fp2==NULL) //25
{
printf("\nError Opening the file.");
getch();
exit(0);
}
while(!feof(fp1))
{
fprintf(fp2,"\n");
fscanf(fp1,"%s",op);
i++;
if(check_label(i))
{
fprintf(fp2,"\n label #%d:",i);
}//40
if(strcmp(op,"print")==0)
{
fscanf(fp1,"%s",result);
fprintf(fp2,"\n\t OUT %s",result);
}
if(strcmp(op,"goto")==0)
{
fscanf(fp1,"%s",operand2);
fprintf(fp2,"\n\t JMP label#%s",operand2);

St.Joseph’s College of Engineering Page 50 of 59


label[no++]=atoi(operand2);
}
if(strcmp(op,"[]=")==0)
{
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n\t STORE %s[%s],%s",operand1,operand2,result);
}
if(strcmp(op,"uminus")==0)
{
fscanf(fp1,"%s %s",operand1,result); //60
fprintf(fp2,"\n\t MOV R1,%s",operand1);
fprintf(fp2,"\n\t MOV %s,R1",result);
}
switch(op[0])
{
case '*':
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n\t MOV R0,%s",operand1);
fprintf(fp2,"\n\t MOV R1,%s",operand2);
fprintf(fp2,"\n\t MOV R0,R1");
fprintf(fp2,"\n\t MOV %s,R0",result);
break;
case '+':
fscanf(fp1,"%s %s %s", operand1,operand2,result);
fprintf(fp2,"\n\t MOV R0,%s",operand1);
fprintf(fp2,"\n\t MOV R1,%s",operand2);
fprintf(fp2,"\n\t ADD R0,R1");
fprintf(fp2,"\n\t MOV %s,R0",result);
break;
case '-':
fscanf(fp1,"%s %s %s", operand1,operand2,result);
fprintf(fp2,"\n\t MOV R0,%s",operand1);
fprintf(fp2,"\n\t MOV R1,%s",operand2);
fprintf(fp2,"\n\t SUB R0,R1");
fprintf(fp2,"\n\t MOV %s,R0",result);
break;
case '/':
fscanf(fp1,"%s %s %s", operand1,operand2,result);
fprintf(fp2,"\n\t MOV R0,%s",operand1);
fprintf(fp2,"\n\t MOV R1,%s",operand2);

St.Joseph’s College of Engineering Page 51 of 59


fprintf(fp2,"\n\t DIV R0,R1");
fprintf(fp2,"\n\t MOV %s,R0",result);
break;
case '%':
fscanf(fp1,"%s %s %s", operand1,operand2,result);
fprintf(fp2,"\n\t MOV R0,%s",operand1);
fprintf(fp2,"\n\t MOV R1,%s",operand2);
fprintf(fp2,"\n\t DIV R0,R1");
fprintf(fp2,"\n\t MOV %s,R0",result);
break;
case '=':
fscanf(fp1,"%s %s %s",operand1,result);
fprintf(fp2,"\n\t MOV %s %s",result,operand1);
break;
case '>':
j++;
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n\t JGT %s, %s label#%s",operand1,operand2,result);
label[no++]=atoi(result);
break;
case '<':
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n\t JLT %s, %s label#%s",operand1,operand2,result);
label[no++]=atoi(result);
break;
}
}
fclose(fp2);
fclose(fp1);
fp2=fopen("target.txt","r"); //120
if(fp2==NULL)
{
printf("\n Error opening the file.");
getch();
exit(0);
}
do
{
ch=fgetc(fp2);
printf("%c",ch);

St.Joseph’s College of Engineering Page 52 of 59


}while(ch!=EOF);
fclose(fp2);
getch();
return 0;
}
int check_label(int k)
{
int i;
for(i=0;i<no;i++)
{
if (k==label[i])
return 1;
}
return 0;
}
int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}

OUTPUT:
[root@localhost ~]# vi ex10.c
[root@localhost ~]# cc ex10.c -o ex10.out
[root@localhost ~]# ./ex10.out
Enter filename of the intermediate code: input.c
MOV R0,printf("
MOV R1,B
DIV R0,R1
MOV value,R0
MOV R0,printf("C
MOV R1,value
DIV R0,R1

St.Joseph’s College of Engineering Page 53 of 59


MOV is,R0
MOV R0,}
MOV R1,value
DIV R0,R1
MOV is,R0

RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 54 of 59


EX.NO:11 SIMPLE CODE OPTIMIZATION TECHNIQUES
AIM: To write a C program to implement Code Optimization Techniques.

ALGORITHM:
Input: Set of ‘L’ values with corresponding ‘R’ values.
Output: Intermediate code & Optimized code after eliminating common expressions.

PROGRAM:
#include<stdio.h>
#include<string.h>
#include <termios.h>
#include <unistd.h>
struct op
{
char l;
char r[20];
}
op[10],pr[10];
void main()
{
int a,i,k,j,n,z=0,m,q;
char *p,*l;
char temp,t;
char *tem;

printf("Enter the Number of Values:");


scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("left: ");
op[i].l=getche();
scanf("%c",&op[i].l);
printf("\nright: ");
scanf("%s",op[i].r);
}
printf("Intermediate Code\n") ;
for(i=0;i<n;i++)
{
printf("%c=",op[i].l);
printf("%s\n",op[i].r);
}
St.Joseph’s College of Engineering Page 55 of 59
for(i=0;i<n-1;i++)
{
temp=op[i].l;
for(j=0;j<n;j++)
{
p=strchr(op[j].r,temp);
if(p)
{
pr[z].l=op[i].l;
strcpy(pr[z].r,op[i].r);
z++;
}
}
}
pr[z].l=op[n-1].l;
strcpy(pr[z].r,op[n-1].r);
z++;
printf("\nAfter Dead Code Elimination\n");
for(k=0;k<z;k++)
{
printf("%c\t=",pr[k].l);
printf("%s\n",pr[k].r);
}
for(m=0;m<z;m++)
{
tem=pr[m].r;
for(j=m+1;j<z;j++)
{
p=strstr(tem,pr[j].r);
if(p)
{
t=pr[j].l;
pr[j].l=pr[m].l;
for(i=0;i<z;i++)
{
l=strchr(pr[i].r,t) ;
if(l)
{
a=l-pr[i].r;
printf("pos: %d",a);

St.Joseph’s College of Engineering Page 56 of 59


pr[i].r[a]=pr[m].l;
}
}
}
}
}
printf("Eliminate Common Expression\n");
for(i=0;i<z;i++)
{
printf("%c\t=",pr[i].l);
printf("%s\n",pr[i].r);
}
for(i=0;i<z;i++)
{
for(j=i+1;j<z;j++)
{
q=strcmp(pr[i].r,pr[j].r);
if((pr[i].l==pr[j].l)&&!q)
{
pr[i].l='\0';
strcpy(pr[i].r,'\0');
}
}
}
printf("Optimized Code\n");
for(i=0;i<z;i++)
{
if(pr[i].l!='\0')
{
printf("%c=",pr[i].l);
printf("%s\n",pr[i].r);
}
}
}
int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;

St.Joseph’s College of Engineering Page 57 of 59


newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
int getche(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
OUTPUT:
[root@localhost ~]# vi codeopt.c
[root@localhost ~]# cc codeopt.c -o ex11.out
codeopt.c: In function ‘main’:
codeopt.c:12: warning: return type of ‘main’ is not ‘int’
[root@localhost ~]# ./ex11.out
Enter the Number of Values:5
left: a
right: 9
left: b
right: c+d
left: e
right: c+d
left: f
right: b+e
left: r
right: f
Intermediate Code
a=9
b=c+d
e=c+d
f=b+e

St.Joseph’s College of Engineering Page 58 of 59


r=f

After Dead Code Elimination


b =c+d
e =c+d
f =b+e
r =f
pos: 2Eliminate Common Expression
b =c+d
b =c+d
f =b+b
r =f
Optimized Code
b=c+d
f=b+b
r=:f

RESULT:
Thus the above program has been executed successfully

St.Joseph’s College of Engineering Page 59 of 59

You might also like