[go: up one dir, main page]

0% found this document useful (0 votes)
22 views49 pages

Compiler-Design-Lab-Manual - 42 Pages

The document is a practical record for Compiler Design at Anna University, detailing various experiments related to compiler design, including the implementation of a symbol table, lexical analyzer, and YACC specifications. Each experiment includes an aim, introduction, algorithm, program code, and results. The practical exercises are conducted at JP College of Engineering and are part of the B.E. Computer Science and Engineering curriculum.

Uploaded by

mokipraba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views49 pages

Compiler-Design-Lab-Manual - 42 Pages

The document is a practical record for Compiler Design at Anna University, detailing various experiments related to compiler design, including the implementation of a symbol table, lexical analyzer, and YACC specifications. Each experiment includes an aim, introduction, algorithm, program code, and results. The practical exercises are conducted at JP College of Engineering and are part of the B.E. Computer Science and Engineering curriculum.

Uploaded by

mokipraba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

lOMoARcPSD|5556245

Compiler design lab


manual

Compiler Design (Anna University)

Scan to open on Studocu

Downloaded by PRABAKARAN SELVARAJ


lOMoARcPSD|5556245

Studocu is not sponsored or endorsed by any college or


university

Downloaded by PRABAKARAN SELVARAJ


Department of Computer Science and Engineering
PRACTICAL RECORD

Name: Reg.No:
Degree: B.E (Computer
and Engineering) Year: III Semester: V
Subject Code: CS3501
Subject Name: COMPILER DESIGN

Downloaded by PRABAKARAN SELVARAJ


JP COLLEGE OF ENGINEERING
(Run By DMI Sisters)
College Road, Ayikudy, Tenkasi-627852, TamilNadu,An ISO 9001:2008 Certified
Institution
Approved by AICTE, New Delhi Affiliated to Anna
University, Chennai

Department of Computer Science and Engineering


PRACTICAL RECORD

BONAFIDE CERTIFICATE
Certified that this is the bonafide record of practical exercises done by
Register number

of V Semester B.E CSE in the CS3501 – Compiler Design during the academic year 2023-2024 (ODD).

Staff-in-charge Head of the Department

Certified that this record has been submitted for the practical examination held on at JP
COLLEGE OF ENGINEERING, Ayikudy conducted by Anna University, Chennai.

INTERNAL EXAMINER EXTERNAL EXAMINER

Downloaded by PRABAKARAN SELVARAJ


Ex. No Date Experiment Name Page No Mark Staff
(10) Signature

Downloaded by PRABAKARAN SELVARAJ


Ex. No Date Experiment Name Page No Mark Staff
(10) Signature

Downloaded by PRABAKARAN SELVARAJ


EX. NO: 1
DATE:

IMPLEMENTATION OF SYMBOL TABLE


AIM:

To write a C program to implement a symbol table.

INTRODUCTION:

A Symbol table is a data structure used by a language translator such as a compiler or interpreter,
where each identifier in a program’s source code is associated with information relating to its declaration
or appearance in the source Possible entries in a symbol table: Name: a string.
• Attribute:
1. Reserved word
2. Variable name
3. Type Name
4. Procedure name
5. Constant name
• Data type
• Scope information: where it can be used. Storage allocation

SYMBOL TABLE

Downloaded by PRABAKARAN SELVARAJ


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 memoryaddress.
6. The steps are repeated till”$”is reached.
7. To reach a variable, enter the variable to the searched and symbol table has been checkedfor
corresponding variable, the variable along its address is displayed as result.
8. Stop the program.

PROGRAM:( IMPLEMENTATION OF SYMBOL TABLE)

