/* 
   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
*/
#include        <stdio.h>
#include				<string.h>
#include        "lists.h"
#include        "expr.h"
#include        "c.h"
#include        "gen68.h"
#include 				"diag.h"

extern SNODE *funcstmt,*funcendstmt ;
extern SYM *thissp ;
extern long lc_maxauto;
extern int linkreg;
extern long framedepth;
extern TYP              stdfunc;
extern struct amode     push[], pop[], mvma7[], mvma7i[];
extern OCODE *peep_tail, *peep_head, *peep_insert;
extern long stackdepth;
extern SYM *currentfunc;
extern int prm_cplusplus,prm_linkreg, prm_phiform, prm_68020, prm_68010;
extern int prm_rel, prm_smallcode, prm_profiler, prm_coldfire;
extern long firstlabel, nextlabel;
extern int global_flag;
extern int save_mask, fsave_mask;
extern TABLE *gsyms;
extern ENODE *thisenode ;
extern ENODE *block_rundown ;
extern char dregs[],aregs[],fregs[] ;
extern int funcfloat ; /* unused, placeholder */
extern int rmaskcnt ;
extern int prm_smartframes ;

static int returndreg ;
static int 	diddef;
static int     breaklab;
static int     contlab;
int     retlab;
static long gswitchbottom, gswitchcount;
static long gswitchtop;
static long plabel;
static long retsize ;


void genstmtini(void)
{
}
AMODE    *makedreg(int r)
/*
 *      make an address reference to a data register.
 */
{       AMODE    *ap;
        ap = xalloc(sizeof(AMODE));
        ap->mode = am_dreg;
        ap->preg = r;
        return ap;
}

AMODE    *makeareg(int r)
/*
 *      make an address reference to an address register.
 */
{       AMODE    *ap;
        ap = xalloc(sizeof(AMODE));
        ap->mode = am_areg;
        ap->preg = r;
        return ap;
}

AMODE    *makefreg(int r)
/*
 *      make an address reference to a data register.
 */
{       AMODE    *ap;
        ap = xalloc(sizeof(AMODE));
        ap->mode = am_freg;
        ap->preg = r;
        return ap;
}
AMODE    *make_mask(int mask, int floatflag)
/*
 *      generate the mask address structure.
 */
{       AMODE    *ap;
        ap = xalloc(sizeof(AMODE));
				if (floatflag)
        	ap->mode = am_fmask;
        else
					ap->mode = am_mask;
        ap->offset = (ENODE *)mask;
        return ap;
}

AMODE    *make_direct(int i)
/*
 *      make a direct reference to an immediate value.
 */
{       return make_offset(makeintnode(en_icon,i));
}

