/* 
   Copyright 1994-2003 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
   02111-1307, USA.  

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
/*
 * istmt.c
 *
 * channge the statement list to icode
 */
#include        <stdio.h>
#include				"utype.h"
#include        "lists.h"
#include        "expr.h"
#include        "c.h"
#include				"iexpr.h"
#include 				"iopt.h"
#include 				"diag.h"

extern int global_flag;
extern TABLE gsyms;
extern long nextlabel;
extern TYP              stdfunc;
extern SYM *currentfunc;
extern int prm_cplusplus;
extern int prm_locsub, prm_globsub, prm_copyprop, prm_foldconst;
extern int prm_optcode, prm_optdead, prm_optlive ;
extern short addrsize,intsize;
extern BLOCKLIST *blockhead;
extern int blocknum;
extern QUAD *intermed_head;
extern TABLE tempsyms;
extern int firstlabel;
#ifdef DUMP_GCSE_INFO
extern FILE *icdFile ;
#endif
/*

 * virtual registers
 */
IMODE rlink = { i_rlink, 0, 0 };
IMODE rsp = { i_rsp, 0, 0 };
IMODE rstruct = { i_rstruct, 0, 0 };
IMODE rstructstar = { i_rstructstar, 0, 0 };
IMODE rret = { i_rret, 0, 0 };
int tempnum;
static int 	diddef;     /* True if did default */
/*
 * current label values 
 */
static int     breaklab;
static int     contlab;
int     retlab;
static int deflab;
/*
 * temporaries used in switch-case optimizations
 */
static long gswitchbottom, gswitchcount;
static long gswitchtop;
static int diddef ;

void genstmtini(void)
{
	rsp.size = rlink.size = addrsize;
}
IMODE		*tempreg(int size, int mode)
/*
 * create a temporary register
 */
{
	SYM *sp;
	IMODE *ap;
	char buf[10];
	ap = xalloc(sizeof(IMODE));
	sp = xalloc(sizeof(SYM));
	sprintf(buf,"$$t%d",tempnum);
	sp->name = litlate(buf);
	sp->storage_class = sc_temp;
	sp->value.i = tempnum++;
	if (prm_locsub)
		insert(sp,&tempsyms);
	ap->offset = makenode(en_tempref,sp,0);
	ap->size = size;
   if (mode) {
		ap->mode = i_immed;
      sp->imaddress = ap ;
   } else {
		ap->mode = i_direct;
      sp->imvalue = ap ;
   }
	return ap;
}
IMODE    *make_direct(int i)
/*
 *      make a direct reference to an immediate value.
 */
{       return make_offset(makenode(en_icon,(char *)i,0));
}

IMODE    *make_strlab(char *s)
/*
 *      generate a direct reference to a string label.
 */
{       IMODE    *ap;
        ap = xalloc(sizeof(IMODE));
				ap->size = addrsize;
        ap->mode = i_direct;
        ap->offset = makenode(en_nacon,s,0);
        return ap;
}

void genwhile(SNODE *stmt)
/*
 *      generate code to evaluate a while statement.
 */
{       int     lab1, lab2, lab3;
        lab1 = contlab;         /* save old continue label */
        contlab = nextlabel++;  /* new continue label */
        if( stmt->s1 != 0 )      /* has block */
                {
        				lab2 = breaklab;        /* save old break label */
                breaklab = nextlabel++;
								gen_igoto(contlab);
								lab3 = nextlabel++;
								gen_label(lab3);
                genstmt(stmt->s1);
								gen_label(contlab);
								if (stmt->lst)
		 							gen_line(stmt->lst);
                truejp(stmt->exp,lab3);
                gen_label(breaklab);
                breaklab = lab2;        /* restore old break label */
                }
        else					        /* no loop code */
                {
								if (stmt->lst)
		 							gen_line(stmt->lst);
        				gen_label(contlab);
                truejp(stmt->exp,contlab);
                }
        contlab = lab1;         /* restore old continue label */
}

