Você está na página 1de 60
JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. CS6612 / 116612 - COMPILER LABORATORY LTPC OBJECTIVES: The student should be made to: Be exposed to compiler writing tools. Learn to implement the different Phases of compiler + Be familiar with control flow and data flow analysis + Learn simple optimization techniques LIST OF EXPERIMENTS: 1. Implementation of Symbol Table 2. Develop a lexical analyzer to recognize a few patterns in C. (Ex. identifiers, constants, comments, operators ete.) 3. Implementation of Lexical Analyzer using Lex Tool 4. Generate YACC specification for a few syntactic categories. a) Program to recognize a valid arithmetic expression that usesoperator +, - , * and /. b) Program to recognize a valid variable which starts with a letterfollowed by any number of letters or digits. d)Implementation of Calculator using LEX and YACC 5. Convert the BNF rules into Yace form and write code to generate Ab: 6, Implement type checking 7. Implement control flow analysis and Data flow Analysis 8, Implement any one storage allocation strategies(Heap,Stack,Static) 9. Construction of DAG 10. 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. 11. Implementation of Simple Code Optimization Techniques (Constant Folding., etc.) ct Syntax Tree. TOTAL: 45 PERIODS OUTCOMES: At the end of the course, the student should be able to % Implement the different Phases of compiler using tools + Analyze the control flow and data flow of a typical program % Optimize a given program “© Generate an assembly language program equivalent to a source language program LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS: Standalone desktops with C / C++ compiler and Compiler writing tools 30 Nos. (on Server with C/C++ compiler and Compiler writing tools supporting 30 terminals or more. LEX and YACC N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex. No: 1 SYMBOL TABLE IMPLEMENTATI! Date 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 ‘S? 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 CODING: #include #include #include #include #include #include void main() { int i=0,4=0,x=0,n,flag=0; void *p, *add[5]; c ch, srch,b[15],d[15],c; printf ("Expression terminated by $ : "); while ((c=getchar())!='$"') { blil=c; itt; N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. } n=i-1; printf (" i=0; while (i<=n) { printf ("te",b[i]); itt; } printf£("\n Symbol Table\n"); printf ("Symbol\taddr\ttype") ; while (j<=n) tl c=bl5]i if (isalpha (toascii(c))) { iven Expression : "); if( { pemalloc(c) ; add [x] =p; dix]=c; printf ("Sc\tSd\tidentifier",c,p); t else { ch=b[j+1]; if (ch=="+"| | ch: i p=malloc(c); add[x]=p; d[x]=c; printf ("\n%c\t%d\tidentifier\n",c,p); xtt; byt Itt: t printf£("\nThe symbol is to be searched"); srch=getch (); for (i=0; i<=x; i++) { N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING $6612 / 116612 - COMPILER LABORATORY dti]) print£("\nSymbol Found”); @address ",add[i]); print£("\nSymbol Not Found"); getch(); I OUuTPt res Picererares identifier identifier cory emreersereies ory Sens a ear) RESULT: Thus the above the program is executed and the required output is obtained. N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex.No :2 | | IMPLEMENTATION OF LEXICAL ANALYSIS IN C Date: | aC 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 CODING: #include #include #include void keyw(char *p); int i=0,id=0,kw=0,num=0, o0p=0; char keys[32] [10]=("auto", "break", "case", "char", "const", “continu en, "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", N.SENTHIL MURUGAN AP/CSE e-Mail : sendi 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"); main () { char ch, str[25],seps [15 \t\n, 7 0.0) U#\ "<2", oper [J=" 1876 —t==|.<>/2"7 int 4; char fname [50]; FILE *f1; //elrser(); printf ("enter file path (drive:\\fold\\ filename) \n") ; scanf("$s", fname) ; £1 = fopen(fname,"r"); //£1 = fopen("Input", "0"); if (£1==NULL) ( goto END; } while ( (ch=fgetc(£1))! { for (4=0; 4<=14; j++) OF) print£("%c is an operator\n",ch); opt+; str[i]="\0'; keyw(str); } } for (j=0; j<=14; j++) { N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. if(i 1) break; while (ch ( print£("%e", ch); ry dl } printf("&c is a header file\n",ch); fgetc (£1); break; } if(c { do { ch=fgetc (£1); print£("%c",ch) ; }while (cl print£("\b is an argument \n"); isl; break; } str[i]="\0'; keyw(str); N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. str[i]=ch; itt; else i=0; ) printf ("Keywords: %d\nIdentifiers: %d\nOperators: d\nNumbers: %d\n",kw, id, op, num) ; J/getch (); END: printf ("file not found"); } void keyw(char *p) i int k, £lag=0; for (k=0;k<=31;k++) t if (st romp (keys [k] ,p)=-0) { printf ("ts is a keyword\n",p); kwtt; flag-1; break; } 1 if (flag--0) t if (isdigit (p[0])) t printf ("ts is a number\n",p); num++7 } N.SENTHIL MURUGAN AP/CSE e- Mai JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. else i //4£ (p[0] !=13eep[0] !=10) if (p[0] !="\0") { printf ("ts is an identifier\n",p); idtt; } INPUT: (INPUT. #include #include void main() { Int a,b,c; c=atb; printi(“The sum is %d",¢); getch(); } N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING $6612 / 116612 - COMPILER LABORATORY OUTPUT c:\Flex \Windows\EditPlusPortable>a lenter File path (dive:\fold\filename? Fates Htinclude is a header file Peete ser an identifier identifier identifier identifier Pesaas identifier iors operator identifier Pers an operator an identifier an operator an identifier an identifier printf is an identifier The is an identifier SeCeUMetCitetetry is an identifier PU Sa dé is an identifier ic is an identifier lgetch is an identifier C:\Flex Windows\EditPlusPortable>. RESULT Thus the above the program is executed and the required output is obtained. N.SENTHIL MURUGAN AP/CSE €- Mail: sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. eNOS IMPLEMENTATION OF LEXICAL ANALYSER USING Date: LEX TOOL AIM: To write a lex program to implement the lexical analyzer. ALGORITHM: 1. Start the program 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 CODIN identifier [_a-zA-z] [_a-zA-z0-9]* ae #.* (printf("\n%s is a PREPROCESSOR DIRECTIVE", yytext);) int | double N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. float | char | while | for | do | Herat break | continue | void | switch | case | long | struct | const | typedef | return | else | goto {print£("\n\t%s is a KEYWORD", yytext);} "/*" (COMMENT=1; print£("\n\n\t COMMENT ENDS\n");} (identifier) \( (if (!COMMENT) printf£("\n\t %s ) is a FUNCTION \n",yytext);} \{ (Af ({commENT) print£("\n\t BLOCK BEGINS"); } \} (AE (1COMMENT) print£("\n\t BLOCK ENDS"); } (identifier) (\[[0-9]*\])? (if (COMMENT) printf("\n\t %s IDENTIFIER", yytext) ;) \".#\" (4 £(!COMMENT) printf£("\n\t %s is a STRING", yytext);} [0-9]+ {if (!COMMENT) printf("\n\t %s is a NUMBER", yytext);} N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. \) QF)? {4 £({COMMENT) print£("\n\t");ECHO; print£("\n");} \( ECHO; = (if (1COMMENT) print£("\n\t%s is an ASSIGNMENT OPERATOR", yytext);} \<= | ve {if (COMMENT) printf£("\n\t%s is a RELATIONAL OPERATOR", yytext) ;} \FI\SI\FI\BI\/ (4£(1COMMENT) print£("\n\t%s is a ARITHMETIC OPERATOR", yytext) ;} a int main(int argc, char **argv) { if(arge > 1) { FILE *file; file-fopen(argv[1],"2"); if(!file) { printf ("could not open %s\n",argv[1]); exit (0); } yyin=file; } yylex(); printf ("\n\n"); return 0; N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING } int yywrap () { return 0; } UT (area.c): #include #include double area_of_circle(double 1); int main(int arge,char *argv[]) { iffarge <2) { printf("usage: %s radius\n" argv[0]); { exit(L); } else { double radi =atoftargv[ I); double area=area_of_circle(radius); ©S6612 / T6612 - COMPILER LABORATORY. printf("Area of circle with radius %f=6f\n" radius,area); return 0; N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING $6612 / 116612 - COMPILER LABORATORY OUTPUT RESULT: Thus the above the program is executed and the required output is obtained. N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. oe No Tea YACC PROGRAM TO RECOGNIZE A VALID Date: ARITHMETIC EXPRESSION AIM: ALGORITHM: PROGRAM CODING: %{ /* validate simple arithmetic expression */ finclude #include #include finclude #define YYSTYPE double Bh token num left ‘+! left '*' Be st: st expr '\n' (printf ("Valid"); } ist ‘\n" \ lerror '\n' {print £ ("INVALID") ;} expr: num jexpr '+! expr lexpr '/' expr ae main () t printf(" ENTER AN EXPRESSION TO VALIDATE"); yyparse (); } yylex() if (isdigit (ch) | ch= { ungete (ch, stdin) ; scanf("%1£", &yylval); return num; N.SENTHIL MURUGAN AP/CSE e-Mail :sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. ee pha (char *s) eetee ests ein oureur: :\Flex Windows\EditPlusPortable>yace -d arithval.y C:\Flex Windows\EditPlusPortable>ce y.tab.c -I C:Flex Windows\EditPlusPortable>./a.out ENTER AN EXPRESSION TO VALIDATES+9 Valid 446 Valid 5 INVALID RESULT: Thus the above the program is executed and the required output is obtained N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex. No: 4b YACC PROGRAM TO RECOGNIZE A VALID VARIABLE Date: AIM: ALGORITHM: PROGRAM CODING: &{ /* ¥ prg to recognize valid variable, which starts with a letter, followed by any number of letters or digits. */ #include #include 8h token let dig sad: let recld '\n' {print£("accepted\n"); return 0;} | let '\n' {printf ("accepted\n"); return 0;) | lerror {yyerror("rejected\n"};return 0;} recld: let recld | dig recid | let | dig 8 yylex() ( char ch; while ( (ch=getchar ( if (isalpha (ch) return let; if(isdigit (ch)) return dig; return ch; } yyerror (char *s ( printf ("$s",s); } N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. main() { printf ("ENTER A variable yyparse (); } Output: CaFlex Windows\EditPlusPortable>yace -d vvar.y CAFlex Windows\EditPlusPortable>ce y.tab.c I CAFlex Windows\EditPlusPortable> /a.out ENTER A variable : a45 accepted CAFlex Windows\EditPlusPortable> /a.out ENTER A variable : Se syntax errorrejected CAFlex Windows\EditPlusPortable> /a.out ENTER A variable : ab accepted RESULT: Thus the above the program is executed and the required output is obtained. N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Boles IMPLEMENTATION OF CALCULATION USING LEX arcatsatii | DEEEE AND YACC | AIM: To write a program to implement calculator using lex and yace. ALGORITHM: 1. Start the program, Perform the calculation using both the lex and yace. 3. In the lex tool, ifthe given expression contains numbers and letters then they are displayed 4, Inthe same way, the digit tool. letters and uminus are identified and displayed using yace 5. The calculation is performed and the result is displayed. 6. Stop the program, PROGRAM CODING: USING LEX TOO! aL include finclude "y.tab.h" int ¢; extern int yylval; a} (a-z] { c = yytext [0]; yyly. cn tat; return (LETTER) ; } [0-3] { c = yytext [0]; yylval = c - '0'; N.SENTHIL MURUGAN AP/CSE com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. return (DIGIT) ; } [*a-z0-9\b] { c = yytext [0]; return (c); } 8% USING YACC TOOL: &( #include int regs[26]; int base; 8} astart list &token DIGIT LETTER Sleft ‘|! left 's! fleft ‘+! Bleft tt 1st tye left UMINUS /*supplies precedence for unary minus */ ae /* beginning of rules section */ list: /*empty */ I list stat '\n' I list error '\n' { yyerrok; } stat: expr { printf ("#d\n",$1); } I LETTER { regs[$1] expr $3; } { expr: (expect) $$ = $2; } I expr '*' expr N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING { $$ } I! expr { $$ } I expr { $$ } I expr { $$ } I! expr { $$ } l expr { $$ ) l expr { $$ } I fl imaS1 1") $05 '/) expr = $1 / $3; " expr = $1 % $3; "+! expr Sas licnieds * expr = $1 - $3; "Gg! expr = $1 & $3; expr = $1 | $3; ' expr %prec UMINUS SB iae2r) } Il LETTER { $$ = regs[$1]; ) I number number: DIGIT N.SENTHIL MURUGAN AP/CSE ©S6612 / T6612 - COMPILER LABORATORY. e- Mai JP COLLEGE OF ENGINEERING $6612 / 116612 - COMPILER LABORATORY SPST RESULT: Thus the above the program is executed and the required output is obtained, N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex. No: 5 Convert the BNF rules into Yacc form and write code to generate Abstract Syntax Tre AIM: ALGORITHM: PROGRAM CODIN LEX af #include"y.tab.h" #include #include int LineNo=1; 8h identifier [a-zA-zZ] [_a-zA-z0-9]* number [0-9]+1 ([0-9]1*\.[0-9]+) Be main\(\) return MAIN; if return IF; else return ELSE; while return WHILE float return TYPE; {identifier} {strepy (yylval.var, yytext) return VAR; (number) {strepy (yylval.var, yytext) return NUM;) \< \> \> N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING {strepy (yylval.var, yytext) ; return RELOP;} (MANSIANA \n LineNot++; return yytext [0]; BB int yywrap() ( return 1; } YAce BL #include #include #include void push (int); ©S6612 / T6612 - COMPILER LABORATORY. void AddQuadruple (char *,char *,char *,char *); struct quad ( char op[5]; char argl(10]; char arg2[10]; char result [10]; QUAD [3017 struct stack t int items[100]; int top; bstky int Index=0,tIndex=0, StNo, Ind, tInd; extern int LineNo; Sh N.SENTHIL MURUGAN AP/CSE e- Mai sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. union { char var[10]; } %token NUM VAR RELOP token MAIN IF ELSE WHILE TYPE &type EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP Bleft '-' "+ Sleft #1 1/! 88 PROGRAM : MAIN BLOCK BLOCK: '{' CODE '}! CODE: BLOCK | STATEMENT CODE | STATEMENT STATEMENT: DESCT '; | ASSIGNMENT ';' | ConpsT | WHILEST DESCT: TYPE VARLIST VARLIST: VAR ',' VARLIST | VAR ASSIGNMENT: VAR '=' EXPR( strcpy (QUAD[ Index] .op, st repy (QUAD [Index] .argl, $3); strcpy (QUAD[Index] .arg2,""); N.SENTHIL MURUGAN AP/CSE sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. strepy (QUAD [Index] result, $1); st repy ($$, QUAD[Index++] . result); } EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);} | EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);} | EXPR '*! EXPR (AddQuadruple("*",$1,$3,$$) i} | BXPR '/* EXPR (AddQuadruple("/", $1, $3,$$)7} ‘-' EXPR {AddQuadruple ("UMIN", $2,"",$$) EXPR (stropy ($$, $2);) | VAR | num CONDST: IFST( Ind=pop () sprintf (QUAD[Ind] .result, "$d", Index) ; Ind=pop () sprintf (QUAD[Ind] .result, "%d", Index) ; I | IFST ELSEST IFST: IF '(' CONDITION ')' { my st repy (QUAD [Index] .argl, $3); strepy (QUAD [Index] .op, st repy (QUAD [Index] .arg2, "FALSE") ; st rcpy (QUAD[Index] .result,"-1"); push (Index) ; Indext+; } BLOCK { st repy (QUAD [Index] .op, "GOTO") ; strcpy (QUAD[Index] .argl,""); N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. st rcpy (QUAD[Index] .arg2,""); st repy (QUAD [Index] .result,"-1"); push (Index) ; Index++; he ELSEST: ELSE( tInd=pop (); Ind=pop () + push (tind); sprintf (QUAD[Ind] .result, "$d", Index) ; } BLOCK ( Ind=pop () sprintf (QUAD[Ind] .result, "$d", Index) ; hi 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, "%a", Index) ; } WHILELOOP: WHILE ' CONDITION ')' { strcpy (QUAD[ Index] .op, st repy (QUAD [Index] .argl, $3); st rcpy (QUAD[Index] .arg2, "FALSE") ; N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. strepy (QUAD [Index] .result, "-1"); push (Index) ; Index++; } BLOCK { strepy (QUAD [Index] .op, "GOTO") ; strepy (QUAD [Index] .argl,""); strepy (QUAD [Index] .arg2,"") ; strepy (QUAD [Index] .result,"-1"); push (Index) ; Index++; b cy extern FILE *yyin; int main(int arge,char *argv[]) ( FILE “fp; int i; if (arge>1) t fp=fopen (argv(1],"r"); if (!£p) r print£("\n File not found"); exit (0); } yyin-fp; } yyparse(); N.SENTHIL MURUGAN AP/CSE e- Mai JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. print £("\n\n\t\t—— \n\t\t Pos Operator Argl Arg2_ Result \n\t\t-- i he for (i=; i #include #include #include #include char* type(char{], int); void main() c char a[10],b[10],mess[20],mess1[20]; int i,1; elrser(); print£( "\n\n int a,b;\n\n int c=atb\n") printf( "\n\n Enter a value for a\n") scanf("#s", a); l=strlen(a); printf(™ \n a is i"); stropy (mess, type (a,1)) 7 print£("%s",mess); printf( "\n\n Enter a value for b\n\n") scanf("&s",b); l=strlen(b); printf(" \n b is :") strepy (messi, type (by 1)); N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. printf ("%s",mess1) ; if(stromp(mess, "int" t printf£("\n\n No Type Error"); } else t printf("\n\n Type Error"); } getch(); } char* type(char x{],int m) t int i; Ogestrcmp (messi, "int") char mes [20]; for (1-0; i #include #include #include struct Listnode t char data[50]; int leader, block, u_goto, c_goto; struct Listnode *next; char label[10],target [10]; }*temp, *cur, *first=-NULL, *last=NULL, *curl; FILE *fpry void createnode (char code[50]) ( temp=(struct Listnode *)malloc (sizeof (struct Listnode) ); strcpy (temp->data, code) ; strepy (temp->label, '\0"); strepy (temp->target, '\0"); temp->leader=0; temp->block=0; temp->u_goto=0; N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. temp->c_goto=0; temp->next=NULL; if (first: { first=temp; ULL) last=temp; ) else { last~>next=temp; last=temp; ) } void printlist () i cur=first; printf ("\nMIR code is \n\n"); while (cur!=NULL) { print£ ("\ncode:%s",cur->data) ; printf ("\nleader:$d\t", cur->leader) ; print ("block:%d\t", cur->block) ; print£ ("u_goto:%d\t", cur->u_goto) ; print£ ("c_goto:%d\t", cur->c_goto) ; printf ("label:%s\t", cur->label) ; printé ("target:%s\n", cur->target); cur=cur->next; } N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. void main() { char codeline[501; char c,dup[50],target [10]; char *substring, *token; int i=0,block,block1; int 4=0; fpr= fopen("input .txt","r"); clrser(); while (( { if(c!="\n') { jet c (fpr) ) !=EOF) codeline[i]=c; itt; else codeline[i]='\0'; createnode (codeline); i=0; } , //create last node codeline[i]="\0'; createnode (codeline); fclose (fpr); uw printlist (); // find out leaders,conditional stmts cur=first; N.SENTHIL MURUGAN AP/CSE e- Mai sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. cur->leader=1; while (cur!=NULL) { substring=strstr ((cur->data) ,"if"); if ((strstr ((cur->data), "goto")) !=NULL) { cur->u_goto=1; (cur->next) ->leade: } ) else { cur->c_goto=1; (cur->next)->leader=1; , substring-strstr ((cur->data) ,":")i if (substring! =NULL) ( cur->leader=1; ) substring=strstr ((cur->data) ,"call"); if (substring!=NULL) { cur->leader=1; ) if (strstr (cur->data, "return") !=NULL) { cur->leader=1; (cur->next) ->leader=1; , N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. cur=cur->next; ) //to find labels and targets cur-first; while (cur! ( 4£((cur->u_goto: ( subst ring-strstr (cur->data, ULL ULL) 1) 11 (cur->e_got: eT if (substring! { toke! trstr (substring, "L" ); if (token!=NULL) strepy (cur->target, token) } else { subst ring-strstr(cur->data, "L"); if (substring! =NULL st repy (cur->target, substring) ; } ) if (strstr (cur—>data,":" { strepy (dup, cur->data) ; token=strtok (dup, ":"); // printé ("\ntokel ULL) strepy (cur->label, token) ; ) 3", token); if (token cur=cur->next; N.SENTHIL MURUGAN AP/CSE JP COLLEGE OF ENGINEERING MW printlist (); //to identify blocks cur=first; while (cu { cur=cur->next; NULL) if ((cur->leader) ( itt cur->block=3; } else cur->block=3; } // printlist (0; // print basic blocks printf("\n\n......Basic Blocks cur=first; 5-0; print£("\nBlock $d:",4)¢ while (cur!=NULL) { if ((cur->block) ce print£("%s",cur->data); printf ("\n\t"); cur=cur->next; N.SENTHIL MURUGAN AP/CSE ©S6612 / T6612 - COMPILER LABORATORY. s\n"); e- Mai JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. else { Ht; printf ("\nBlock %d:", 3); } } //to output the control flow from each block poiineen (Ae cue Control Flow....... \a\n"); cur-first; i-0; while (cur!=NULL) i if ({cur->block) ! i block=cur->block; cur->next) ->block) if (cur->u_goto { strepy (target, cur—>target) ; curi=first; while (curl !=NULL, { if (stomp (curl->label, target { 0) blockl=curl->block; Print £("\t\tBlock%d- >Blockd\n", block, block1) ; ) curl=curl->next; } N.SENTHIL MURUGAN AP/CSE e- Mai sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. else if (cur->c_got: { strepy (target, cur->target) ; 1) curl=first; while (curl !=NULL) { if (strcmp (curl->label, target ( 0) block1 ur1->block; printé ("\t\tBlock$d---TRUE--->Block$d---FALSE-— ->Block#d\n", block, block1, (block+1)) ) curl=curl->next; } } else if(strstr(cur->data, "return" { print£("\t\tBlock’d- >Block%d\n", block, (block+1)); } else printf ("\t\tBlocktd-- ->NULL\n", block) ; cur=cur->next; } cur=last; block= cur->block; printé("\t\tBlock%d-- -->NULL", block) ; getch (); N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING INPUT (input.txt) oer Poteet ara SSAA orn) SAA brtaet} sR N.SENTHIL MURUGAN AP/CSE $6612 / 116612 - COMPILER LABORATORY e- Mail sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. IMPLEMENTATION OF STORAGE ALLOCATION STRATEGY AIM: ALGORITHM: PROGRAM CODIN #include"stdio.h" #include"conio.h" #include"stdlib.h" define TRUE 1 define FALSE 0 typedef struct Heap { int data; struct Heap ‘next; }node; node *create(); void main() { /*local declarations*/ int choice, val; char ans; node *head; void display (node *); node *search (node *, int); node *insert (node *); void dele(node **); head=NULL; do { elrser(); printf£("\n Program to perform various operations on heap using dynamic memory management”); printf (*\nl.Create”): printf ("\n2.Display” printf ("\n3.Insert an element in a list”); printf (“\n4.Delete an element from list”); printf ("\n5.Quit”); printf ("\n Enter Your Choice (1-5)"); scanf (“d, &choice”); switch (choice: { N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. case 1:head=create(); break; case 2:display (head); break; case 3:head=insert (head) ; break; case 4idele(&head); break; case 5:exit (0); default :clrser(); printf (“Invalid Choice,Try again”); getch (); i }while (choice } /*The create function creates a list of allocated node *Input :None *Output :Retyurns a pointer to head of list *Parameter Passing Methopd:Node e/ node *create() { node *temp, *new,* head; int val, flag; char ans="y’ node *get_node(); temp=NULL; flag=TRUE; /*flag to indicate whether a new node is created for the first time or not*/ do { printf("\n Enter the Element”); scanf ("$d”, &val) ; /*allocate new node*/ new =get_node(); printf("\n Memory is not allocated”); new-> data=val; if (flag--TRUE)/* Executed only for the first time*/ { head: new; ead; /*head is the first node in the heap*/ N.SENTHIL MURUGAN AP/CSE ¢- Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. } else { /*temp keeps track of the most recently created node*/ temp->next=new; temp=new; } print£(\nDo you want to enter more elements? (y/n)” ans=getch ()7 }while (ans ye printf("\nThe list is created”); getch); elrser(); return head; I node *get_node() { node *temp; temp=(node*) malloc (sizeof (node) ); //asing the mem. Allocation function temp->next =NUL! return temp; I void display (node*head) t node *temp; temp=head; if (temp= =NULL) ( printf£("\n The list is empty\n”); getch(); elrser(); return; } while (temp! ( printf (“td->”,temp-> data); temp=temp->next; } print (“NULL”); getch(); elrser(); } node *search(node *head, int key) NULL) N.SENTHIL MURUGAN AP/CSE sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. t node*temp; int found; temp=head; if (temp: t printf (“The linked list is empty\n”); getch(); elrser(); return NULL; } ull) found=FALS While (temp { if (temp->data != key) temp = temp->next; else found = True; } NULL && foun: if (found ( print£("\n The Elements is present in the list”\n); getch(); return tem } TRUE) else printf("\n The Element is not present in the list\n"); getch (); return NULL; } node *insert (node *head) t int choice; node *insert_head (node*); void insert_after (node*); void insert_last (node*) ; printf("\n"1.Insert a node as a head node”); printf("\n"l.Insert a node as a last node”); printf("\n"l.Insert a node as at the intermediate position in the list ”); printf("\n”l.Enter your choice for insertion of node ”); scanf (“#d”, échoice) 7 switch (choice) ( case 1:head = insert_head (head); N.SENTHIL MURUGAN AP/CSE ¢- Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING break; case2:insert_last (head) ; break; case2:insert_after (head); break; } return head; } /*Insertion of node at first position*/ node *insert_head (node*head) ( node *New, *temp; New = get_node(); printf ("\n Enter the element which you scanf (“%d”, &New->data) ; if(head == NULL) head = New; else i temp=head; New->next = temp; head= New; } return hea } /*Insertion of node at last position*/ void insert_last (node *head) ( node *New, *temp; New = get_node (); printf ("\n Enter the element which you scanf (“#d”, 6New->data) ; if(head == NULL) t head = New; } else i temp-head; while (temp->next temp=temp->next; temp->next New->next=NULL; N.SENTHIL MURUGAN AP/CSE ©S6612 / T6612 - COMPILER LABORATORY. want to insert ”); want to insert “); e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. } } /*Insertion of node at intermediate position*/ void insert_after(node *head) { int key; node *New, *temp; New = get_node(); print£("Enter the element after which you want to insert De scanf (“#d”, 6key) ; temp=head; do { if (temp->data { printf ("Enter element which you want to insert ”); scanf (“%d", éNew->data) ; New->next=temp->next; temp->next=New; return; ey) node *get_prev(node *head, int val) { node*temp. *prev; int flag; temp = hea if (temp == NULL) return NULL; flag = FALSE; prev = NULL; while (temp ( if (temp->data! ( prev = temp; ULL && !flag) al) temp = temp->next; t else flag = TRUE; } if(flag) /*if Flag is true*/ return prev; N.SENTHIL MURUGAN AP/CSE ¢- Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. else return NULL; } void dele(node **head) { int key; node *New, *temp; temp=*head; if (temp: ( printf ("\n The list is empty\n ”); getch (); elrser(); return; } elrser(); print£("\nENTER the Element you want to delete scanf ("td".&key); temp= search (*head, key) ; if (temp (ULL) ( prev = get_prev(*head, key) ; if (prev != NULL) ( prev ->next = temp-> next; free (temp); } else ( *head = temp->next; free(temp); // using the mem. Dellocation function } printf (“\n”The Element is deleted\n”); getch(); elrscr()7 } NULL) ouTPUT: Program to perform various operations on heap using Dynamic memory management. 1. Create 2. Display 3. Insert an element in a list 4, Delete an element from list 5. Quit N.SENTHIL MURUGAN AP/CSE e- Mai 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Enter your choice(1-5) 1 Enter the element: 10 Do you want to enter more elements? (y/n)y Enter the element:20 Do you want to enter more elements?(y/n)y Enter the element:30 Do you want to enter more elements?(y/n)n The List is created Program to perform various operations on Heap using Dynamic memory management. 1. Create 2. Display 3. Insert an element in a list 4, Delete an element from list 5. Quit Enter your choice(1-5) 4 Enter the element you want to delete: 20 The element is present in the list The element is deleted Program to perform various operations on Heap using Dynamic memory management. 1. Create 2. Display 3. Insert an element in a list 4, Delete an element from list 5. Quit Enter your choice(1-5) 2 10-> 30-> NULL RESULT: Thus the above the program is executed and the required output is obtained N.SENTHIL MURUGAN AP/CSE sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex. No: 9 CONSTRUCTION OF DAG AIM: ALGORITHM: PROGRAM. DI #include #define N 8 typedef struct node node; struct node { int count; node *next; ye node graph(N]; void buildGraph( int a[](2], int edges ) { int i; for( i-0; icount = afil[ll; ptr->next = graph{ afi][0] ].next; graph[ a(i][0] ].next = ptr; graph[ a[i][1] ].count++; void printGraph() { ancien N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. node *ptr; for( i=0; inext ) print£( "$a", ptr->count ); printf( "\n" ); t } void main() { int a[8](2],i,37 clrscr(); print£("\n\nEnter the edges b/w nodes \n"); for (i=0;1<8; i++) { for (3=0; 3<2; j++) { scanf ("d", &a[i] (41); t I buildGraph( a, 8 ); print£("\nThe DAG for (atb)*c+((atb)+e) : \n\n"); printGraph (); getch(); N.SENTHIL MURUGAN AP/CSE e-Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING OUTPUT $6612 / 116612 - COMPILER LABORATORY Poe ETC Se ekcee Serene Posse ay Pevnvesre ety cess) eeeriresee ery pete oy r 6 N.SENTHIL MURUGAN AP/CSE ft Fl FI EB e- Mail : sendhil28@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex. No: 10 IMPLEMENTATION OF BACK END OF COMPILER Date: AIM: To write a C program to implement the back end of the compiler. ALGORITHM: 1) Start the program. 2) Get the three variables from statements and stored in the text file k.txt 3) Compile the program and give the path of the source file. 4) Execute the program. 5) Target code for the given statement was produced. 6) Stop the program. PROGRAM CODING: #include #include #include #include void main() { int 1-2, j-0,k=2, kL char ip[101,kk(101; FILE *£p; printf("\nEnter the filename of the intermediate code"); scanf("s", ek) ; fp=fopen (kk, "r"); if (£p==NULL) { print£("\nError in Opening the file"); geteh(); } while (!£eof (fp) ) { fscanf (fp, "$s\n", ip); printé("\t\t%s\n", ip); } rewind (£p); printé ("\n- printé (" printf ("\n- tatement \t target code\n"); N.SENTHIL MURUGAN AP/CSE e-Mail : sendi 8@gmail.com JP COLLEGE OF ENGINEERING $6612 / 116612 - COMPILER LABORATORY Red\n\t", iplitk], i); nt €("\E\ESUB "); if (slower (ip[il)) print£("%c,R&d\n\n", ip[itk1], 5) 7 print iplil, iplit printé("\n getch(); ee selteeey OUTPUT ee ee eee one Esra) RESULT: Thus the above the program is executed and the required output is obtained N.SENTHIL MURUGAN AP/CSE sendhil28@ gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Ex. No: 11 IMPLEMENTATION OF CODE OPTIMIZATION TECHNIQUES To write a program for implementation of Code Optimization Technique in C. PROGRAM: #include #include #include #include #include struct ConstFold ( char new_str[10]; char str[10]; fopt_Data[20]; void ReadInput (char Buffer[],FILE *Out_file); int Gen_token(char str{],char Tokens[][10]); int New_Index=0; int main() t FILE *In_file, *Out_file; char Buffer(100],ch; int In_file Out_file while (1) { ch = fgetc(In_file); i=0; while (1) t if(ch break; Buffer[i++]=ch; ch = fgete(In_file); fopen("code.txt","r") 7 fopen ("output txt", "w"); ou) if(ch == EOF) break; }//End while if(ch break; N.SENTHIL MURUGAN AP/CSE 8@gmail.com JP COLLEGE OF ENGINEERING ©S6612 / T6612 - COMPILER LABORATORY. Buffer[il='\0'; ReadInput (Buffer, Out_file);//writing to the output file }//End while return 0; }//End main void ReadInput (char Buffer[],FILE *Out_file’ t char temp[100], Token{10] [10]; int n,i, 3, flag=0; strepy (temp, Buffer) ; n= Gen_token (temp, Token) ; for (i=0; isn; itt) t if(!stromp (Token[i],"=")) t if (isdigit (Token[i+1] [0]) | |Token[it1] [0 t /*L£ yes then saving that number and its variable In the Opt_Data array*/ flag=1; strepy (opt_Data [New_Index] .new_str, Token [i-1]); strcpy (opt_Data[New_Index++] .str, Token [i+1]); t//End if }//End if }//End for if(!flag) t for (i=0; i

Você também pode gostar