Lab Report - 5
Lab Report - 5
Laboratory-5
Question
Generate intermediate code for if, if-else & while loop in C.
int label_num=0;
int else_label_num = 0;
bool else_flag=0;
int bool_ir_index=100;
int bool_ir_start = 100;
int bool_ir_if_top=-1;
int bool_ir_if_stack[10];
int loop_stack_top=-1;
int loop_stack[10];
char bool_code[25][50];
struct three_address_code {
char instr[4][20];
} *tac_temp,tac[50];
int tac_len, tac_temp_len, tac_temp_tot = 1;
struct tac_package {
int tac_len;
struct three_address_code *tac;
};
void addToThreeAddressArthmtc(char* op, char* arg1, char* arg2, char*
result)
{
if(tac_temp_len >= tac_temp_tot-1)
{
tac_temp = reallocarray(tac_temp,sizeof(struct three_address_code),
tac_temp_tot *= 2);
}
strcpy(tac_temp[tac_temp_len].instr[0],result);
strcpy(tac_temp[tac_temp_len].instr[1],arg1);
strcpy(tac_temp[tac_temp_len].instr[2],arg2);
strcpy(tac_temp[tac_temp_len].instr[3],op);
tac_temp_len++;
}
void addToThreeAddressBrnch(char *res)
{
char *arg1 = "",*arg2 = "",*op = "",*result = "";
char *init = strtok(res," ");
if(res[0] == 'i')
{
arg1 = strtok(NULL," ");
op = strtok(NULL, " ");
arg2 = strtok(NULL, " ");
strtok(NULL, " ");
result = strtok(NULL, " ");
}
else if(res[0] == 'g')
{
op = init;
result = strtok(NULL, " ");
}
else result = strtok(init,":");
strcpy(tac[tac_len].instr[0],result);
strcpy(tac[tac_len].instr[1],arg1);
strcpy(tac[tac_len].instr[2],arg2);
strcpy(tac[tac_len].instr[3],op);
tac_len++;
}
void generate_code(char* op, char* arg1, char* arg2, char* result)
{
//printf("%s = %s %s %s\n", result, arg1, op, arg2);
addToThreeAddressArthmtc(op,arg1,arg2,result);
CSPC62 – Compiler Design – Laboratory5
Prajwal Sundar - 106121092
}
void backpatch(int *list,int next_ir) {
char addr[10];
sprintf(addr,"L%d ",next_ir-100);
int i=0;
while(list[i]!=0) {
char label[25];
strcat(bool_code[list[i]-100],addr);
if(bool_code[next_ir-100][0] != 'L') {
sprintf(label,"L%d: ",next_ir-100);
strcat(label,bool_code[next_ir-100]);
strcpy(bool_code[next_ir-100],label);
}
i++;
}
}
%}
%token INCLUDE INCL_FILE MACRO
%token TYPE IF ELSE VARIABLE CONSTANT
%token WHILE MAIN RETURN
%token LOGIC_OPRTR OPRTR_ASSGN UNARY OR AND
%token ERROR
%left '+' '-'
%left '*' '/'
%left LOGIC_OPRTR
%right '=' UMINUS
%%
program: program_body
|
;
program_body:
include program_body
| main
;
include: INCLUDE INCL_FILE
main: TYPE MAIN '(' ')' '{' body '}'
body:
body line
|
;
line: branch
{
if(else_flag)
{
char label[5] = {0}, buff[5] = {0};
sprintf(buff,"%d",else_label_num);
label[0] = 'G';
strcat(label,buff);
strcpy(tac[tac_len++].instr[0],label);
else_flag=0;
else_label_num++;
}
}
| assignment ';'
%%
#include "myLexHeader.h"
int main(void)
{
for(int i=0;i<tac_len;i++)
{
CSPC62 – Compiler Design – Laboratory5
Prajwal Sundar - 106121092
Sample.c:
int main(){
int x = 4, count = 1;
if(x < 5) count = count*2;
else count = count + 2;
return 0;
}
Output:
Result:
Intermediate code for conditional and looping constructs was
generated successfully.