void gen_for(SNODE *stmt)
/*
 *      generate code to evaluate a for loop
 */
{       int     old_break, old_cont, exit_label, loop_label, start_label;
        old_break = breaklab;
        old_cont = contlab;
        loop_label = nextlabel++;
        contlab = nextlabel++;
				start_label = nextlabel++;
        exit_label = nextlabel++;
        if( stmt->label != 0 )
                gen_expr(0,stmt->label,F_NOVALUE
                        ,natural_size(stmt->label));
				
				gen_igoto(start_label);
        gen_label(loop_label);
        if( stmt->s1 != 0 ) {
								breaklab = exit_label;
                genstmt(stmt->s1);
				}
				gen_label(contlab);
        if( stmt->s2 != 0 )
                gen_expr(0,stmt->s2,F_NOVALUE,natural_size(stmt->s2));
				gen_label(start_label);
				if (stmt->lst)
		 			gen_line(stmt->lst);
        if( stmt->exp != 0 )
                truejp(stmt->exp,loop_label);
				else
						gen_igoto(loop_label);
				gen_label(exit_label);
 				breaklab = old_break;
				contlab = old_cont;
}

void genif(SNODE *stmt)
/*
 *      generate code to evaluate an if statement.
 */
{       int     lab1, lab2;
        lab1 = nextlabel++;     /* else label */
        lab2 = nextlabel++;     /* exit label */
        falsejp(stmt->exp,lab1);
        genstmt(stmt->s1);
        if( stmt->s2 != 0 )             /* else part exists */
                {
								gen_igoto(lab2);
                gen_label(lab1);
                genstmt(stmt->s2);
                gen_label(lab2);
                }
        else                            /* no else code */
                gen_label(lab1);
}

void gendo(SNODE *stmt)
/*
 *      generate code for a do - while loop.
 */
{       int     oldcont, oldbreak;
        oldcont = contlab;
        oldbreak = breaklab;
        contlab = nextlabel++;
        gen_label(contlab);
        if( stmt->s1 != 0 && stmt->s1->next != 0 )
                {
                breaklab = nextlabel++;
                genstmt(stmt->s1);      /* generate body */
                truejp(stmt->exp,contlab);
                gen_label(breaklab);
                }
        else
                {
                genstmt(stmt->s1);
                truejp(stmt->exp,contlab);
                }
        breaklab = oldbreak;
        contlab = oldcont;
}
void gen_genword(SNODE *stmt)
/*
 * generate data in the code seg
 */
{
		gen_icode(i_genword,0,make_immed((int)stmt->exp),0);
}
IMODE *set_symbol(char *name, int isproc)
/*
 *      generate a call to a library routine.
 */
{       SYM     *sp;
        IMODE *result;
        sp = gsearch(name);
        if( sp == 0 )
                {
                ++global_flag;
                sp = xalloc(sizeof(SYM));
                sp->tp = &stdfunc;
                sp->name = name;
                sp->storage_class = sc_external;
								sp->extflag = TRUE;
                insert(sp,&gsyms);
                --global_flag;
                }
				result = make_strlab(name);
				return result;					
}
IMODE *call_library(char *lib_name,int size)
/*
 *      generate a call to a library routine.
 */
{       
        IMODE *result;
				result = set_symbol(lib_name,1);
        gen_icode(i_gosub,0,result,0);
        if( size != 0 ) {
          gen_icode(i_parmadj,0,make_immed(size),0);
				}
				result = tempreg(intsize,0);
        gen_icode(i_assn,result,&rret,0);
				return result;					
}