#includecstdio.hS
#includecconio.hS
#includecmalloc.hS
#includecstring.hS
#includecmath.hS
#includecctype.hS void main()
{
int i=O,j=O,x=O,n,flag=O;
void *p,*add[15];
char ch,srch,b[15],d[15],c;
clrscr();
printf("expression terminated by $:");
while((c=getchar())!='$')
{
b[i]=c;i++;
}
n=i-1;
printf("given expression:");
i=O;
while(ic=n)
{
printf("%c",b[i]); i++;
}
printf("symbol table\n");

Downloaded by PRABAKARAN SELVARAJ


printf("symbol\taddr\ttype\n");
while(jc=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\n",c,p);
}
else
{
ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(c);
add[x]=p;
d[x]=c; printf("%c\t%d\
tidentifier\n",c,p); x++;
}}
} j+
+;
}
printf("the symbol is to be searched\n");
srch=getch();
for(i=O;ic=x;i++)
{
if(srch==d[i])
{
printf("symbol found\n"); printf("%c%s%d\
n",srch,"@address",add[i]);

Downloaded by PRABAKARAN SELVARAJ


flag=1;
}
}
if(flag==O)
printf("symbol not found\n");
getch();
}

OUTPUT:

RESULT:

Thus the C program to implement the symbol table was executed and the output is verified.

Downloaded by PRABAKARAN SELVARAJ


EX. NO:2
DATE:

DEVELOP A LEXICAL ANALYZER TO RECOGNIZE A FEWPATTERNS IN C


AIM:

To Write a C program to develop a lexical analyzer to recognize a few patterns in C.


INTRODUCTION:

Lexical analysis is the process of converting a sequence of characters (such as in a computer


program of web page) into a sequence of tokens (strings with an identified “meaning”). A program
that perform lexical analysis may be called a lexer, tokenize or scanner

TOKEN
A token is a structure representing a lexeme that explicitly indicates its categorization
for the Purpose of parsing. A category of token is what in linguistics might be called a part-of-
speech.Examplesof token categories may include “identifier” and “integer literal”, although the
set of Token differ in different programming languages.
The process of forming tokens from an input stream of characters is called tokenization.
Consider this expression in the C programming language:Sum=3 + 2;

Tokenized and represented by the following table:

Lexeme Token category


Sum “identifier”
= “assignment operator”
3 “integer literal”
+ “addition operator”
2 “integer literal”
; “end of the statement”

Downloaded by PRABAKARAN SELVARAJ


ALGORITHM:

1. Start the program


2. Include the header files.
3. Allocate memory for the variable by dynamic memory allocation function.
4. Use the file accessing functions to read the file.
5. Get the input file from the user.
6. Separate all the file contents as tokens and match it with the functions.
7. Define all the keywords in a separate file and name it as key.c
8. Define all the operators in a separate file and name it as open.c
9. Give the input program in a file and name it as input.c 10. Finally print the output after
recognizing all the tokens.
10. Stop the program.

PROGRAM:

(DEVELOP A LEXICAL ANALYZER TO RECOGNIZE A FEW PATTERNS IN C)

#include<stdio.h>
#include<conio.h
>
#include<ctype.h>
#include<string.h
> void main()
{
FILE *fi,*fo,*fop,*fk;
intflag=0,i=1;
char c,t,a[15],ch[15],file[20];
clrscr();
printf("\n Enter the File Name:");
scanf("%s",&file);
fi=fopen(file,"r");
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi); while(!
feof(fi))
{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.'==1))
fputc(c,fo);
else
{ if(c=='\n')
fprintf(fo,"\t$\t");
else fprintf(fo,"\t%c\
t",c);
}

Downloaded by PRABAKARAN SELVARAJ


c=getc(fi);

Downloaded by PRABAKARAN SELVARAJ


}
fclose(fi);
fclose(fo);
fi=fopen("inter.c","r");
printf("\n Lexical Analysis");
fscanf(fi,"%s",a);
printf("\n Line: %d\n",i++);
while(!feof(fi))
{
if(strcmp(a,"$")==0)
{
printf("\n Line: %d \n",i++);
fscanf(fi,"%s",a);
}
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
scanf("%s",&file);
fi=fopen(file,"r");
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi); while(!
feof(fi))
{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.'==1))
fputc(c,fo);
else
{
if(c=='\n')
fprintf(fo,"\t$\t");
else fprintf(fo,"\t%c\
t",c);
}
c=getc(fi);
}
fclose(fi);
fclose(fo);
fi=fopen("inter.c","r");
printf("\n Lexical Analysis");
fscanf(fi,"%s",a);
printf("\n Line: %d\n",i++);
while(!feof(fi))