AMODE    *make_strlab(char *s)
/*
 *      generate a direct reference to a string label.
 */
{       AMODE    *ap;
        ap = xalloc(sizeof(AMODE));
        ap->mode = am_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;
        initstack();            /* initialize temp registers */
        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_codes(op_bra,0,make_label(contlab),0);
								lab3 = nextlabel++;
								gen_label(lab3);
                genstmt(stmt->s1);
								gen_label(contlab);
                initstack();
								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);
                initstack();
                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++;
        initstack();
        if( stmt->label != 0 )
               	gen_void(stmt->label);
				
        gen_codes(op_bra,0,make_label(start_label),0);
        gen_label(loop_label);
        if( stmt->s1 != 0 ) {
								breaklab = exit_label;
                genstmt(stmt->s1);
				}
				if (stmt->lst)
		 			gen_line(stmt->lst);
				gen_label(contlab);
        initstack();
        if( stmt->s2 != 0 )
								gen_void(stmt->s2) ;
				gen_label(start_label);
        initstack();
        if( stmt->exp != 0 )
                truejp(stmt->exp,loop_label);
				else
						gen_codes(op_bra,0,make_label(loop_label),0);
				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 */
        initstack();            /* clear temps */
        falsejp(stmt->exp,lab1);
        genstmt(stmt->s1);
        if( stmt->s2 != 0 )             /* else part exists */
                {
                gen_codes(op_bra,0,make_label(lab2),0);
                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, looplab;
        oldcont = contlab;
        oldbreak = breaklab;
        looplab = nextlabel++;
        contlab = nextlabel++;
        breaklab = nextlabel++;
        gen_label(looplab);
        genstmt(stmt->s1);      /* generate body */
        gen_label(contlab);
        initstack();
        truejp(stmt->exp,looplab);
        gen_label(breaklab);
        breaklab = oldbreak;
        contlab = oldcont;
}
void gen_genword(SNODE *stmt)
/*
 * Generate data in the code stream
 */
{
		gen_codes(op_genword,2,make_immed((int)stmt->exp),0);
}
AMODE *set_symbol(char *name, int isproc)
/*
 *      generate a call to a library routine.
 */
{       SYM     *sp;
        AMODE *result = xalloc(sizeof(AMODE));
        sp = gsearch(name);
        if( sp == 0 )
                {
                ++global_flag;
                sp = xalloc(sizeof(SYM));
                sp->tp = &stdfunc;
                sp->name = name;
								if (isproc)
                	sp->storage_class = sc_externalfunc;
								else
                	sp->storage_class = sc_external;
								sp->extflag = TRUE;
                insert(sp,gsyms);
                --global_flag;
                }
				result->mode = am_direct ;
				result->length = 4 ;
				result->offset = makenode(en_napccon,(void *)sp,0) ;
				return result;					
}
static char xdregs[3],xaregs[3],xfregs[3] ;
AMODE *flush_for_libcall()
{
	int i;
				for (i=0; i < 3 ; i++) {
					if (xdregs[i] = dregs[i])
						gen_push(i,am_dreg,0) ;
				}
				for (i=0; i < 3 ; i++) {
					if (xaregs[i] = aregs[i])
						gen_push(i,am_areg,0) ;
				}
				for (i=0; i < 3 ; i++) {
					if (xfregs[i] = fregs[i])
						gen_push(i,am_freg,0) ;
				}
}
void call_library2(char *lib_name, int size)
{
   AMODE *result = set_symbol(lib_name,1) ;
   gen_codes(op_bsr,0,result,0) ;
   gen_codes(op_add,4,make_immed(size),makeareg(7)) ;
}
AMODE *call_library(char *lib_name,int size)
/*
 *      generate a call to a library routine.
 */
{       
	int i ;
        AMODE *result;
				result = set_symbol(lib_name,1);
        gen_codes(op_bsr,0,result,0);
				if (size)
        	gen_codes(op_add,4,make_immed(size),makeareg(7));
				result = temp_data();
				if (result->preg != 0)
        	gen_codes(op_move,4,makedreg(0),result);
				result->tempflag = TRUE;
				for (i=2; i >= 0 ; i--) {
					if (xfregs[i])
						gen_pop(i,am_freg,0) ;
				}
				for (i=2; i >= 0 ; i--) {
					if (xaregs[i])
						gen_pop(i,am_areg,0) ;
				}
				for (i=2; i >= 0 ; i--) {
					if (xdregs[i])
						gen_pop(i,am_dreg,0) ;
				}
				return result;					
}