int analyzeswitch(SNODE *stmt)
{
	gswitchbottom = 0x7fffffff;
	gswitchtop = 0x80000000;
	gswitchcount = 0;
	stmt = stmt->s1;
	while (stmt) {
		if (!stmt->s2) {
			gswitchcount++;
			if ((long)stmt->label < gswitchbottom)
				gswitchbottom = (int)stmt->label;
			if ((long)stmt->label > gswitchtop)
				gswitchtop = (int)stmt->label;
		}
		stmt = stmt->next;
	}
	gswitchtop++;
	if (gswitchcount == 0)
		return(0);
	if (gswitchcount < 5)
		return 3;
	if (gswitchcount*10/(gswitchtop-gswitchbottom) >= 8)
		return(1);
	return(2);
}
void bingen(int lower, int avg, int higher,IMODE *ap1, int deflab, long * switchids,int * switchlabels,int *switchbinlabels)
/*
 * generate the binary tree of if statements
 */
{
	IMODE *ap2 = make_immed(switchids[avg]);
	long labnum = switchlabels[avg];
	if (switchbinlabels[avg] != -1)
		gen_label(switchbinlabels[avg]);
	gen_icgoto(i_je,labnum,ap1,ap2);
	if (avg == lower) {
		gen_igoto(deflab);
	}
	else {
		int avg1 = (lower + avg)/2;
		int avg2 = (higher + avg+1)/2;
		if (avg+1 < higher) 
			labnum = switchbinlabels[avg2]=nextlabel++;
		else
			labnum = deflab;
      if (ap1->size < 0)
			gen_icgoto(i_jg,labnum,0,0);
		else
			gen_icgoto(i_ja,labnum,0,0);
		bingen(lower,avg1,avg,ap1,deflab,switchids,switchlabels,switchbinlabels);
		if (avg+1 < higher)
			bingen(avg+1,avg2,higher,ap1,deflab,switchids,switchlabels,switchbinlabels);
	}
}
void genbinaryswitch(SNODE *stmt, int deflab)
/*
 * setup for binary switch gen
 */
{
	int curlab, i=0,j;
   IMODE *ap1;
  long switchbottom=gswitchbottom, switchcount=gswitchcount;
  long switchtop=gswitchtop;
  int *switchlabels=0;
  long *switchids=0;
  int *switchbinlabels=0;
	curlab = nextlabel++;
   ap1 = gen_expr(0,stmt->exp,0,4);
	global_flag++;
		switchlabels = xalloc((switchcount) * sizeof(int));
		switchbinlabels = xalloc((switchcount) * sizeof(int));
		switchids = xalloc((switchcount) * sizeof(long));
	global_flag--;
	stmt = stmt->s1;
	while (stmt) {
                if( stmt->s2 )          /* default case ? */
                        {
                        stmt->label = (SNODE *) deflab;
												diddef = TRUE;
                        }
                else
                        {
												switchlabels[i] = curlab;
												switchbinlabels[i] = -1;
												switchids[i++] = (int)stmt->label;
												stmt->label = (SNODE *)curlab;
                        }
                if( stmt->s1 != 0)
                        curlab = nextlabel++;
                stmt = stmt->next;
                }
	for (i=0; i < switchcount; i++)
		for (j=i+1; j < switchcount; j++)
			if (switchids[j] < switchids[i]) {
				int temp = switchids[i];
				switchids[i] = switchids[j];
				switchids[j] = temp;
				temp = switchlabels[i];
				switchlabels[i] = switchlabels[j];
				switchlabels[j] = temp;
			}
	bingen(0,(switchcount)/2,switchcount,ap1,deflab,switchids,switchlabels,switchbinlabels);
}
void gencompactswitch(SNODE *stmt, int deflab)
{       int             tablab,curlab,i, size;
        IMODE    *ap,*ap2;
  long switchbottom=gswitchbottom, switchcount=gswitchcount;
  long switchtop=gswitchtop;
  int *switchlabels=0;
				tablab = nextlabel++;
        curlab = nextlabel++;
        ap = gen_expr(0,stmt->exp,F_VOL,4);
        gen_icode2(i_coswitch,ap,make_immed(switchbottom),
						make_immed(switchtop-switchbottom),deflab);
//            align(4);
				gen_label(tablab);
		switchlabels = xalloc((switchtop-switchbottom) * sizeof(int));
	for (i=switchbottom; i < switchtop; i++) {
		switchlabels[i-switchbottom] = deflab;
	}
	stmt = stmt->s1;
	while (stmt) {
                if( stmt->s2 )          /* default case ? */
                        {
                        stmt->label = (SNODE *)deflab;
												diddef = TRUE;
                        }
                else
                        {
												switchlabels[(int)stmt->label-switchbottom] = curlab;
												stmt->label = (SNODE *)curlab;
                        }
                if(stmt->next != 0 )
                        curlab = nextlabel++;
                stmt = stmt->next;
                }
	for (i=0; i < switchtop-switchbottom; i++)
		gen_idc(switchlabels[i]);
}