Downloaded by PRABAKARAN SELVARAJ


{
if(strcmp(a,"$")==0)
{
printf("\n Line: %d \n",i++);
fscanf(fi,"%s",a);
}
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
scanf
FILE
Include stdio.h conio.h iostream.h Oper.C:
( open para
) closepara
{ openbrace
} closebrace
< lesser
> greater
" doublequote ' singlequote
: colon
; semicolon
# preprocessor
= equal
== asign
% percentage
^ bitwise
& reference
* star
+ add
- sub
\ backslash
/ slash

Input.C:
#include "stdio.h"
#include
"conio.h" void
main()
{
int a=10,b,c; a=b*c;
getch();
}

Downloaded by PRABAKARAN SELVARAJ


OUTPUT:

RESULT:
Thus the above program for developing the lexical the lexical analyzer and recognizing
the fewpattern s in C is executed successfully and the output is verified.

Downloaded by PRABAKARAN SELVARAJ


EX.NO:3
DATE:

IMPLEMENTATION OF LEXICAL ANALYZER USING LEX TOOL

AIM:

To write a program to implement the Lexical Analyzer using lex tool.

INTRODUCTION:

THEORY:
 A language for specifying lexical analyzer.
 There is a wide range of tools for construction of lexical analyzer. The majority of
thesetools are based on regular expressions.
 The one of the traditional tools of that kind is lex.
LEX:

 The lex is used in the manner depicted. A specification of the lexical analyzer is
preferred by creating a program lex.1 in the lex language.
 Then lex.1 is run through the lex compiler to produce a ‘c’ program lex.yy.c.
 The program lex.yy.c consists of a tabular representation of a transition diagram
constructed from the regular expression of lex.1 together with a standard routine that uses
table of recognize leximes.
 Lex.yy.c is run through the ‘C’ compiler to produce as object program a.out, which is the
lexical analyzer that transform as input stream into sequence of tokens.

LEX SOURCE:

Downloaded by PRABAKARAN SELVARAJ


ALGORITHM:
1. Start the program
2. Lex program consists of three parts.
3. Declaration %% 4. Translation rules %%
5. Auxiliary procedure.
6. The declaration section includes declaration of variables, main test, constants and regular
7. Definitions.
8. Translation rule of lex program are statements of the form
9. P1{action}
10. P2{action}
11. …..
12. …...
13. Pn{action}
14. Write program in the vi editor and save it with .1 extension.
15. Compile the lex program with lex compiler to produce output file as lex.yy.c.
16. Eg. $ lex filename.1
17. $gcc lex.yy.c-11
18. Compile that file with C compiler and verify the output.

PROGRAM:
(LEXICAL ANALYZER USING LEX TOOL)

#includecstdio.hS
#includecctype.hS
#includecconio.hS
#includecstring.hS
char vars[1OO][1OO];
int vcnt;
char input[1OOO],c;
char token[5O],tlen;
int state=O,pos=O,i=O,id;
char *getAddress(char str[])
{
for(i=O;icvcnt;i++)
if(strcmp(str,vars[i])==O)
return vars[i];
strcpy(vars[vcnt],str);
return vars[vcnt++];
}
int isrelop(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='^')
return 1;

Downloaded by PRABAKARAN SELVARAJ


else return O;
}
int main(void)
{
clrscr();
printf("Enter the Input String:");
gets(input);
do
{
c=input[pos];
putchar(c);
switch(state)
{
case O:
if(isspace(c))
printf("\b");
if(isalpha(c))
{
token[O]=c;
tlen=1;
state=1;
}
if(isdigit(c)) state=2;
if(isrelop(c)) state=3;
if(c==';') printf("\
tc3,3S\n"); if(c=='=')
printf("\tc4,4S\n");
break;
case 1:
if(!isalnum(c))
{
token[tlen]='\o'; printf("\b\tc1,%pS\
n",getAddress(token)); state=O;
pos--;
}
else token[tlen+
+]=c; break;
case 2:
if(!isdigit(c))
{
printf("\b\tc2,%pS\n",&input[pos]);
state=O;

Downloaded by PRABAKARAN SELVARAJ


pos--;
}
break;
case 3:
id=input[pos-1];
if(c=='=')
printf("\tc%d,%dS\n",id*1O,id*1O);
else{
printf("\b\tc%d,%dS\
n",id,id); pos--;
}state=O;
break;
}
pos++;
}
while(c!=O);
getch();
return O;
}