int analyzeswitch(SNODE *stmt)
/* 
 * Decide whitch type of switch statement to use
 */
{
	gswitchbottom = 0x7fffffff;
	gswitchtop = -0x80000000;
	gswitchcount = 0;
	stmt = stmt->s1;
	while (stmt) {
		if (!stmt->s2) {
			gswitchcount++;
			if ((int)stmt->label < gswitchbottom)
				gswitchbottom = (int)stmt->label;
			if ((int)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,AMODE *ap1, int deflab, int size, long *switchids, int *switchlabels, int *switchbinlabels)
/*
 * Recursively output the compare/jump tree for a type of binary search
 * on the case value
 */
{
	AMODE *ap2 = make_immed(switchids[avg]);
	AMODE *ap3 = make_label(switchlabels[avg]);
	if (switchbinlabels[avg] != -1)
		gen_label(switchbinlabels[avg]);
	gen_codes(op_cmp,4,ap2,ap1);
	gen_codes(op_beq,0,ap3,0);
	if (avg == lower) {
		ap3 = make_label(deflab);
		gen_codes(op_bra,0,ap3,0);
	}
	else {
		int avg1 = (lower + avg)/2;
		int avg2 = (higher + avg+1)/2;
		if (avg+1 < higher) 
			ap3 = make_label(switchbinlabels[avg2]=nextlabel++);
		else
			ap3 = make_label(deflab);
		if (size < 0)
			gen_codes(op_bgt,0,ap3,0);
		else
			gen_codes(op_bhi,0,ap3,0);
		bingen(lower,avg1,avg,ap1,deflab,size,switchids,switchlabels,switchbinlabels);
		if (avg+1 < higher)
			bingen(avg+1,avg2,higher,ap1,deflab,size,switchids,switchlabels,switchbinlabels);
	}
}
void genbinaryswitch(SNODE *stmt, int deflab)
/*
 * Main routine for handling the binary switch setup
 */
{
	int curlab, i=0,j,size = natural_size(stmt->exp);
	AMODE *ap1;
  long switchbottom=gswitchbottom, switchcount=gswitchcount;
  long switchtop=gswitchtop;
  int *switchlabels=0;
  long *switchids=0;
  int *switchbinlabels=0;
	curlab = nextlabel++;
  initstack();
  ap1 = gen_expr(stmt->exp,FALSE,FALSE,4);
	do_extend(ap1,ap1->length,F_DREG);
	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;
			}
	bingen(0,(switchcount)/2,switchcount,ap1,deflab,size,switchids,switchlabels,switchbinlabels);
	freeop(ap1) ;
}
void gencompactswitch(SNODE *stmt, int deflab)
/*
 * Generate a table lookup mechanism if the switch table isn't too sparse
 */
{       int             tablab,curlab,i,size;
        AMODE    *ap,*ap1,*ap2,*ap3;
  			long switchbottom=gswitchbottom, switchcount=gswitchcount;
			  long switchtop=gswitchtop;
  			int *switchlabels=0;
				tablab = nextlabel++;
        curlab = nextlabel++;
        initstack();
        ap = gen_expr(stmt->exp,FALSE,FALSE,4);
				size = ap->length;
				do_extend(ap,4,F_DREG | F_VOL);
				initstack();
				if (switchbottom) {
					gen_codes(op_sub,4,make_immed(switchbottom),ap);
					if (size < 0)
						gen_codes(op_blt,0,make_label(deflab),0);
					else {
						peep_tail->noopt = TRUE;
						gen_codes(op_bcs,0,make_label(deflab),0);
					}
				} else {
					if (size < 0) {
					  gen_codes(op_tst,4,ap,0);
						gen_codes(op_blt,0,make_label(deflab),0);
					}
				}
				gen_codes(op_cmp,4,make_immed(switchtop-switchbottom),ap);
				if (size < 0)
					gen_codes(op_bhs,0,make_label(deflab),0);
				else
					gen_codes(op_bcc,0,make_label(deflab),0);
				ap1= temp_addr();
				if (prm_68020 || prm_coldfire) {
					ap2 = xalloc(sizeof(AMODE));
					ap2->preg = ap1->preg;
					ap2->mode = am_pcindxdata;
                ap2->scale = 2;
					ap2->offset = makenode(en_labcon,(char *)tablab,0);
               gen_codes(op_lea,4, ap2, ap1);
					ap3 = xalloc(sizeof(AMODE));
					ap3->sreg = ap->preg;
					ap3->preg = ap1->preg;
					ap3->scale = 0;
               ap3->offset = makeintnode(en_icon,0);
					ap3->mode = am_ind;
               gen_codes(op_adda,4,ap3,ap1);  
				} else {
					ap2 = xalloc(sizeof(AMODE));
					if (prm_rel) {
						ap2->preg = ap1->preg;
						ap2->mode = am_pcindx;
					}
					else {
						ap2->mode = am_adirect;
						if (prm_smallcode)
							ap2->preg = 2;
						else
							ap2->preg = 4;
					}
               ap2->offset = makeintnode(en_labcon,tablab);
					gen_codes(op_lea,0,ap2,ap1);
					if (prm_rel || prm_smallcode)
						gen_codes(op_asl,4,make_immed(1),ap);
					else
						gen_codes(op_asl,4,make_immed(2),ap);
					if (prm_rel) {
						gen_codes(op_add,4,ap,ap1);
						ap2->mode = am_ind;
						gen_codes(op_add,2,ap2,ap1);
					}
					else {
						ap3 = xalloc(sizeof(AMODE)) ;
						ap3->sreg = ap->preg;
						ap3->preg = ap1->preg;
						ap3->scale = 0;
                  ap3->offset = makeintnode(en_icon,0);
						ap3->mode = am_baseindxdata;
						gen_codes(op_move,4,ap3,ap1);
					}
				}
				ap1->mode = am_ind;
				gen_codes(op_jmp,0,ap1,0);

				initstack();
				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++)
      if (!prm_coldfire && (prm_smallcode || prm_rel))
			gen_codes(op_dcl,2,make_label(switchlabels[i]),0);
		else
			gen_codes(op_dcl,4,make_label(switchlabels[i]),0);
}

void gensimpleswitch(SNODE *stmt, int deflab)
{
	int curlab, i=0,j;
	AMODE *ap1;
  long switchbottom=gswitchbottom, switchcount=gswitchcount;
  long switchtop=gswitchtop;
  int *switchlabels=0;
  long *switchids=0;
  int *switchbinlabels=0;
	curlab = nextlabel++;
  initstack();
  ap1 = gen_expr(stmt->exp,FALSE,FALSE,4);
	do_extend(ap1,ap1->length,F_DREG);
	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;
			}
	for (i=0; i < switchcount; i++) {
		AMODE *ap2 = make_immed(switchids[i]);
		AMODE *ap3 = make_label(switchlabels[i]);
		gen_codes(op_cmp,ap1->length,ap2,ap1);
		gen_code(op_beq,ap3,0);
	}
	gen_codes(op_jmp,0,make_label(deflab),0);
	freeop(ap1);
}
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 AddProfilerData(void)
{
	char pname[256];
	if (prm_profiler) {
		sprintf(pname,"%s",currentfunc->name);
		plabel = stringlit(pname,FALSE,strlen(pname)+1);
		gen_codes(op_pea,4,make_label(plabel),0);
		call_library("__profile_in",4);
	}
}
void SubProfilerData(void)
{
	if (prm_profiler) {
		gen_codes(op_pea,4,make_label(plabel),0);
		call_library("__profile_out",4);
	}
}
void genreturn(SNODE *stmt,int flag)
/*
 *      generate a return statement.
 */
{       AMODE    *ap,*ap1,*ap2,*ap3;
				ENODE *mvn1 ;
				int size;
				SubProfilerData();
        if( stmt != 0 && stmt->exp != 0 )
        {
                initstack();
								if (currentfunc->tp->btp && isstructured(currentfunc->tp->btp)) {
									int lbl;
									lbl = nextlabel++;
									size = currentfunc->tp->btp->size;
  	              ap = gen_expr(stmt->exp,FALSE,TRUE,4);
									do_extend(ap,4,F_AREG | F_VOL) ;
									ap2 = xalloc(sizeof(AMODE));
									if (prm_linkreg && !currentfunc->intflag) {
										if ((currentfunc->pascaldefn || currentfunc->isstdcall) && currentfunc->tp->lst.head && currentfunc->tp->lst.head != (SYM *)-1) {
											ap2->preg = linkreg;
											ap2->mode = am_indx;
                                 ap2->offset = makeintnode(en_icon,(currentfunc->tp->lst.head->value.i + ((currentfunc->tp->lst.head->tp->size +3) &0xFFFFFFFCL)));
										}
										else {
											ap2->preg = linkreg;
											ap2->mode = am_indx;
                                 ap2->offset = makeintnode(en_icon,8);
										}
									}
									else if ( prm_phiform || currentfunc->intflag) {
										if ((currentfunc->pascaldefn || currentfunc->isstdcall) && currentfunc->tp->lst.head && currentfunc->tp->lst.head != (SYM *)-1) {
											ap2->preg = linkreg;
											ap2->mode = am_indx;
                                 ap2->offset = makeintnode(en_icon,(currentfunc->tp->lst.head->value.i + ((currentfunc->tp->lst.head->tp->size +3) &0xFFFFFFFCL)));
										}
										else {
								 			ap2->preg = linkreg;
											ap2->mode = am_ind;
										}
									}
									else {
										if (currentfunc->pascaldefn && currentfunc->tp->lst.head && currentfunc->tp->lst.head != (SYM *)-1) {
											ap2->preg = 7;
											ap2->mode = am_indx;
                                 ap2->offset = makeintnode(en_icon,(framedepth+stackdepth+currentfunc->tp->lst.head->value.i + ((currentfunc->tp->lst.head->tp->size+3) & 0xfffffffcL)));
										}
										else {
											ap2->preg = 7;
											ap2->mode = am_indx;
                                 ap2->offset = makeintnode(en_icon,(framedepth+stackdepth));
										}
									}
// fixme - moveblock
									ap3 = temp_addr();
									ap1 = temp_data();
									gen_codes(op_move,4,ap2,ap3);
									ap->mode = am_ainc;
									ap3->mode = am_ainc;
									gen_codes(op_move,4,make_immed(size),ap1);
									gen_label(lbl);
									gen_codes(op_move,1,ap,ap3);
									gen_codes(op_sub,4,make_immed(1),ap1);
									gen_codes(op_bne,0,make_label(lbl),0);
									gen_codes(op_move,4,ap2,makedreg(0));
									freeop(ap1);
									freeop(ap3);
									freeop(ap);
								}
								else {
									size = currentfunc->tp->btp->size;
                           if (size == 4 && currentfunc->tp->btp->type == bt_float)
                              size = 7 ;
                           if (currentfunc->tp->btp->type == bt_long || currentfunc->tp->btp->type == bt_unsignedlong) {
                              size = currentfunc->tp->btp->type == bt_long ? -6 : 6 ;
                              ap = gen_expr(stmt->exp,FALSE,FALSE,size);
                              do_extend(ap,size, F_DOUBLEREG);
                           } else if (size > 6) {
										retsize = 10;
  	              	ap = gen_expr(stmt->exp,FALSE,FALSE,size);
										do_extend(ap,size, F_FREG);
									}
            	    else {
                                 returndreg = TRUE ;
											retsize = 4;
  	              		ap = gen_expr(stmt->exp,FALSE,FALSE,size);
											do_extend(ap,size, F_DREG | F_VOL);
              	  		if( ap->preg != 0 ) {
                	        gen_codes(op_move,size,makedreg(0),ap);
													ap = makedreg(0);
											}
									}
								}
        }
				if (flag & 1) {
        	if( retlab != -1 )
                gen_label(retlab);
					if (flag & 2)
						return ap ;
               if (currentfunc->value.classdata.eofdest) {
                  if (returndreg)
                     gen_codes(op_move,4,makedreg(0),push) ;
                  gen_expr(currentfunc->value.classdata.eofdest, TRUE,FALSE,0) ;
                  if (returndreg)
                     gen_codes(op_move,4,pop,makedreg(0)) ;

               }
					if ((!prm_linkreg || currentfunc->intflag) && (lc_maxauto))
						if (lc_maxauto > 8) {
							AMODE *ap = xalloc(sizeof(AMODE)); 
							ap->mode = am_indx;
                     ap->offset = makeintnode(en_icon,lc_maxauto);
							ap->preg = 7;
              	gen_codes(op_lea,0,ap,makeareg(7));
						}
						else
             	gen_codes(op_add,4,make_immed(lc_maxauto),makeareg(7));
          if( fsave_mask != 0 )
            gen_codes(op_fmovem,10,pop,make_mask(fsave_mask,1));
          if( save_mask != 0 )
              if (prm_coldfire)
                  if (rmaskcnt >1 )
             		{
                           gen_codes(op_movem,4,mvma7,make_mask(save_mask,0));
									mvn1 = xalloc(sizeof(struct enode));
									mvn1->nodetype = en_icon;
									mvn1->v.i = (rmaskcnt<<2);
									ap3 = xalloc(sizeof(struct amode));	
									ap3->mode = am_indx;
									ap3->preg = 7;
									ap3->offset = mvn1;
                           gen_codes(op_lea,4,ap3,mvma7i);
                           freeop(ap3);
                   }
                   else
                           gen_codes(op_move,4,pop,make_mask(save_mask,0));
		    			else
                     gen_codes(op_movem,4,pop,make_mask(save_mask,0));
               if (prm_linkreg && !currentfunc->intflag && (currentfunc->tp->lst.head && currentfunc->tp->lst.head != (SYM *)-1 || lc_maxauto) || !prm_smartframes) {
						gen_codes(op_unlk,0,makeareg(linkreg),0);
					}
					if (currentfunc->intflag)
           	gen_codes(op_rte,0,0,0);
					else
						if (currentfunc->pascaldefn || currentfunc->isstdcall) {
							long retsize = 0;
							if (currentfunc->tp->lst.head && currentfunc->tp->lst.head != (SYM *)-1) {
								SYM *sp = currentfunc->tp->lst.head;
								if (currentfunc->isstdcall)
									while (sp->next)
										sp = sp->next;
								retsize = sp->value.i+((sp->tp->size + 3) & 0xfffffffcL);
								if (prm_linkreg)
									retsize -= 8;
							} 
							if (currentfunc->tp->btp && isstructured(currentfunc->tp->btp))
								retsize +=4;
							if (retsize) {
								if (prm_68020 || prm_68010)
									gen_codes(op_rtd,0,make_immed(retsize),0);
								else {
									ap = temp_addr();
									freeop(ap);
									gen_codes(op_move,4,pop,ap);
									if (retsize > 8) {
										ap1 = xalloc(sizeof(AMODE));
										ap1->mode = am_indx;
                              ap1->offset = makeintnode(en_icon,retsize);
										ap1->preg = 7;
                		gen_codes(op_lea,0,ap1,makeareg(7));
									}
									else
                		gen_codes(op_add,4,make_immed(retsize),makeareg(7));
									ap->mode = am_ind;
									gen_codes(op_jmp,0,ap,0);
								}
								return;
							}
						}
           	gen_codes(op_rts,0,0,0);
        }
        else {
					if (retlab == -1)
						retlab = nextlabel++;
          gen_codes(op_bra,0,make_label(retlab),0);
				}
}

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_codes(op_bra,0,make_label((int)stmt->label),0);
                                break;
                        case st_expr:
                                initstack();
                                gen_void(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_codes(op_bra,0,make_label(contlab),0);
                                break;
                        case st_break:
		 														gen_codes(op_bra,0,make_label(breaklab),0);
                                break;
                        case st_switch:
                                genxswitch(stmt);
                                break;
												case st__genword:
																gen_genword(stmt);
																break;
												case st_asm:
																if (stmt->exp)
																	add_peep(stmt->exp);
																break;
                        default:
                                DIAG("unknown statement.");
                                break;
                        }
                stmt = stmt->next;
                }
}
#ifdef CPLUSPLUS
void scppinit(void)
/*
 * Call C++ reference variable and class initializers
 */
{
#ifdef XXXXX
	if (!strcmp(currentfunc->name,"_main")) {
		AMODE *ap1,*ap2,*ap3,*ap4;
		int lbl = nextlabel++;
		initstack();
		ap1 = temp_addr();
		ap4 = xalloc(sizeof(AMODE));
		ap4->preg = ap1->preg;
		ap4->mode = am_ind;
		ap2 = set_symbol("CPPSTART",0);
		ap3 = set_symbol("CPPEND",0);
		gen_codes(op_lea,4,ap2,ap1);
		gen_label(lbl);
		gen_codes(op_move,4,ap1,push);
		gen_codes(op_jsr,4,ap4,0);
		gen_codes(op_move,4,pop,ap1);
		gen_codes(op_add,4,make_immed(4),ap1);
		gen_codes(op_cmp,4,ap3,ap1);
		gen_codes(op_bhi,0,make_label(lbl),0);
		freeop(ap1);
	}
#endif
}
#endif
void genfunc(SNODE *stmt)
/*
 *      generate a function body.
 */
{           //int isconst = FALSE;
            returndreg = FALSE ;
				retsize = 0;
				stackdepth = 0;
        retlab = contlab = breaklab = -1;

				funcfloat = 0;
            if (funcstmt)
               gen_line(funcstmt) ;
            funcstmt = 0 ;
				if (stmt->stype == st_line) {
					gen_line(stmt);
					stmt = stmt->next;
				}
				if (!stmt) {
					gen_codelab(currentfunc);
          gen_codes(op_rts,0,0,0);
					flush_peep();
					return;
				}
#ifdef CPLUSPLUS
#ifdef XXXXX              
				if (currentfunc->value.classdata.cppflags & PF_CONSTRUCTOR) {
					isconst = TRUE;
				}
#endif
				if (currentfunc->value.classdata.cppflags & (PF_HEADERFUNC | PF_INSTANTIATED))
					gen_virtual(currentfunc);
				else
#endif
					gen_codelab(currentfunc);  /* name of function */
					
        opt1(stmt);			/* push args & also subtracts SP */
#ifdef CPLUSPLUS
#ifdef XXXXX
            if (isconst) {
					SYM *psp = currentfunc->parentclass ;
					if (currentfunc->value.classdata.basecons)
						gen_void(currentfunc->value.classdata.basecons);
               if (psp->value.classdata.baseclass->vtabsp) {
                     CLASSLIST *l = psp->value.classdata.baseclass ;
							ENODE *thisn = thisenode ;
                     ENODE *ts = makenode(en_nacon,psp->value.classdata.baseclass->vtabsp, 0) ;
                     ENODE *exp1, *exp2 ;
							thisn = makenode(en_l_ref,thisn,0);
                     while (l) {
                        if (l->isvtab) {
                           exp1 = makenode(en_addstruc,ts,makeintnode(en_icon,l->vtaboffs)) ;
                           exp2 = makenode(en_addstruc,thisn,makeintnode(en_icon,l->offset)) ;
                           exp2 = makenode(en_l_ref,exp2,0);
                           exp2 = makenode(en_assign,exp2,exp1) ;
                           initstack() ;
                           gen_expr(exp2,FALSE,TRUE,4) ;
                        }
                        l = l->link ;
                     }
					}
				}
#endif
				if (prm_cplusplus)
					scppinit();
#endif
        genstmt(stmt);
#ifdef CPLUSPLUS
				if (block_rundown)
					if (retsize)
						if (retsize > 4) {
							gen_codes(op_fmove,10,makefreg(0), push);
							gen_void(block_rundown);
							gen_codes(op_fmove,10,pop,makefreg(0));
						}
						else {
							gen_codes(op_move,4,makedreg(0),push);
							gen_void(block_rundown);
							gen_codes(op_move,4,pop, makedreg(0));
						}
					else
						gen_void(block_rundown);
#endif
        if (funcendstmt)
				gen_line(funcendstmt) ;
        funcendstmt = 0 ;
        genreturn(0,1);
#ifdef CPLUSPLUS
				thissp->inreg = FALSE;
				thissp->value.i = 4;
#endif
        flush_peep();
#ifdef CPLUSPLUS
				if (currentfunc->value.classdata.cppflags & (PF_HEADERFUNC | PF_INSTANTIATED))
					gen_endvirtual(currentfunc);
#endif
}