void gensimpleswitch(SNODE *stmt, int deflab)
{
	int curlab, i=0,j;
   IMODE *ap1;
  long switchbottom=gswitchbottom, switchcount=gswitchcount;
  long switchtop=gswitchtop;
  int *switchlabels=0;
  long *switchids=0;
  int *switchbinlabels=0;
	curlab = nextlabel++;
  ap1 = gen_expr(0,stmt->exp,0,4);
	global_flag++;
		switchlabels = xalloc((switchcount) * sizeof(int));
		switchbinlabels = xalloc((switchcount) * sizeof(int));
		switchids = xalloc((switchcount) * sizeof(long));
	global_flag--;
	stmt = stmt->s1;
	while (stmt) {
                if( stmt->s2 )          /* default case ? */
                        {
                        stmt->label = (SNODE *) deflab;
												diddef = TRUE;
                        }
                else
                        {
												switchlabels[i] = curlab;
												switchbinlabels[i] = -1;
												switchids[i++] = (int)stmt->label;
												stmt->label = (SNODE *)curlab;
                        }
                if( stmt->next != 0 )
                        curlab = nextlabel++;
                stmt = stmt->next;
                }
	for (i=0; i < switchcount; i++)
		for (j=i+1; j < switchcount; j++)
			if (switchids[j] < switchids[i]) {
				int temp = switchids[i];
				switchids[i] = switchids[j];
				switchids[j] = temp;
				temp = switchlabels[i];
				switchlabels[i] = switchlabels[j];
				switchlabels[j] = temp;
			}
//    align(4);
	for (i=0; i < switchcount; i++) {
      gen_data(switchids[i]) ;
      gen_idc(switchlabels[i]) ;
	}
   gen_igoto(deflab) ;
}
void gencase(SNODE *stmt)
/*
 *      generate all cases for a switch statement.
 */
{       while( stmt != 0 )
                {
                gen_label((int)stmt->label);
                if( stmt->s1 != 0 )
                        {
                        genstmt(stmt->s1);
                        }
                stmt = stmt->next;
                }
}

void genxswitch(SNODE *stmt)
/*
 *      analyze and generate best switch statement.
 */
{       int     oldbreak;
	int olddiddef = diddef;
	int deflab = nextlabel++;
        oldbreak = breaklab;
        breaklab = nextlabel++;
				diddef = FALSE;
				switch (analyzeswitch(stmt)) {
					case 3:
						gensimpleswitch(stmt,deflab);
						break;
  				case 2:
						genbinaryswitch(stmt,deflab);
						break;
					case 1:
						gencompactswitch(stmt,deflab);
						break;
					case 0:
						if (stmt->s1)
							stmt->s1->label = (SNODE *) nextlabel++;
						break;
				}
        gencase(stmt->s1);
				if (!diddef)
					gen_label(deflab);
        gen_label(breaklab);
        breaklab = oldbreak;
	diddef = olddiddef;
}

void genreturn(SNODE *stmt,int flag)
/*
 *      generate a return statement.
 */
{       IMODE    *ap,*ap1;
				int size;
				/* returns a value? */
        if( stmt != 0 && stmt->exp != 0 )
        {
                        if (currentfunc->tp->btp && isstructured(currentfunc->tp->btp)) {
									size = currentfunc->tp->btp->size;
  	              ap = gen_expr(0,stmt->exp,F_VOL,4);
									gen_icode(i_assnblock,&rstructstar,ap,(IMODE *)size);
									gen_icode(i_assn,&rret,&rstruct,0);
								}
								else {
									size = natural_size(stmt->exp);
  	              ap = gen_expr(0,stmt->exp,0,size);
									gen_icode(i_assn,&rret,ap,0);
								}
        }
				/* create the return or a branch to the return
				 * return is put at end of function...
				 */
				if (flag) {
        	if( retlab != -1 )
                gen_label(retlab);
					if (currentfunc->intflag)
           	gen_icode(i_rett,0,0,0);
					else
           	gen_icode(i_ret,0,0,0);
        }
        else {
					if (retlab == -1)
						retlab = nextlabel++;
					gen_igoto(retlab);
				}
}