OUTPUT:

RESULT:
Thus the program for the exercise on lexical analysis using lex has been successfully
executed andoutput is verified.

Downloaded by PRABAKARAN SELVARAJ


EX.NO:4
DATE:

GENERATE YACC SPECIFICATION FOR A FEW SYNTACTIC


CATEGORIES.

AIM :

To write a c program to do exercise on syntax analysis using YACC.

INTRODUCTION :
YACC (yet another compiler) is a program designed to produce designed to compile a
LALRgrammar and to produce the source code of the synthetically analyses of the language
produced bythe grammar.

ALGORITHM :
1. Start the program.

2. Write the code for parser. l in the declaration port.

3. Write the code for the ‘y’ parser.

4. Also write the code for different arithmetical operations.

5. Write additional code to print the result of computation.

6. Execute and verify it.

7. Stop the program.

PROGRAM:

PROGRAM TO RECOGNIZE A VALID ARITHMETIC EXPRESSION THAT USES


OPERATOR +, - , * AND /.

#include<stdio.h>
#include<conio.h
> void main()
{
char s[5];
clrscr();
printf("\n Enter any operator:");
gets(s);
switch(s[0])
{
case'>':
if(s[1]=='=')
printf("\n Greater than or equal");
else

Downloaded by PRABAKARAN SELVARAJ


printf("\n Greater than");
break;
case'<':
if(s[1]=='=')
printf("\n Less than or equal");
else
printf("\nLess than");
break;
case'=':
if(s[1]=='=')
printf("\nEqual to");
else printf("\
nAssignment"); break;
case'!':
if(s[1]=='=')
printf("\nNot Equal");
else
printf("\n Bit Not");
break;
case'&':
if(s[1]=='&') printf("\
nLogical AND"); else
printf("\n Bitwise AND");
break;
case'|':
if(s[1]=='|') printf("\
nLogical OR"); else
printf("\nBitwise OR");
break;
case'+':
printf("\n Addition");break;
case'-': printf("\nSubstraction");break;
case'*': printf("\nMultiplication");
break;
case'/': printf("\nDivision");
break;
case'%': printf("Modulus");
break;
default:
printf("\n Not a operator");
}

Downloaded by PRABAKARAN SELVARAJ


getch();
}

OUTPUT:

RESULT:
Thus the program for the exercise on the syntax using YACC has been executed
successfully and Output is verified.

Downloaded by PRABAKARAN SELVARAJ


EX.NO:5
DATE:

PROGRAM TO RECOGNISE A VALID VARIABLE WHICH STARTS WITH ALETTER


FOLLOWED BY ANY NUMBER OF LETTERS OR DIGITS

AIM:

To write a yacc program to check valid variable followed by letter or digits.

ALGORITHM:
1. Start the program.
2. Reading an expression.
3. Checking the validating of the given expression according to the rule using yacc .
4. Using expression rule print the result of the given values.
5. Stop the program.
PROGRAM :