void genstmt(SNODE *stmt)
/*
 *      genstmt will generate a statement and follow the next pointer
 *      until the block is generated.
 */
{
		   while( stmt != 0 )
                {
                switch( stmt->stype )
                        {
												case st_block:
																genstmt(stmt->exp);
																break;
                        case st_label:
                                gen_label((int)stmt->label);
                                break;
                        case st_goto:
																gen_igoto((int)stmt->label);
                                break;
                        case st_expr:
                                gen_expr(0,stmt->exp,F_NOVALUE,
                                        natural_size(stmt->exp));
                                break;
                        case st_return:
                                genreturn(stmt,0);
                                break;
                        case st_if:
                                genif(stmt);
                                break;
                        case st_while:
                                genwhile(stmt);
                                break;
                        case st_do:
                                gendo(stmt);
                                break;
                        case st_for:
                                gen_for(stmt);
                                break;
												case st_line:
																gen_line(stmt);
																break;
                        case st_continue:
																gen_igoto(contlab);
                                break;
                        case st_break:
																gen_igoto(breaklab);
                                break;
                        case st_switch:
                                genxswitch(stmt);
                                break;
												case st__genword:
																gen_genword(stmt);
																break;
												case st_passthrough:
																gen_asm(stmt);
																break;
                        default:
                                DIAG("unknown statement.");
                                break;
                        }
                stmt = stmt->next;
                }
}
SYM *gen_mp_virtual_thunk(SYM *vsp)
{
#ifdef XXXXX
	LIST *v = mpthunklist;
	SYM *sp;
	AMODE *ap1,*ap2 ;
	char buf[100];
	while (v) {
		sp = (SYM *)v->data;
		if (sp->value.i == vsp->value.classdata.vtabindex)
			return sp;
		v = v->link;
	}
	global_flag ++;
	sp = xalloc(sizeof(SYM));
	sp->value.i = vsp->value.classdata.vtabindex;
	sprintf(buf,"@$mpt$%d",sp->value.i);
	sp->name = litlate(buf) ;
	sp->storage_class = sc_static;
  sp->staticlabel=FALSE;
	v = xalloc(sizeof(LIST));
	v->data = sp;
	v->link = mpthunklist;
	mpthunklist = v;
	global_flag--;
   cseg();
   gen_codelab(sp) ;
//   gen_virtual(sp) ;
	ap1 = makedreg(ESP) ;
	ap1->mode = am_indisp ;
   ap1->offset = makeintnode(en_icon,4) ;
	gen_codes(op_mov,4,makedreg(EAX),ap1) ;
	ap1->preg = 0 ;
   if (sp->value.classdata.vtaboffs)
      ap1->offset = makeintnode(en_icon,sp->value.classdata.vtaboffs) ;
   else
      ap1->offset = makeintnode(en_icon,0) ;
	gen_codes(op_mov,4,makedreg(EAX),ap1) ;
   ap1->offset = makeintnode(en_icon,sp->value.i) ;
	gen_codes(op_jmp,4,ap1,0) ;
	flush_peep() ;
//   gen_endvirtual(sp) ;
	return sp;
 #endif
    return 0 ;
}
void genfunc(SNODE *stmt)
/*
 *      generate a function body and dump the icode
 */
{       retlab = contlab = breaklab = -1;
		intermed_head = 0;
      tempnum = 0;
		blocknum = 0;
		blockhead = 0;
		addblock(-1);
      memset(&tempsyms,0,sizeof(tempsyms)) ;
//      firstlabel = nextlabel;
#ifdef CPLUSPLUS
		if (prm_cplusplus)
#endif
				if (stmt->stype == st_line) {
					gen_line(stmt);
					stmt = stmt->next;
				}
				/* We do constant folding while we still have the enode list */
            if (prm_foldconst)
               constscan(stmt);
/*          switchbottom = switchtop = 0;
*/

				/* Generate the icode */
				/* LCSE is done while code is generated */
        genstmt(stmt);
        genreturn(0,1);
#ifdef DUMP_GCSE_INFO
         if (icdFile)
            fprintf(icdFile,"\n*************************FUNCTION %s********************************\n",currentfunc->name) ;
#endif

/*
 * icode optimizations goes here.  Note that LCSE is done through
 * DAG construction during the actual construction of the blocks
 * so it is already done at this point.
 *
 * Order IS important!!!!!!!!! be careful!!!!!
 */
				/* Global opts */
				flows_and_doms();
            CalculatePointers() ;
            CalculateEquations(intermed_head) ;
            if (prm_globsub)
               gcse() ;
            if (prm_copyprop)
               CopyPropagation() ;

            if (prm_optcode)
               commondelete(intermed_head); /* reuse common code frags */

				/* Local opts */
            if (prm_optdead)
               peep_icode(intermed_head); /* peepcode optimizer for icode */

            if (prm_optlive)
               LiveAnalysis() ;
				/* Code gen from icode */
            gen_strlab(currentfunc);  /* name of function */
            rewrite_icode(); /* Translate to machine code & dump */
            gcseRundown() ;
            RundownUse() ;
            RundownPointers() ;
}