variable_test.l
%{
/* This LEX program returns the tokens for the Expression */
#include "y.tab.h"
%}
%%
"int " {return INT;} "float" {return FLOAT;}
"double" {return DOUBLE;} [a-zA-Z]*[O-9]*{
printf("\nIdentifier is %s",yytext);
return ID;
}
return yytext[O];
\n return O;
int yywrap()
{
return 1;
}
variable_test.y
%{
#include
/* This YACC program is for recognising the Expression*/
%}
%token ID INT FLOAT DOUBLE
%% D; T L ;
L:L,ID |ID ;
T:INT |FLOAT |DOUBLE ;
%%
extern FILE *yyin; main(

Downloaded by PRABAKARAN SELVARAJ


{
do
{
yyparse();
}while(!feof(yyin));
}
yyerror(char*s)
{
}

OUTPUT:

RESULT:
Thus the program for the exercise on the syntax using YACC has been executed
successfully and Output is verified.

Downloaded by PRABAKARAN SELVARAJ


EX.NO.6
DATE:

IMPLEMENTATION OF CALCULATOR USING LEX AND YACC

AIM:
To write a program for implementing a calculator for computing the given expression using
semantic rules of the YACC tool and LEX.

ALGORITHM:
1. A Yacc source program has three parts as follows:
Declarations %% translation rules %% supporting C routines
2. Declarations Section: This section contains entries that:
i. Include standard I/O header file.
ii. Define global variables.
iii. Define the list rule as the place to start processing.
iv. Define the tokens used by the parser. v. Define the operators and
their precedence.
3. Rules Section: The rules section defines the rules that parse the input stream.
Each rule of a grammar production and the associated semantic action.
4. Programs Section: The programs section contains the following subroutines.
Because these subroutines are included in this file, it is not necessary to use the
yacc library when processing this file.
5. Main- The required main program that calls the yyparse subroutine to start
the program.
6. yyerror(s) -This error-handling subroutine only prints a syntax error message.
7. yywrap -The wrap-up subroutine that returns a value of 1 when the end of input
occurs. The calc.lex file contains include statements for standard input and
output, as programmar file information if we use the -d flag with the yacc
command. The y.tab.h file contains definitions for the tokens that the parser
program uses.
8. calc.lex contains the rules to generate these tokens from the input stream.

PROGRAM:

%{
#include cstdio.hS
int op=O,i; float a,b;
%}
dig[O-9]+|([O-9]*)"."([O-9]+)
add "+"
sub "-"mul"*
" div "/"
pow "^"ln \n
%%

Downloaded by PRABAKARAN SELVARAJ


{dig}{digi();}

Downloaded by PRABAKARAN SELVARAJ


{add}{op=1;}
{sub}{op=2;}
{mul}{op=3;}
{div}{op=4;}
{pow}{op=5;}
{ln}
{printf("\n the result:%f\n\n",a);}
%%
digi()
{
if(op==O) a=atof(yytext);else
{
b=atof(yytext); switch(op)
{
case 1:
a=a+b; break; case 2:
a=a-b; break; case 3:
a=a*b; break; case 4:
a=a/b; break; case 5:
for(i=a;bS1;b--) a=a*i;
break;
}
op=O;
}
}
main(int argv,char *argc[])
{
yylex();
}
yywrap()
{
return 1;
}

OUTPUT:
Lex cal.l
Cc lex.yy.c-ll a.out
4*8
The result=32

RESULT:
Thus the program for the exercise on the syntax using YACC has been executed
Successfully and Output is verified.

Downloaded by PRABAKARAN SELVARAJ


EX.NO:7
DATE:

IMPLEMENTATION OF TYPE CHECKING

AIM:
To write a C program for implementing type checking for given expression.

ALGORITHM:
The type analysis and type checking is an important activity done in the semantic
analysis phase. The need for type checking is
1. To detect the errors arising in the expression due to incompatible operand.
2. To generate intermediate code for expressions due to incompatible operand.

ALGORITHM:
1. Start a program.
2. Include all the header files.
3. Initialize all the functions and variables.
4. Get the expression from the user and separate into the tokens.
5. After separation, specify the identifiers, operators and number.
6. Print the output.
7. Stop the program.

PROGRAM:
( TYPE CHECKING)
#include cstdio.hS
charstr[5O],opstr[75];
int f[2][9]={2,3,4,4,4,O,6,6,O,1,1,3,3,5,5,O,5,O};
int col,col1,col2;
char c;
swt()
{
switch(c)
{

Downloaded by PRABAKARAN SELVARAJ


case'+':
col=O
;
break;
case'-':
col=1;
break;
case'*'
:
col=2;
break;
case'/':
col=3;
break;
case'^'
:
col=4;
break;
case'('
:
col=5;
break;
case')'
:
col=6;
break;
case'd'
:
col=7;
break;
case'$'
:
col=8;
break;
default
:
printf("\nTERMINAL MISSMATCH\n");
exit(1);
}
return O;
}
main() {
int i=O,j=O,col1,cn,k=O;
int t1=O,foundg=O;
char temp[2O];
clrscr();
printf("\nEnter arithmetic expression:");
scanf("%s",&str);

Downloaded by PRABAKARAN SELVARAJ


while(str[i]!='\O')
i++;
str[i]='$';
str[++i]='\O';
printf("%s\n",str);
come:
i=O;

Downloaded by PRABAKARAN SELVARAJ


opstr[O]='$';
j=1;
c='$';
swt(); col1=col; c=str[i];
swt(); col2=col; if(f[1]
[col1]Sf[2][col2])
{
opstr[j]='S';
j++;
}
else if(f[1][col1]cf[2][co2])
{
opstr[j]='c';
j++;
}
else
{
opstr[j]='='; j++;
}
while(str[i]!='$')
{
c=str[i];
swt();
col1=col;
c=str[++i];
swt();
col2=col;
opstr[j]=str[--i];
j++;
if(f[O][col1]Sf[1][col2])
{
opstr[j]='S';
j++;
}
else if(f[O][col1]cf[1][col2])
{
opstr[j]='c';
j++;
}
else
{
opstr[j]='=';
j++;
} i+
+;
}
opstr[j]='$';

Downloaded by PRABAKARAN SELVARAJ


opstr[++j]='\O';
printf("\nPrecedence Input:%s\n",opstr);
i=O;
j=O;
while(opstr[i]!='\O')
{
foundg=O; while(foundg!=1)
{
if(opstr[i]=='\O')
goto redone;
if(opstr[i]=='S')
foundg=1;
t1=i;
i++;
}
if(foundg==1)
for(i=t1;iSO;i--
)
if(opstr[i]=='c')
break; if(i==O){
printf("\nERROR\
n"); exit(1);
}
cn=i;
j=O;
i=t1+1;
while(opstr[i]!='\O')
{
temp[j]=opstr[i];
j++;
i++;
}
temp[j]='\O';
opstr[cn]='E';
opstr[++cn]='\O';
strcat(opstr,temp);
printf("\n%s",opstr);
i=1;
}
redone:
k=O;
while(opstr[k]!='\O')
{ k+
+;
if(opstr[k]=='c')
{
Printf("\nError");
exit(1);

Downloaded by PRABAKARAN SELVARAJ


}}

Downloaded by PRABAKARAN SELVARAJ


if((opstr[O]=='$')&&(opstr[2]=='$'))
goto sue;
i=1;
while(opstr[i]!='\O')
{
c=opstr[i]; if(c=='+'||c=='*'||
c=='/'||c=='$')
{
temp[j]=c;
j++;
} i+
+;
}
temp[j]='\O';
strcpy(str,temp);
goto come;
sue:
printf("\n success");
return O;
}

OUTPUT:

Downloaded by PRABAKARAN SELVARAJ


RESULT:
Thus the program has been executed successfully and Output is verified.

Downloaded by PRABAKARAN SELVARAJ


EX.NO:8
DATE:

IMPLEMENT CONTROL FLOW ANALYSIS AND DATA FLOW ANALYSIS

AIM:

To Writs a C program to implement data flow and control flow analysis.

INTRODUCTION:

 Data flow analysis is a technique for gathering information about the possible set of value
calculated at various points in a computer program.
 Control flow analysis can be represent by basic blocks. It depicts how th program control
is being passed among the blocks.
ALGORITHM:

1. Start the program


2. Declare the necessary variables
3. Get the choice to insert, delete and display the values in stack
4. Perform PUSH() operation
a. t = newnode()
b. Enter info to be inserted
c. Read n
d. t ->info= n
e. t ->next=top
f. top = t
g. Return
5. Perform POP() operation
a. If (top=NULL)
b. Print”underflow”
c. Return
d. X=top
e. Top=top->next
f. Delnode(x)
g. Return.
6. Display the values.
7. Stop the program.

Downloaded by PRABAKARAN SELVARAJ


PROGRAM:
(DATA FLOW AND CONTROL FLOW ANALYSIS)
#includecconio.hS
struct stack
{
int no;
struct stack *next;
}
*start=null typedef struct stack st;
voidpush();
int pop();
voiddisplay();
voidmain()
{
char ch;
int choice, item;
do
{
clrscr();
printf(“\n1:push”);
printf(“\n2:pop”);
printf(“\n3:display”);
printf(“\n enter your
choice”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
push();
break;
case 2:
item=pop();
printf(“the delete element in %d”,item);
break;
case 3:
display();
break;
default:
printf(“\nwrong choice”);
};
printf(“\n do you want to continue(y/n”);
fflush(stdin);
scanf(“%c”,&ch);
}

Downloaded by PRABAKARAN SELVARAJ


while(ch==’y’||ch==’y’);

Downloaded by PRABAKARAN SELVARAJ


}
Void push()
{
st*node;
node=(st*)malloc(sizeof(st));
printf(“\n enter the number to be
insert”); scanf(“%d”,&node-Sno);
node-Snext=start;
start=node;
}
intpop();
{
st*temp; temp=start;
if(start==null)
{
printf(“stack is already empty”);
getch();
exit();
}
else
{
start=start-Snext;
free(temp);
}
return(temp-Sno);
}
void display()
{
st*temp;
temp=start;
while(temp-Snext!=null)
{
printf(“\nno=%d”,temp-
Sno); temp=temp-Snext;
}
printf(“\nno=%d”,temp-Sno);
}

Downloaded by PRABAKARAN SELVARAJ


OUTPUT:

Downloaded by PRABAKARAN SELVARAJ


RESULT:
Thus the C program to implement data flow and control flow analysis was executed
successfully.

Downloaded by PRABAKARAN SELVARAJ


EX.NO: 9
DATE:
IMPLEMENT THE BACK END OF THE COMPILER

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.
INTRODUCTION:
A compiler is a computer program that implements a programming language specification to
“translate” programs, usually as a set of files which constitute the source code written in source
language,into their equivalent machine readable instructions(the target language, often having a
binary form knownas object code). This translation process is called compilation.
BACK END:
 Some local optimization
 Register allocation
 Peep-hole optimization
 Code generation
 Instruction scheduling
The main phases of the back end include the following:
 Analysis: This is the gathering of program information from the intermediate
representation derived from the input; data-flow analysis is used to build use-define chains,
together with dependence analysis, alias analysis, pointer analysis, escape analysis etc.

 Optimization: The intermediate language representation is transformed into functionally


equivalent but faster (or smaller) forms. Popular optimizations are expansion, dead,
constant, propagation, loop transformation, register allocation and even automatic
parallelization.

 Code generation: The transformed language is translated into the output language, usually
the native machine language of the system. This involves resource and storage decisions,
such as deciding which variables to fit into registers and memory and the selection and
scheduling of appropriate machine instructions along with their associated modes. Debug
data may also need to be generated to facilitate debugging

Downloaded by PRABAKARAN SELVARAJ


ALGORITHM:

1. Start the program


2. Open the source file and store the contents as quadruples.
3. Check for operators, in quadruples, if it is an arithmetic operator generator it or if
assignment operator generates it, else perform unary minus on register C. 4. Write the
generated code into output definition of the file in outp.c
5. Print the output.
6. Stop the program

PROGRAM:
(BACK END OF THE COMPILER)

#includecstdio.hS
#includecstdio.hS
#includecconio.hS
#includecstring.h
S void main()
{
char icode[1O][3O],str[2O],opr[1O];
int i=O;
clrscr();
printf("\n Enter the set of intermediate code (terminated by exit):\n");
do
{
scanf("%s",icode[i]);
}
while(strcmp(icode[i++],"exit")!=O);
printf("\n target code generation");
printf("\n************************");
i=O;
do
{
strcpy(str,icode[i]);
switch(str[3])
{
case '+': strcpy(opr,"ADD");
break;
case '-': strcpy(opr,"SUB");
break;
case '*':
strcpy(opr,"MUL");
break;
case '/': strcpy(opr,"DIV");
break;
}

Downloaded by PRABAKARAN SELVARAJ


printf("\n\tMov%c,R%d",str[2],i);
printf("\n\t%s%c,R%d",opr,str[4],i);
printf("\n\tMov R%d,%c",i,str[O]);
}
while(strcmp(icode[++i],"exit")!=O);
getch();
}

OUTPUT:

RESULT:
Thus the program was implemented to the TAC has been successfully executed.

Downloaded by PRABAKARAN SELVARAJ


EX.NO:10
DATE:

IMPLEMENTATION OF SIMPLE CODE OPTIMIZATION TECHNIQUES

AIM:

To write a C program to implement simple code optimization technique.

INTRODUCTION:

Optimization is a program transformation technique, which tries to improve the code by


making itconsume less resource (i.e. CPU, memory) and deliver high speed.
In optimization, high-level general programming constructs are replaced by very
efficient lowlevel programming codes. A code optimizing process must follow the three rules
given below:
The output code must not, in any way, change the meaning of the program.
 Optimization should increases the speed of the program and if possible, the program
should demand less number of resources.
 Optimization should itself be fast and fast and should not delay the overall compiling
process.
Efforts for an optimized code can be made at various levels of compiling the process.
 At the beginning, users can change/rearrange the code or use better algorithms to write
the code.
 After generating intermediate code, the compiler can modify the intermediate code by
address calculations and improving loops.
 While producing the target machine code, the compiler can make use of memory
hierarchy and cpu registers.
Optimization can be categorized broadly into two types: Machine independent and Machine
dependent.

Machine independent optimization


In this optimization, the compiler takes in the intermediate code and transforms a part
of the codethat does not involve any CPU registers and/or absolute memory locations.

For Example:
Do
{
item=1O;
value=value+item;
}
while(valuec1OO);
This code involves repeated assignment of the identifier item, which if weput this way:
item=1O; do
{
value=value+item;
}
while(valuec1OO);

Downloaded by PRABAKARAN SELVARAJ


Should not only save the cpu cycles, but can be used on any processor.

Machine dependent optimization

Machine dependent optimization is done after the target code has been generated and when
the code is transformed according to the target machine architecture. It involves CPU registers and
may have absolute memory references rather than relative references. Machine- dependent
optimizers put efforts to take maximum advantage of memory hierarchy.

ALGORITHM:

1. Start the program


2. Declare the variables and functions.
3. Enter the expressionand state it in the variable a, b, c.
4. Calculate the variables b & c with ‘temp’ and store it in f1 and f2.
5. If(f1=null && f2=null) then expression could not be optimized.
6. Print the results.
7. Stop the program.

PROGRAM:
(SIMPLE CODE OPTIMIZATION TECHNIQUE)

Before:
Using for :

#includeciostream.hS
#include cconio.hS
int main()
{
int i, n;
int
fact=1;
cout cc"\nEnter a number: " cin SSn;
for(i=n;iS=1;i--)
fact=fact *i;
coutcc"The factoral value is: "ccfact;
getch();
return 0;
}

Downloaded by PRABAKARAN SELVARAJ


OUTPUT:

Downloaded by PRABAKARAN SELVARAJ


Afte
(SIMPLE CODE OPTIMIZATION TECHNIQUE)

Using do-while:

#includeciostream.hS
#includecconio.hS void main()
{
clrscr();int n,f;
f=1;
coutcc"Enter the number:\n";
cinSSn;
do
{
f=f*n
; n--;
}
while(nSO);
coutcc"The factorial value is:"ccf;
getch();
}

OUTPUT:

RESULT:
Thus the Simple Code optimization technique is successfully executed.

Downloaded by PRABAKARAN SELVARAJ

You might also like