File:  [gforth] / gforth / engine / main.c
Revision 1.146: download - view: text, annotated - select for diffs
Sat Jan 22 21:06:03 2005 UTC (19 years, 3 months ago) by anton
Branches: MAIN
CVS tags: HEAD
preparation for gcc PR 15242 workaround
minor changes

    1: /* command line interpretation, image loading etc. for Gforth
    2: 
    3: 
    4:   Copyright (C) 1995,1996,1997,1998,2000,2003,2004 Free Software Foundation, Inc.
    5: 
    6:   This file is part of Gforth.
    7: 
    8:   Gforth is free software; you can redistribute it and/or
    9:   modify it under the terms of the GNU General Public License
   10:   as published by the Free Software Foundation; either version 2
   11:   of the License, or (at your option) any later version.
   12: 
   13:   This program is distributed in the hope that it will be useful,
   14:   but WITHOUT ANY WARRANTY; without even the implied warranty of
   15:   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16:   GNU General Public License for more details.
   17: 
   18:   You should have received a copy of the GNU General Public License
   19:   along with this program; if not, write to the Free Software
   20:   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
   21: */
   22: 
   23: #include "config.h"
   24: #include "forth.h"
   25: #include <errno.h>
   26: #include <ctype.h>
   27: #include <stdio.h>
   28: #include <unistd.h>
   29: #include <string.h>
   30: #include <math.h>
   31: #include <sys/types.h>
   32: #ifndef STANDALONE
   33: #include <sys/stat.h>
   34: #endif
   35: #include <fcntl.h>
   36: #include <assert.h>
   37: #include <stdlib.h>
   38: #include <signal.h>
   39: #ifndef STANDALONE
   40: #if HAVE_SYS_MMAN_H
   41: #include <sys/mman.h>
   42: #endif
   43: #endif
   44: #include "io.h"
   45: #include "getopt.h"
   46: #ifdef STANDALONE
   47: #include <systypes.h>
   48: #endif
   49: 
   50: typedef enum prim_num {
   51: /* definitions of N_execute etc. */
   52: #include PRIM_NUM_I
   53:   N_START_SUPER
   54: } PrimNum;
   55: 
   56: /* global variables for engine.c 
   57:    We put them here because engine.c is compiled several times in
   58:    different ways for the same engine. */
   59: Cell *SP;
   60: Float *FP;
   61: Address UP=NULL;
   62: 
   63: #ifdef HAS_FFCALL
   64: Cell *RP;
   65: Address LP;
   66: 
   67: #include <callback.h>
   68: 
   69: va_alist clist;
   70: 
   71: void engine_callback(Xt* fcall, void * alist)
   72: {
   73:   /* save global valiables */
   74:   Cell *rp = RP;
   75:   Cell *sp = SP;
   76:   Float *fp = FP;
   77:   Address lp = LP;
   78: 
   79:   clist = (va_alist)alist;
   80: 
   81:   engine(fcall, sp, rp, fp, lp);
   82: 
   83:   /* restore global variables */
   84:   RP = rp;
   85:   SP = sp;
   86:   FP = fp;
   87:   LP = lp;
   88: }
   89: #endif
   90: 
   91: #ifdef GFORTH_DEBUGGING
   92: /* define some VM registers as global variables, so they survive exceptions;
   93:    global register variables are not up to the task (according to the 
   94:    GNU C manual) */
   95: Xt *saved_ip;
   96: Cell *rp;
   97: #endif
   98: 
   99: #ifdef NO_IP
  100: Label next_code;
  101: #endif
  102: 
  103: #ifdef HAS_FILE
  104: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
  105: char* pfileattr[6]={"r","r","r+","r+","w","w"};
  106: 
  107: #ifndef O_BINARY
  108: #define O_BINARY 0
  109: #endif
  110: #ifndef O_TEXT
  111: #define O_TEXT 0
  112: #endif
  113: 
  114: int ufileattr[6]= {
  115:   O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
  116:   O_RDWR  |O_BINARY, O_RDWR  |O_BINARY,
  117:   O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
  118: #endif
  119: /* end global vars for engine.c */
  120: 
  121: #define PRIM_VERSION 1
  122: /* increment this whenever the primitives change in an incompatible way */
  123: 
  124: #ifndef DEFAULTPATH
  125: #  define DEFAULTPATH "."
  126: #endif
  127: 
  128: #ifdef MSDOS
  129: jmp_buf throw_jmp_buf;
  130: #endif
  131: 
  132: #if defined(DOUBLY_INDIRECT)
  133: #  define CFA(n)	({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
  134: #else
  135: #  define CFA(n)	((Cell)(symbols+((n)&~0x4000UL)))
  136: #endif
  137: 
  138: #define maxaligned(n)	(typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
  139: 
  140: static UCell dictsize=0;
  141: static UCell dsize=0;
  142: static UCell rsize=0;
  143: static UCell fsize=0;
  144: static UCell lsize=0;
  145: int offset_image=0;
  146: int die_on_signal=0;
  147: #ifndef INCLUDE_IMAGE
  148: static int clear_dictionary=0;
  149: UCell pagesize=1;
  150: char *progname;
  151: #else
  152: char *progname = "gforth";
  153: int optind = 1;
  154: #endif
  155: 
  156: #define CODE_BLOCK_SIZE (4096*1024) /* !! overflow handling for -native */
  157: Address code_area=0;
  158: Cell code_area_size = CODE_BLOCK_SIZE;
  159: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
  160: 					   does for the dictionary */
  161: Address start_flush=NULL; /* start of unflushed code */
  162: Cell last_jump=0; /* if the last prim was compiled without jump, this
  163:                      is it's number, otherwise this contains 0 */
  164: 
  165: static int no_super=0;   /* true if compile_prim should not fuse prims */
  166: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
  167: 					     dynamically */
  168: static int print_metrics=0; /* if true, print metrics on exit */
  169: static int static_super_number = 10000000; /* number of ss used if available */
  170: #define MAX_STATE 4 /* maximum number of states */
  171: static int maxstates = MAX_STATE; /* number of states for stack caching */
  172: static int ss_greedy = 0; /* if true: use greedy, not optimal ss selection */
  173: static int diag = 0; /* if true: print diagnostic informations */
  174: static int relocs = 0;
  175: static int nonrelocs = 0;
  176: 
  177: #ifdef HAS_DEBUG
  178: int debug=0;
  179: # define debugp(x...) if (debug) fprintf(x);
  180: #else
  181: # define perror(x...)
  182: # define fprintf(x...)
  183: # define debugp(x...)
  184: #endif
  185: 
  186: ImageHeader *gforth_header;
  187: Label *vm_prims;
  188: #ifdef DOUBLY_INDIRECT
  189: Label *xts; /* same content as vm_prims, but should only be used for xts */
  190: #endif
  191: 
  192: #ifndef NO_DYNAMIC
  193: #define MAX_IMMARGS 2
  194: 
  195: typedef struct {
  196:   Label start; /* NULL if not relocatable */
  197:   Cell length; /* only includes the jump iff superend is true*/
  198:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
  199:   char superend; /* true if primitive ends superinstruction, i.e.,
  200:                      unconditional branch, execute, etc. */
  201:   Cell nimmargs;
  202:   struct immarg {
  203:     Cell offset; /* offset of immarg within prim */
  204:     char rel;    /* true if immarg is relative */
  205:   } immargs[MAX_IMMARGS];
  206: } PrimInfo;
  207: 
  208: PrimInfo *priminfos;
  209: PrimInfo **decomp_prims;
  210: 
  211: const char const* const prim_names[]={
  212: #include PRIM_NAMES_I
  213: };
  214: 
  215: static int is_relocatable(int p)
  216: {
  217:   return !no_dynamic && priminfos[p].start != NULL;
  218: }
  219: #else /* defined(NO_DYNAMIC) */
  220: static int is_relocatable(int p)
  221: {
  222:   return 0;
  223: }
  224: #endif /* defined(NO_DYNAMIC) */
  225: 
  226: #ifdef MEMCMP_AS_SUBROUTINE
  227: int gforth_memcmp(const char * s1, const char * s2, size_t n)
  228: {
  229:   return memcmp(s1, s2, n);
  230: }
  231: #endif
  232: 
  233: static Cell max(Cell a, Cell b)
  234: {
  235:   return a>b?a:b;
  236: }
  237: 
  238: static Cell min(Cell a, Cell b)
  239: {
  240:   return a<b?a:b;
  241: }
  242: 
  243: /* image file format:
  244:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
  245:  *   padding to a multiple of 8
  246:  *   magic: "Gforth3x" means format 0.6,
  247:  *              where x is a byte with
  248:  *              bit 7:   reserved = 0
  249:  *              bit 6:5: address unit size 2^n octets
  250:  *              bit 4:3: character size 2^n octets
  251:  *              bit 2:1: cell size 2^n octets
  252:  *              bit 0:   endian, big=0, little=1.
  253:  *  The magic are always 8 octets, no matter what the native AU/character size is
  254:  *  padding to max alignment (no padding necessary on current machines)
  255:  *  ImageHeader structure (see forth.h)
  256:  *  data (size in ImageHeader.image_size)
  257:  *  tags ((if relocatable, 1 bit/data cell)
  258:  *
  259:  * tag==1 means that the corresponding word is an address;
  260:  * If the word is >=0, the address is within the image;
  261:  * addresses within the image are given relative to the start of the image.
  262:  * If the word =-1 (CF_NIL), the address is NIL,
  263:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
  264:  * If the word =CF(DODOES), it's a DOES> CFA
  265:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
  266:  *					possibly containing a jump to dodoes)
  267:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
  268:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
  269:  *                                        it's the threaded code of a primitive
  270:  * bits 13..9 of a primitive token state which group the primitive belongs to,
  271:  * bits 8..0 of a primitive token index into the group
  272:  */
  273: 
  274: Cell groups[32] = {
  275:   0,
  276:   0
  277: #undef GROUP
  278: #undef GROUPADD
  279: #define GROUPADD(n) +n
  280: #define GROUP(x, n) , 0
  281: #include PRIM_GRP_I
  282: #undef GROUP
  283: #undef GROUPADD
  284: #define GROUP(x, n)
  285: #define GROUPADD(n)
  286: };
  287: 
  288: unsigned char *branch_targets(Cell *image, const unsigned char *bitstring,
  289: 			      int size, Cell base)
  290:      /* produce a bitmask marking all the branch targets */
  291: {
  292:   int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
  293:   Cell token;
  294:   unsigned char bits;
  295:   unsigned char *result=malloc(steps);
  296: 
  297:   memset(result, 0, steps);
  298:   for(k=0; k<steps; k++) {
  299:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  300:       if(bits & (1U << (RELINFOBITS-1))) {
  301: 	assert(i*sizeof(Cell) < size);
  302:         token=image[i];
  303: 	if (token>=base) { /* relocatable address */
  304: 	  UCell bitnum=(token-base)/sizeof(Cell);
  305: 	  result[bitnum/RELINFOBITS] |= 1U << ((~bitnum)&(RELINFOBITS-1));
  306: 	}
  307:       }
  308:     }
  309:   }
  310:   return result;
  311: }
  312: 
  313: void relocate(Cell *image, const unsigned char *bitstring, 
  314:               int size, Cell base, Label symbols[])
  315: {
  316:   int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
  317:   Cell token;
  318:   char bits;
  319:   Cell max_symbols;
  320:   /* 
  321:    * A virtual start address that's the real start address minus 
  322:    * the one in the image 
  323:    */
  324:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
  325:   unsigned char *targets = branch_targets(image, bitstring, size, base);
  326: 
  327:   /* group index into table */
  328:   if(groups[31]==0) {
  329:     int groupsum=0;
  330:     for(i=0; i<32; i++) {
  331:       groupsum += groups[i];
  332:       groups[i] = groupsum;
  333:       /* printf("group[%d]=%d\n",i,groupsum); */
  334:     }
  335:     i=0;
  336:   }
  337:   
  338: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
  339:   
  340:   for (max_symbols=0; symbols[max_symbols]!=0; max_symbols++)
  341:     ;
  342:   max_symbols--;
  343: 
  344:   for(k=0; k<steps; k++) {
  345:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  346:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
  347:       if(bits & (1U << (RELINFOBITS-1))) {
  348: 	assert(i*sizeof(Cell) < size);
  349: 	/* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
  350:         token=image[i];
  351: 	if(token<0) {
  352: 	  int group = (-token & 0x3E00) >> 9;
  353: 	  if(group == 0) {
  354: 	    switch(token|0x4000) {
  355: 	    case CF_NIL      : image[i]=0; break;
  356: #if !defined(DOUBLY_INDIRECT)
  357: 	    case CF(DOCOL)   :
  358: 	    case CF(DOVAR)   :
  359: 	    case CF(DOCON)   :
  360: 	    case CF(DOUSER)  : 
  361: 	    case CF(DODEFER) : 
  362: 	    case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
  363: 	    case CF(DOESJUMP): image[i]=0; break;
  364: #endif /* !defined(DOUBLY_INDIRECT) */
  365: 	    case CF(DODOES)  :
  366: 	      MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
  367: 	      break;
  368: 	    default          : /* backward compatibility */
  369: /*	      printf("Code field generation image[%x]:=CFA(%x)\n",
  370: 		     i, CF(image[i])); */
  371: 	      if (CF((token | 0x4000))<max_symbols) {
  372: 		image[i]=(Cell)CFA(CF(token));
  373: #ifdef DIRECT_THREADED
  374: 		if ((token & 0x4000) == 0) { /* threade code, no CFA */
  375: 		  if (targets[k] & (1U<<(RELINFOBITS-1-j)))
  376: 		    compile_prim1(0);
  377: 		  compile_prim1(&image[i]);
  378: 		}
  379: #endif
  380: 	      } else
  381: 		fprintf(stderr,"Primitive %ld used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n",(long)CF(token),(long)&image[i], i, PACKAGE_VERSION);
  382: 	    }
  383: 	  } else {
  384: 	    int tok = -token & 0x1FF;
  385: 	    if (tok < (groups[group+1]-groups[group])) {
  386: #if defined(DOUBLY_INDIRECT)
  387: 	      image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
  388: #else
  389: 	      image[i]=(Cell)CFA((groups[group]+tok));
  390: #endif
  391: #ifdef DIRECT_THREADED
  392: 	      if ((token & 0x4000) == 0) { /* threade code, no CFA */
  393: 		if (targets[k] & (1U<<(RELINFOBITS-1-j)))
  394: 		  compile_prim1(0);
  395: 		compile_prim1(&image[i]);
  396: 	      }
  397: #endif
  398: 	    } else
  399: 	      fprintf(stderr,"Primitive %lx, %d of group %d used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n", (long)-token, tok, group, (long)&image[i],i,PACKAGE_VERSION);
  400: 	  }
  401: 	} else {
  402:           /* if base is > 0: 0 is a null reference so don't adjust*/
  403:           if (token>=base) {
  404:             image[i]+=(Cell)start;
  405:           }
  406:         }
  407:       }
  408:     }
  409:   }
  410:   free(targets);
  411:   finish_code();
  412:   ((ImageHeader*)(image))->base = (Address) image;
  413: }
  414: 
  415: UCell checksum(Label symbols[])
  416: {
  417:   UCell r=PRIM_VERSION;
  418:   Cell i;
  419: 
  420:   for (i=DOCOL; i<=DOESJUMP; i++) {
  421:     r ^= (UCell)(symbols[i]);
  422:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  423:   }
  424: #ifdef DIRECT_THREADED
  425:   /* we have to consider all the primitives */
  426:   for (; symbols[i]!=(Label)0; i++) {
  427:     r ^= (UCell)(symbols[i]);
  428:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  429:   }
  430: #else
  431:   /* in indirect threaded code all primitives are accessed through the
  432:      symbols table, so we just have to put the base address of symbols
  433:      in the checksum */
  434:   r ^= (UCell)symbols;
  435: #endif
  436:   return r;
  437: }
  438: 
  439: Address verbose_malloc(Cell size)
  440: {
  441:   Address r;
  442:   /* leave a little room (64B) for stack underflows */
  443:   if ((r = malloc(size+64))==NULL) {
  444:     perror(progname);
  445:     exit(1);
  446:   }
  447:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
  448:   debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
  449:   return r;
  450: }
  451: 
  452: static Address next_address=0;
  453: void after_alloc(Address r, Cell size)
  454: {
  455:   if (r != (Address)-1) {
  456:     debugp(stderr, "success, address=$%lx\n", (long) r);
  457:     if (pagesize != 1)
  458:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
  459:   } else {
  460:     debugp(stderr, "failed: %s\n", strerror(errno));
  461:   }
  462: }
  463: 
  464: #ifndef MAP_FAILED
  465: #define MAP_FAILED ((Address) -1)
  466: #endif
  467: #ifndef MAP_FILE
  468: # define MAP_FILE 0
  469: #endif
  470: #ifndef MAP_PRIVATE
  471: # define MAP_PRIVATE 0
  472: #endif
  473: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
  474: # define MAP_ANON MAP_ANONYMOUS
  475: #endif
  476: 
  477: #if defined(HAVE_MMAP)
  478: static Address alloc_mmap(Cell size)
  479: {
  480:   Address r;
  481: 
  482: #if defined(MAP_ANON)
  483:   debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
  484:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
  485: #else /* !defined(MAP_ANON) */
  486:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
  487:      apparently defaults) */
  488:   static int dev_zero=-1;
  489: 
  490:   if (dev_zero == -1)
  491:     dev_zero = open("/dev/zero", O_RDONLY);
  492:   if (dev_zero == -1) {
  493:     r = MAP_FAILED;
  494:     debugp(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
  495: 	      strerror(errno));
  496:   } else {
  497:     debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
  498:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
  499:   }
  500: #endif /* !defined(MAP_ANON) */
  501:   after_alloc(r, size);
  502:   return r;  
  503: }
  504: #endif
  505: 
  506: Address my_alloc(Cell size)
  507: {
  508: #if HAVE_MMAP
  509:   Address r;
  510: 
  511:   r=alloc_mmap(size);
  512:   if (r!=(Address)MAP_FAILED)
  513:     return r;
  514: #endif /* HAVE_MMAP */
  515:   /* use malloc as fallback */
  516:   return verbose_malloc(size);
  517: }
  518: 
  519: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
  520: {
  521:   Address image = MAP_FAILED;
  522: 
  523: #if defined(HAVE_MMAP)
  524:   if (offset==0) {
  525:     image=alloc_mmap(dictsize);
  526:     debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
  527:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
  528:     after_alloc(image,dictsize);
  529:   }
  530: #endif /* defined(HAVE_MMAP) */
  531:   if (image == (Address)MAP_FAILED) {
  532:     image = my_alloc(dictsize+offset)+offset;
  533:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
  534:     fread(image, 1, imagesize, file);
  535:   }
  536:   return image;
  537: }
  538: 
  539: void set_stack_sizes(ImageHeader * header)
  540: {
  541:   if (dictsize==0)
  542:     dictsize = header->dict_size;
  543:   if (dsize==0)
  544:     dsize = header->data_stack_size;
  545:   if (rsize==0)
  546:     rsize = header->return_stack_size;
  547:   if (fsize==0)
  548:     fsize = header->fp_stack_size;
  549:   if (lsize==0)
  550:     lsize = header->locals_stack_size;
  551:   dictsize=maxaligned(dictsize);
  552:   dsize=maxaligned(dsize);
  553:   rsize=maxaligned(rsize);
  554:   lsize=maxaligned(lsize);
  555:   fsize=maxaligned(fsize);
  556: }
  557: 
  558: void alloc_stacks(ImageHeader * header)
  559: {
  560:   header->dict_size=dictsize;
  561:   header->data_stack_size=dsize;
  562:   header->fp_stack_size=fsize;
  563:   header->return_stack_size=rsize;
  564:   header->locals_stack_size=lsize;
  565: 
  566:   header->data_stack_base=my_alloc(dsize);
  567:   header->fp_stack_base=my_alloc(fsize);
  568:   header->return_stack_base=my_alloc(rsize);
  569:   header->locals_stack_base=my_alloc(lsize);
  570: }
  571: 
  572: #warning You can ignore the warnings about clobbered variables in go_forth
  573: int go_forth(Address image, int stack, Cell *entries)
  574: {
  575:   volatile ImageHeader *image_header = (ImageHeader *)image;
  576:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
  577:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
  578:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
  579: #ifdef GFORTH_DEBUGGING
  580:   volatile Cell *orig_rp0=rp0;
  581: #endif
  582:   Address lp0=image_header->locals_stack_base + lsize;
  583:   Xt *ip0=(Xt *)(image_header->boot_entry);
  584: #ifdef SYSSIGNALS
  585:   int throw_code;
  586: #endif
  587: 
  588:   /* ensure that the cached elements (if any) are accessible */
  589:   IF_spTOS(sp0--);
  590:   IF_fpTOS(fp0--);
  591:   
  592:   for(;stack>0;stack--)
  593:     *--sp0=entries[stack-1];
  594: 
  595: #ifdef SYSSIGNALS
  596:   get_winsize();
  597:    
  598:   install_signal_handlers(); /* right place? */
  599:   
  600:   if ((throw_code=setjmp(throw_jmp_buf))) {
  601:     static Cell signal_data_stack[8];
  602:     static Cell signal_return_stack[8];
  603:     static Float signal_fp_stack[1];
  604: 
  605:     signal_data_stack[7]=throw_code;
  606: 
  607: #ifdef GFORTH_DEBUGGING
  608:     debugp(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
  609: 	      throw_code, saved_ip, rp);
  610:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
  611:       /* no rstack overflow or underflow */
  612:       rp0 = rp;
  613:       *--rp0 = (Cell)saved_ip;
  614:     }
  615:     else /* I love non-syntactic ifdefs :-) */
  616:       rp0 = signal_return_stack+8;
  617: #else  /* !defined(GFORTH_DEBUGGING) */
  618:     debugp(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
  619:       rp0 = signal_return_stack+8;
  620: #endif /* !defined(GFORTH_DEBUGGING) */
  621:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
  622:     
  623:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
  624: 		       rp0, signal_fp_stack, 0));
  625:   }
  626: #endif
  627: 
  628:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
  629: }
  630: 
  631: #ifndef INCLUDE_IMAGE
  632: void print_sizes(Cell sizebyte)
  633:      /* print size information */
  634: {
  635:   static char* endianstring[]= { "   big","little" };
  636:   
  637:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
  638: 	  endianstring[sizebyte & 1],
  639: 	  1 << ((sizebyte >> 1) & 3),
  640: 	  1 << ((sizebyte >> 3) & 3),
  641: 	  1 << ((sizebyte >> 5) & 3));
  642: }
  643: 
  644: /* static superinstruction stuff */
  645: 
  646: struct cost { /* super_info might be a more accurate name */
  647:   char loads;       /* number of stack loads */
  648:   char stores;      /* number of stack stores */
  649:   char updates;     /* number of stack pointer updates */
  650:   char branch;	    /* is it a branch (SET_IP) */
  651:   unsigned char state_in;    /* state on entry */
  652:   unsigned char state_out;   /* state on exit */
  653:   unsigned char imm_ops;     /* number of immediate operands */
  654:   short offset;     /* offset into super2 table */
  655:   unsigned char length;      /* number of components */
  656: };
  657: 
  658: PrimNum super2[] = {
  659: #include SUPER2_I
  660: };
  661: 
  662: struct cost super_costs[] = {
  663: #include COSTS_I
  664: };
  665: 
  666: struct super_state {
  667:   struct super_state *next;
  668:   PrimNum super;
  669: };
  670: 
  671: #define HASH_SIZE 256
  672: 
  673: struct super_table_entry {
  674:   struct super_table_entry *next;
  675:   PrimNum *start;
  676:   short length;
  677:   struct super_state *ss_list; /* list of supers */
  678: } *super_table[HASH_SIZE];
  679: int max_super=2;
  680: 
  681: struct super_state *state_transitions=NULL;
  682: 
  683: int hash_super(PrimNum *start, int length)
  684: {
  685:   int i, r;
  686:   
  687:   for (i=0, r=0; i<length; i++) {
  688:     r <<= 1;
  689:     r += start[i];
  690:   }
  691:   return r & (HASH_SIZE-1);
  692: }
  693: 
  694: struct super_state **lookup_super(PrimNum *start, int length)
  695: {
  696:   int hash=hash_super(start,length);
  697:   struct super_table_entry *p = super_table[hash];
  698: 
  699:   /* assert(length >= 2); */
  700:   for (; p!=NULL; p = p->next) {
  701:     if (length == p->length &&
  702: 	memcmp((char *)p->start, (char *)start, length*sizeof(PrimNum))==0)
  703:       return &(p->ss_list);
  704:   }
  705:   return NULL;
  706: }
  707: 
  708: void prepare_super_table()
  709: {
  710:   int i;
  711:   int nsupers = 0;
  712: 
  713:   for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
  714:     struct cost *c = &super_costs[i];
  715:     if ((c->length < 2 || nsupers < static_super_number) &&
  716: 	c->state_in < maxstates && c->state_out < maxstates) {
  717:       struct super_state **ss_listp= lookup_super(super2+c->offset, c->length);
  718:       struct super_state *ss = malloc(sizeof(struct super_state));
  719:       ss->super= i;
  720:       if (c->offset==N_noop && i != N_noop) {
  721: 	if (is_relocatable(i)) {
  722: 	  ss->next = state_transitions;
  723: 	  state_transitions = ss;
  724: 	}
  725:       } else if (ss_listp != NULL) {
  726: 	ss->next = *ss_listp;
  727: 	*ss_listp = ss;
  728:       } else {
  729: 	int hash = hash_super(super2+c->offset, c->length);
  730: 	struct super_table_entry **p = &super_table[hash];
  731: 	struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
  732: 	ss->next = NULL;
  733: 	e->next = *p;
  734: 	e->start = super2 + c->offset;
  735: 	e->length = c->length;
  736: 	e->ss_list = ss;
  737: 	*p = e;
  738:       }
  739:       if (c->length > max_super)
  740: 	max_super = c->length;
  741:       if (c->length >= 2)
  742: 	nsupers++;
  743:     }
  744:   }
  745:   debugp(stderr, "Using %d static superinsts\n", nsupers);
  746: }
  747: 
  748: /* dynamic replication/superinstruction stuff */
  749: 
  750: #ifndef NO_DYNAMIC
  751: int compare_priminfo_length(const void *_a, const void *_b)
  752: {
  753:   PrimInfo **a = (PrimInfo **)_a;
  754:   PrimInfo **b = (PrimInfo **)_b;
  755:   Cell diff = (*a)->length - (*b)->length;
  756:   if (diff)
  757:     return diff;
  758:   else /* break ties by start address; thus the decompiler produces
  759:           the earliest primitive with the same code (e.g. noop instead
  760:           of (char) and @ instead of >code-address */
  761:     return (*b)->start - (*a)->start;
  762: }
  763: #endif /* !defined(NO_DYNAMIC) */
  764: 
  765: static char MAYBE_UNUSED superend[]={
  766: #include PRIM_SUPEREND_I
  767: };
  768: 
  769: Cell npriminfos=0;
  770: 
  771: Label goto_start;
  772: Cell goto_len;
  773: 
  774: int compare_labels(const void *pa, const void *pb)
  775: {
  776:   Label a = *(Label *)pa;
  777:   Label b = *(Label *)pb;
  778:   return a-b;
  779: }
  780: 
  781: Label bsearch_next(Label key, Label *a, UCell n)
  782:      /* a is sorted; return the label >=key that is the closest in a;
  783:         return NULL if there is no label in a >=key */
  784: {
  785:   int mid = (n-1)/2;
  786:   if (n<1)
  787:     return NULL;
  788:   if (n == 1) {
  789:     if (a[0] < key)
  790:       return NULL;
  791:     else
  792:       return a[0];
  793:   }
  794:   if (a[mid] < key)
  795:     return bsearch_next(key, a+mid+1, n-mid-1);
  796:   else
  797:     return bsearch_next(key, a, mid+1);
  798: }
  799: 
  800: void check_prims(Label symbols1[])
  801: {
  802:   int i;
  803: #ifndef NO_DYNAMIC
  804:   Label *symbols2, *symbols3, *ends1, *ends1j, *ends1jsorted, *goto_p;
  805:   int nends1j;
  806: #endif
  807: 
  808:   if (debug)
  809: #ifdef __VERSION__
  810:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
  811: #else
  812: #define xstr(s) str(s)
  813: #define str(s) #s
  814:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
  815: #endif
  816:   for (i=0; symbols1[i]!=0; i++)
  817:     ;
  818:   npriminfos = i;
  819:   
  820: #ifndef NO_DYNAMIC
  821:   if (no_dynamic)
  822:     return;
  823:   symbols2=engine2(0,0,0,0,0);
  824: #if NO_IP
  825:   symbols3=engine3(0,0,0,0,0);
  826: #else
  827:   symbols3=symbols1;
  828: #endif
  829:   ends1 = symbols1+i+1;
  830:   ends1j =   ends1+i;
  831:   goto_p = ends1j+i+1; /* goto_p[0]==before; ...[1]==after;*/
  832:   nends1j = i+1;
  833:   ends1jsorted = (Label *)alloca(nends1j*sizeof(Label));
  834:   memcpy(ends1jsorted,ends1j,nends1j*sizeof(Label));
  835:   qsort(ends1jsorted, nends1j, sizeof(Label), compare_labels);
  836: 
  837:   /* check whether the "goto *" is relocatable */
  838:   goto_len = goto_p[1]-goto_p[0];
  839:   debugp(stderr, "goto * %p %p len=%ld\n",
  840: 	 goto_p[0],symbols2[goto_p-symbols1],goto_len);
  841:   if (memcmp(goto_p[0],symbols2[goto_p-symbols1],goto_len)!=0) { /* unequal */
  842:     no_dynamic=1;
  843:     debugp(stderr,"  not relocatable, disabling dynamic code generation\n");
  844:     return;
  845:   }
  846:   goto_start = goto_p[0];
  847:   
  848:   priminfos = calloc(i,sizeof(PrimInfo));
  849:   for (i=0; symbols1[i]!=0; i++) {
  850:     int prim_len = ends1[i]-symbols1[i];
  851:     PrimInfo *pi=&priminfos[i];
  852:     int j=0;
  853:     char *s1 = (char *)symbols1[i];
  854:     char *s2 = (char *)symbols2[i];
  855:     char *s3 = (char *)symbols3[i];
  856:     Label endlabel = bsearch_next(symbols1[i]+1,ends1jsorted,nends1j);
  857: 
  858:     pi->start = s1;
  859:     pi->superend = superend[i]|no_super;
  860:     if (pi->superend)
  861:       pi->length = endlabel-symbols1[i];
  862:     else
  863:       pi->length = prim_len;
  864:     pi->restlength = endlabel - symbols1[i] - pi->length;
  865:     pi->nimmargs = 0;
  866:     relocs++;
  867:     debugp(stderr, "%-15s %3d %p %p %p len=%3ld restlen=%2ld s-end=%1d",
  868: 	      prim_names[i], i, s1, s2, s3, (long)(pi->length), (long)(pi->restlength), pi->superend);
  869:     if (endlabel == NULL) {
  870:       pi->start = NULL; /* not relocatable */
  871:       if (pi->length<0) pi->length=100;
  872:       debugp(stderr,"\n   non_reloc: no J label > start found\n");
  873:       relocs--;
  874:       nonrelocs++;
  875:       continue;
  876:     }
  877:     if (ends1[i] > endlabel && !pi->superend) {
  878:       pi->start = NULL; /* not relocatable */
  879:       pi->length = endlabel-symbols1[i];
  880:       debugp(stderr,"\n   non_reloc: there is a J label before the K label (restlength<0)\n");
  881:       relocs--;
  882:       nonrelocs++;
  883:       continue;
  884:     }
  885:     if (ends1[i] < pi->start && !pi->superend) {
  886:       pi->start = NULL; /* not relocatable */
  887:       pi->length = endlabel-symbols1[i];
  888:       debugp(stderr,"\n   non_reloc: K label before I label (length<0)\n");
  889:       relocs--;
  890:       nonrelocs++;
  891:       continue;
  892:     }
  893:     assert(pi->length>=0);
  894:     assert(pi->restlength >=0);
  895:     while (j<(pi->length+pi->restlength)) {
  896:       if (s1[j]==s3[j]) {
  897: 	if (s1[j] != s2[j]) {
  898: 	  pi->start = NULL; /* not relocatable */
  899: 	  debugp(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
  900: 	  /* assert(j<prim_len); */
  901: 	  relocs--;
  902: 	  nonrelocs++;
  903: 	  break;
  904: 	}
  905: 	j++;
  906:       } else {
  907: 	struct immarg *ia=&pi->immargs[pi->nimmargs];
  908: 
  909: 	pi->nimmargs++;
  910: 	ia->offset=j;
  911: 	if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
  912: 	  ia->rel=0;
  913: 	  debugp(stderr,"\n   absolute immarg: offset %3d",j);
  914: 	} else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
  915: 		   symbols1[DOESJUMP+1]) {
  916: 	  ia->rel=1;
  917: 	  debugp(stderr,"\n   relative immarg: offset %3d",j);
  918: 	} else {
  919: 	  pi->start = NULL; /* not relocatable */
  920: 	  debugp(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
  921: 	  /* assert(j<prim_len);*/
  922: 	  relocs--;
  923: 	  nonrelocs++;
  924: 	  break;
  925: 	}
  926: 	j+=4;
  927:       }
  928:     }
  929:     debugp(stderr,"\n");
  930:   }
  931:   decomp_prims = calloc(i,sizeof(PrimInfo *));
  932:   for (i=DOESJUMP+1; i<npriminfos; i++)
  933:     decomp_prims[i] = &(priminfos[i]);
  934:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
  935: 	compare_priminfo_length);
  936: #endif
  937: }
  938: 
  939: void flush_to_here(void)
  940: {
  941: #ifndef NO_DYNAMIC
  942:   if (start_flush)
  943:     FLUSH_ICACHE(start_flush, code_here-start_flush);
  944:   start_flush=code_here;
  945: #endif
  946: }
  947: 
  948: #ifndef NO_DYNAMIC
  949: void append_jump(void)
  950: {
  951:   if (last_jump) {
  952:     PrimInfo *pi = &priminfos[last_jump];
  953:     
  954:     memcpy(code_here, pi->start+pi->length, pi->restlength);
  955:     code_here += pi->restlength;
  956:     last_jump=0;
  957:   }
  958: }
  959: 
  960: /* Gforth remembers all code blocks in this list.  On forgetting (by
  961: executing a marker) the code blocks are not freed (because Gforth does
  962: not remember how they were allocated; hmm, remembering that might be
  963: easier and cleaner).  Instead, code_here etc. are reset to the old
  964: value, and the "forgotten" code blocks are reused when they are
  965: needed. */
  966: 
  967: struct code_block_list {
  968:   struct code_block_list *next;
  969:   Address block;
  970:   Cell size;
  971: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
  972: 
  973: Address append_prim(Cell p)
  974: {
  975:   PrimInfo *pi = &priminfos[p];
  976:   Address old_code_here = code_here;
  977: 
  978:   if (code_area+code_area_size < code_here+pi->length+pi->restlength) {
  979:     struct code_block_list *p;
  980:     append_jump();
  981:     flush_to_here();
  982:     if (*next_code_blockp == NULL) {
  983:       code_here = start_flush = code_area = my_alloc(code_area_size);
  984:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
  985:       *next_code_blockp = p;
  986:       p->next = NULL;
  987:       p->block = code_here;
  988:       p->size = code_area_size;
  989:     } else {
  990:       p = *next_code_blockp;
  991:       code_here = start_flush = code_area = p->block;
  992:     }
  993:     old_code_here = code_here;
  994:     next_code_blockp = &(p->next);
  995:   }
  996:   memcpy(code_here, pi->start, pi->length);
  997:   code_here += pi->length;
  998:   return old_code_here;
  999: }
 1000: #endif
 1001: 
 1002: int forget_dyncode(Address code)
 1003: {
 1004: #ifdef NO_DYNAMIC
 1005:   return -1;
 1006: #else
 1007:   struct code_block_list *p, **pp;
 1008: 
 1009:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
 1010:     if (code >= p->block && code < p->block+p->size) {
 1011:       next_code_blockp = &(p->next);
 1012:       code_here = start_flush = code;
 1013:       code_area = p->block;
 1014:       last_jump = 0;
 1015:       return -1;
 1016:     }
 1017:   }
 1018:   return -no_dynamic;
 1019: #endif /* !defined(NO_DYNAMIC) */
 1020: }
 1021: 
 1022: long dyncodesize(void)
 1023: {
 1024: #ifndef NO_DYNAMIC
 1025:   struct code_block_list *p;
 1026:   long size=0;
 1027:   for (p=code_block_list; p!=NULL; p=p->next) {
 1028:     if (code_here >= p->block && code_here < p->block+p->size)
 1029:       return size + (code_here - p->block);
 1030:     else
 1031:       size += p->size;
 1032:   }
 1033: #endif /* !defined(NO_DYNAMIC) */
 1034:   return 0;
 1035: }
 1036: 
 1037: Label decompile_code(Label _code)
 1038: {
 1039: #ifdef NO_DYNAMIC
 1040:   return _code;
 1041: #else /* !defined(NO_DYNAMIC) */
 1042:   Cell i;
 1043:   struct code_block_list *p;
 1044:   Address code=_code;
 1045: 
 1046:   /* first, check if we are in code at all */
 1047:   for (p = code_block_list;; p = p->next) {
 1048:     if (p == NULL)
 1049:       return code;
 1050:     if (code >= p->block && code < p->block+p->size)
 1051:       break;
 1052:   }
 1053:   /* reverse order because NOOP might match other prims */
 1054:   for (i=npriminfos-1; i>DOESJUMP; i--) {
 1055:     PrimInfo *pi=decomp_prims[i];
 1056:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
 1057:       return vm_prims[super2[super_costs[pi-priminfos].offset]];
 1058:     /* return pi->start;*/
 1059:   }
 1060:   return code;
 1061: #endif /* !defined(NO_DYNAMIC) */
 1062: }
 1063: 
 1064: #ifdef NO_IP
 1065: int nbranchinfos=0;
 1066: 
 1067: struct branchinfo {
 1068:   Label **targetpp; /* **(bi->targetpp) is the target */
 1069:   Cell *addressptr; /* store the target here */
 1070: } branchinfos[100000];
 1071: 
 1072: int ndoesexecinfos=0;
 1073: struct doesexecinfo {
 1074:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
 1075:   Label *targetp; /*target for branch (because this is not in threaded code)*/
 1076:   Cell *xt; /* cfa of word whose does-code needs calling */
 1077: } doesexecinfos[10000];
 1078: 
 1079: void set_rel_target(Cell *source, Label target)
 1080: {
 1081:   *source = ((Cell)target)-(((Cell)source)+4);
 1082: }
 1083: 
 1084: void register_branchinfo(Label source, Cell *targetpp)
 1085: {
 1086:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
 1087:   bi->targetpp = (Label **)targetpp;
 1088:   bi->addressptr = (Cell *)source;
 1089:   nbranchinfos++;
 1090: }
 1091: 
 1092: Address compile_prim1arg(PrimNum p, Cell **argp)
 1093: {
 1094:   Address old_code_here=append_prim(p);
 1095: 
 1096:   assert(vm_prims[p]==priminfos[p].start);
 1097:   *argp = (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
 1098:   return old_code_here;
 1099: }
 1100: 
 1101: Address compile_call2(Cell *targetpp, Cell **next_code_targetp)
 1102: {
 1103:   PrimInfo *pi = &priminfos[N_call2];
 1104:   Address old_code_here = append_prim(N_call2);
 1105: 
 1106:   *next_code_targetp = (Cell *)(old_code_here + pi->immargs[0].offset);
 1107:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetpp);
 1108:   return old_code_here;
 1109: }
 1110: #endif
 1111: 
 1112: void finish_code(void)
 1113: {
 1114: #ifdef NO_IP
 1115:   Cell i;
 1116: 
 1117:   compile_prim1(NULL);
 1118:   for (i=0; i<ndoesexecinfos; i++) {
 1119:     struct doesexecinfo *dei = &doesexecinfos[i];
 1120:     dei->targetp = (Label *)DOES_CODE1((dei->xt));
 1121:     branchinfos[dei->branchinfo].targetpp = &(dei->targetp);
 1122:   }
 1123:   ndoesexecinfos = 0;
 1124:   for (i=0; i<nbranchinfos; i++) {
 1125:     struct branchinfo *bi=&branchinfos[i];
 1126:     set_rel_target(bi->addressptr, **(bi->targetpp));
 1127:   }
 1128:   nbranchinfos = 0;
 1129: #else
 1130:   compile_prim1(NULL);
 1131: #endif
 1132:   flush_to_here();
 1133: }
 1134: 
 1135: #ifdef NO_IP
 1136: Cell compile_prim_dyn(PrimNum p, Cell *tcp)
 1137:      /* compile prim #p dynamically (mod flags etc.) and return start
 1138: 	address of generated code for putting it into the threaded
 1139: 	code. This function is only called if all the associated
 1140: 	inline arguments of p are already in place (at tcp[1] etc.) */
 1141: {
 1142:   PrimInfo *pi=&priminfos[p];
 1143:   Cell *next_code_target=NULL;
 1144:   Address codeaddr;
 1145:   Address primstart;
 1146:   
 1147:   assert(p<npriminfos);
 1148:   if (p==N_execute || p==N_perform || p==N_lit_perform) {
 1149:     codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
 1150:     primstart = append_prim(p);
 1151:     goto other_prim;
 1152:   } else if (p==N_call) {
 1153:     codeaddr = compile_call2(tcp+1, &next_code_target);
 1154:   } else if (p==N_does_exec) {
 1155:     struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
 1156:     Cell *arg;
 1157:     codeaddr = compile_prim1arg(N_lit,&arg);
 1158:     *arg = (Cell)PFA(tcp[1]);
 1159:     /* we cannot determine the callee now (last_start[1] may be a
 1160:        forward reference), so just register an arbitrary target, and
 1161:        register in dei that we need to fix this before resolving
 1162:        branches */
 1163:     dei->branchinfo = nbranchinfos;
 1164:     dei->xt = (Cell *)(tcp[1]);
 1165:     compile_call2(0, &next_code_target);
 1166:   } else if (!is_relocatable(p)) {
 1167:     Cell *branch_target;
 1168:     codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
 1169:     compile_prim1arg(N_branch,&branch_target);
 1170:     set_rel_target(branch_target,vm_prims[p]);
 1171:   } else {
 1172:     unsigned j;
 1173: 
 1174:     codeaddr = primstart = append_prim(p);
 1175:   other_prim:
 1176:     for (j=0; j<pi->nimmargs; j++) {
 1177:       struct immarg *ia = &(pi->immargs[j]);
 1178:       Cell *argp = tcp + pi->nimmargs - j;
 1179:       Cell argval = *argp; /* !! specific to prims */
 1180:       if (ia->rel) { /* !! assumption: relative refs are branches */
 1181: 	register_branchinfo(primstart + ia->offset, argp);
 1182:       } else /* plain argument */
 1183: 	*(Cell *)(primstart + ia->offset) = argval;
 1184:     }
 1185:   }
 1186:   if (next_code_target!=NULL)
 1187:     *next_code_target = (Cell)code_here;
 1188:   return (Cell)codeaddr;
 1189: }
 1190: #else /* !defined(NO_IP) */
 1191: Cell compile_prim_dyn(PrimNum p, Cell *tcp)
 1192:      /* compile prim #p dynamically (mod flags etc.) and return start
 1193:         address of generated code for putting it into the threaded code */
 1194: {
 1195:   Cell static_prim = (Cell)vm_prims[p];
 1196: #if defined(NO_DYNAMIC)
 1197:   return static_prim;
 1198: #else /* !defined(NO_DYNAMIC) */
 1199:   Address old_code_here;
 1200: 
 1201:   if (no_dynamic)
 1202:     return static_prim;
 1203:   if (p>=npriminfos || !is_relocatable(p)) {
 1204:     append_jump();
 1205:     return static_prim;
 1206:   }
 1207:   old_code_here = append_prim(p);
 1208:   last_jump = (priminfos[p].superend) ? 0 : p;
 1209:   return (Cell)old_code_here;
 1210: #endif  /* !defined(NO_DYNAMIC) */
 1211: }
 1212: #endif /* !defined(NO_IP) */
 1213: 
 1214: #ifndef NO_DYNAMIC
 1215: int cost_codesize(int prim)
 1216: {
 1217:   return priminfos[prim].length;
 1218: }
 1219: #endif
 1220: 
 1221: int cost_ls(int prim)
 1222: {
 1223:   struct cost *c = super_costs+prim;
 1224: 
 1225:   return c->loads + c->stores;
 1226: }
 1227: 
 1228: int cost_lsu(int prim)
 1229: {
 1230:   struct cost *c = super_costs+prim;
 1231: 
 1232:   return c->loads + c->stores + c->updates;
 1233: }
 1234: 
 1235: int cost_nexts(int prim)
 1236: {
 1237:   return 1;
 1238: }
 1239: 
 1240: typedef int Costfunc(int);
 1241: Costfunc *ss_cost =  /* cost function for optimize_bb */
 1242: #ifdef NO_DYNAMIC
 1243: cost_lsu;
 1244: #else
 1245: cost_codesize;
 1246: #endif
 1247: 
 1248: struct {
 1249:   Costfunc *costfunc;
 1250:   char *metricname;
 1251:   long sum;
 1252: } cost_sums[] = {
 1253: #ifndef NO_DYNAMIC
 1254:   { cost_codesize, "codesize", 0 },
 1255: #endif
 1256:   { cost_ls,       "ls",       0 },
 1257:   { cost_lsu,      "lsu",      0 },
 1258:   { cost_nexts,    "nexts",    0 }
 1259: };
 1260: 
 1261: #define MAX_BB 128 /* maximum number of instructions in BB */
 1262: #define INF_COST 1000000 /* infinite cost */
 1263: #define CANONICAL_STATE 0
 1264: 
 1265: struct waypoint {
 1266:   int cost;     /* the cost from here to the end */
 1267:   PrimNum inst; /* the inst used from here to the next waypoint */
 1268:   char relocatable; /* the last non-transition was relocatable */
 1269:   char no_transition; /* don't use the next transition (relocatability)
 1270: 		       * or this transition (does not change state) */
 1271: };
 1272: 
 1273: void init_waypoints(struct waypoint ws[])
 1274: {
 1275:   int k;
 1276: 
 1277:   for (k=0; k<maxstates; k++)
 1278:     ws[k].cost=INF_COST;
 1279: }
 1280: 
 1281: void transitions(struct waypoint inst[], struct waypoint trans[])
 1282: {
 1283:   int k;
 1284:   struct super_state *l;
 1285:   
 1286:   for (k=0; k<maxstates; k++) {
 1287:     trans[k] = inst[k];
 1288:     trans[k].no_transition = 1;
 1289:   }
 1290:   for (l = state_transitions; l != NULL; l = l->next) {
 1291:     PrimNum s = l->super;
 1292:     int jcost;
 1293:     struct cost *c=super_costs+s;
 1294:     struct waypoint *wi=&(trans[c->state_in]);
 1295:     struct waypoint *wo=&(inst[c->state_out]);
 1296:     if (wo->cost == INF_COST)
 1297:       continue;
 1298:     jcost = wo->cost + ss_cost(s);
 1299:     if (jcost <= wi->cost) {
 1300:       wi->cost = jcost;
 1301:       wi->inst = s;
 1302:       wi->relocatable = wo->relocatable;
 1303:       wi->no_transition = 0;
 1304:       /* if (ss_greedy) wi->cost = wo->cost ? */
 1305:     }
 1306:   }
 1307: }
 1308: 
 1309: /* use dynamic programming to find the shortest paths within the basic
 1310:    block origs[0..ninsts-1] and rewrite the instructions pointed to by
 1311:    instps to use it */
 1312: void optimize_rewrite(Cell *instps[], PrimNum origs[], int ninsts)
 1313: {
 1314:   int i,j;
 1315:   static struct waypoint inst[MAX_BB+1][MAX_STATE];  /* before instruction*/
 1316:   static struct waypoint trans[MAX_BB+1][MAX_STATE]; /* before transition */
 1317:   int nextdyn, nextstate, no_transition;
 1318:   
 1319:   init_waypoints(inst[ninsts]);
 1320:   inst[ninsts][CANONICAL_STATE].cost=0;
 1321:   transitions(inst[ninsts],trans[ninsts]);
 1322:   for (i=ninsts-1; i>=0; i--) {
 1323:     init_waypoints(inst[i]);
 1324:     for (j=1; j<=max_super && i+j<=ninsts; j++) {
 1325:       struct super_state **superp = lookup_super(origs+i, j);
 1326:       if (superp!=NULL) {
 1327: 	struct super_state *supers = *superp;
 1328: 	for (; supers!=NULL; supers = supers->next) {
 1329: 	  PrimNum s = supers->super;
 1330: 	  int jcost;
 1331: 	  struct cost *c=super_costs+s;
 1332: 	  struct waypoint *wi=&(inst[i][c->state_in]);
 1333: 	  struct waypoint *wo=&(trans[i+j][c->state_out]);
 1334: 	  int no_transition = wo->no_transition;
 1335: 	  if (!(is_relocatable(s)) && !wo->relocatable) {
 1336: 	    wo=&(inst[i+j][c->state_out]);
 1337: 	    no_transition=1;
 1338: 	  }
 1339: 	  if (wo->cost == INF_COST) 
 1340: 	    continue;
 1341: 	  jcost = wo->cost + ss_cost(s);
 1342: 	  if (jcost <= wi->cost) {
 1343: 	    wi->cost = jcost;
 1344: 	    wi->inst = s;
 1345: 	    wi->relocatable = is_relocatable(s);
 1346: 	    wi->no_transition = no_transition;
 1347: 	    /* if (ss_greedy) wi->cost = wo->cost ? */
 1348: 	  }
 1349: 	}
 1350:       }
 1351:     }
 1352:     transitions(inst[i],trans[i]);
 1353:   }
 1354:   /* now rewrite the instructions */
 1355:   nextdyn=0;
 1356:   nextstate=CANONICAL_STATE;
 1357:   no_transition = ((!trans[0][nextstate].relocatable) 
 1358: 		   ||trans[0][nextstate].no_transition);
 1359:   for (i=0; i<ninsts; i++) {
 1360:     Cell tc=0, tc2;
 1361:     if (i==nextdyn) {
 1362:       if (!no_transition) {
 1363: 	/* process trans */
 1364: 	PrimNum p = trans[i][nextstate].inst;
 1365: 	struct cost *c = super_costs+p;
 1366: 	assert(trans[i][nextstate].cost != INF_COST);
 1367: 	assert(c->state_in==nextstate);
 1368: 	tc = compile_prim_dyn(p,NULL);
 1369: 	nextstate = c->state_out;
 1370:       }
 1371:       {
 1372: 	/* process inst */
 1373: 	PrimNum p = inst[i][nextstate].inst;
 1374: 	struct cost *c=super_costs+p;
 1375: 	assert(c->state_in==nextstate);
 1376: 	assert(inst[i][nextstate].cost != INF_COST);
 1377: #if defined(GFORTH_DEBUGGING)
 1378: 	assert(p == origs[i]);
 1379: #endif
 1380: 	tc2 = compile_prim_dyn(p,instps[i]);
 1381: 	if (no_transition || !is_relocatable(p))
 1382: 	  /* !! actually what we care about is if and where
 1383: 	   * compile_prim_dyn() puts NEXTs */
 1384: 	  tc=tc2;
 1385: 	no_transition = inst[i][nextstate].no_transition;
 1386: 	nextstate = c->state_out;
 1387: 	nextdyn += c->length;
 1388:       }
 1389:     } else {
 1390: #if defined(GFORTH_DEBUGGING)
 1391:       assert(0);
 1392: #endif
 1393:       tc=0;
 1394:       /* tc= (Cell)vm_prims[inst[i][CANONICAL_STATE].inst]; */
 1395:     }
 1396:     *(instps[i]) = tc;
 1397:   }      
 1398:   if (!no_transition) {
 1399:     PrimNum p = trans[i][nextstate].inst;
 1400:     struct cost *c = super_costs+p;
 1401:     assert(c->state_in==nextstate);
 1402:     assert(trans[i][nextstate].cost != INF_COST);
 1403:     assert(i==nextdyn);
 1404:     (void)compile_prim_dyn(p,NULL);
 1405:     nextstate = c->state_out;
 1406:   }
 1407:   assert(nextstate==CANONICAL_STATE);
 1408: }
 1409: 
 1410: /* compile *start, possibly rewriting it into a static and/or dynamic
 1411:    superinstruction */
 1412: void compile_prim1(Cell *start)
 1413: {
 1414: #if defined(DOUBLY_INDIRECT)
 1415:   Label prim;
 1416: 
 1417:   if (start==NULL)
 1418:     return;
 1419:   prim = (Label)*start;
 1420:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
 1421:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
 1422:     *start=(Cell)prim;
 1423:     return;
 1424:   } else {
 1425:     *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
 1426:     return;
 1427:   }
 1428: #elif defined(INDIRECT_THREADED)
 1429:   return;
 1430: #else /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
 1431:   /* !! does not work, for unknown reasons; but something like this is
 1432:      probably needed to ensure that we don't call compile_prim_dyn
 1433:      before the inline arguments are there */
 1434:   static Cell *instps[MAX_BB];
 1435:   static PrimNum origs[MAX_BB];
 1436:   static int ninsts=0;
 1437:   PrimNum prim_num;
 1438: 
 1439:   if (start==NULL || ninsts >= MAX_BB ||
 1440:       (ninsts>0 && superend[origs[ninsts-1]])) {
 1441:     /* after bb, or at the start of the next bb */
 1442:     optimize_rewrite(instps,origs,ninsts);
 1443:     /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts); */
 1444:     ninsts=0;
 1445:     if (start==NULL)
 1446:       return;
 1447:   }
 1448:   prim_num = ((Xt)*start)-vm_prims;
 1449:   if(prim_num >= npriminfos) {
 1450:     optimize_rewrite(instps,origs,ninsts);
 1451:     /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts);*/
 1452:     ninsts=0;
 1453:     return;
 1454:   }    
 1455:   assert(ninsts<MAX_BB);
 1456:   instps[ninsts] = start;
 1457:   origs[ninsts] = prim_num;
 1458:   ninsts++;
 1459: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
 1460: }
 1461: 
 1462: Address loader(FILE *imagefile, char* filename)
 1463: /* returns the address of the image proper (after the preamble) */
 1464: {
 1465:   ImageHeader header;
 1466:   Address image;
 1467:   Address imp; /* image+preamble */
 1468:   Char magic[8];
 1469:   char magic7; /* size byte of magic number */
 1470:   Cell preamblesize=0;
 1471:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
 1472:   UCell check_sum;
 1473:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
 1474: 		 (RELINFOBITS == 16) ? 1 :
 1475: 		 (RELINFOBITS == 32) ? 2 : 3);
 1476:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
 1477: 		   (sizeof(Char) == 2) ? 1 :
 1478: 		   (sizeof(Char) == 4) ? 2 : 3) + ausize;
 1479:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
 1480: 		   (sizeof(Cell) == 2) ? 1 :
 1481: 		   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
 1482:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
 1483: #ifdef WORDS_BIGENDIAN
 1484:        0
 1485: #else
 1486:        1
 1487: #endif
 1488:     ;
 1489: 
 1490:   vm_prims = engine(0,0,0,0,0);
 1491:   check_prims(vm_prims);
 1492:   prepare_super_table();
 1493: #ifndef DOUBLY_INDIRECT
 1494: #ifdef PRINT_SUPER_LENGTHS
 1495:   print_super_lengths();
 1496: #endif
 1497:   check_sum = checksum(vm_prims);
 1498: #else /* defined(DOUBLY_INDIRECT) */
 1499:   check_sum = (UCell)vm_prims;
 1500: #endif /* defined(DOUBLY_INDIRECT) */
 1501:   
 1502:   do {
 1503:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
 1504:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
 1505: 	      progname, filename);
 1506:       exit(1);
 1507:     }
 1508:     preamblesize+=8;
 1509:   } while(memcmp(magic,"Gforth3",7));
 1510:   magic7 = magic[7];
 1511:   if (debug) {
 1512:     magic[7]='\0';
 1513:     fprintf(stderr,"Magic found: %s ", magic);
 1514:     print_sizes(magic7);
 1515:   }
 1516: 
 1517:   if (magic7 != sizebyte)
 1518:     {
 1519:       fprintf(stderr,"This image is:         ");
 1520:       print_sizes(magic7);
 1521:       fprintf(stderr,"whereas the machine is ");
 1522:       print_sizes(sizebyte);
 1523:       exit(-2);
 1524:     };
 1525: 
 1526:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
 1527: 
 1528:   set_stack_sizes(&header);
 1529:   
 1530: #if HAVE_GETPAGESIZE
 1531:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
 1532: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
 1533:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
 1534: #elif PAGESIZE
 1535:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
 1536: #endif
 1537:   debugp(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
 1538: 
 1539:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
 1540: 			  preamblesize+dictsize, data_offset);
 1541:   imp=image+preamblesize;
 1542:   alloc_stacks((ImageHeader *)imp);
 1543:   if (clear_dictionary)
 1544:     memset(imp+header.image_size, 0, dictsize-header.image_size);
 1545:   if(header.base==0 || header.base  == (Address)0x100) {
 1546:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
 1547:     char reloc_bits[reloc_size];
 1548:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
 1549:     fread(reloc_bits, 1, reloc_size, imagefile);
 1550:     relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
 1551: #if 0
 1552:     { /* let's see what the relocator did */
 1553:       FILE *snapshot=fopen("snapshot.fi","wb");
 1554:       fwrite(image,1,imagesize,snapshot);
 1555:       fclose(snapshot);
 1556:     }
 1557: #endif
 1558:   }
 1559:   else if(header.base!=imp) {
 1560:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
 1561: 	    progname, (unsigned long)header.base, (unsigned long)imp);
 1562:     exit(1);
 1563:   }
 1564:   if (header.checksum==0)
 1565:     ((ImageHeader *)imp)->checksum=check_sum;
 1566:   else if (header.checksum != check_sum) {
 1567:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
 1568: 	    progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
 1569:     exit(1);
 1570:   }
 1571: #ifdef DOUBLY_INDIRECT
 1572:   ((ImageHeader *)imp)->xt_base = xts;
 1573: #endif
 1574:   fclose(imagefile);
 1575: 
 1576:   /* unnecessary, except maybe for CODE words */
 1577:   /* FLUSH_ICACHE(imp, header.image_size);*/
 1578: 
 1579:   return imp;
 1580: }
 1581: 
 1582: /* pointer to last '/' or '\' in file, 0 if there is none. */
 1583: char *onlypath(char *filename)
 1584: {
 1585:   return strrchr(filename, DIRSEP);
 1586: }
 1587: 
 1588: FILE *openimage(char *fullfilename)
 1589: {
 1590:   FILE *image_file;
 1591:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
 1592: 
 1593:   image_file=fopen(expfilename,"rb");
 1594:   if (image_file!=NULL && debug)
 1595:     fprintf(stderr, "Opened image file: %s\n", expfilename);
 1596:   return image_file;
 1597: }
 1598: 
 1599: /* try to open image file concat(path[0:len],imagename) */
 1600: FILE *checkimage(char *path, int len, char *imagename)
 1601: {
 1602:   int dirlen=len;
 1603:   char fullfilename[dirlen+strlen(imagename)+2];
 1604: 
 1605:   memcpy(fullfilename, path, dirlen);
 1606:   if (fullfilename[dirlen-1]!=DIRSEP)
 1607:     fullfilename[dirlen++]=DIRSEP;
 1608:   strcpy(fullfilename+dirlen,imagename);
 1609:   return openimage(fullfilename);
 1610: }
 1611: 
 1612: FILE * open_image_file(char * imagename, char * path)
 1613: {
 1614:   FILE * image_file=NULL;
 1615:   char *origpath=path;
 1616:   
 1617:   if(strchr(imagename, DIRSEP)==NULL) {
 1618:     /* first check the directory where the exe file is in !! 01may97jaw */
 1619:     if (onlypath(progname))
 1620:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
 1621:     if (!image_file)
 1622:       do {
 1623: 	char *pend=strchr(path, PATHSEP);
 1624: 	if (pend==NULL)
 1625: 	  pend=path+strlen(path);
 1626: 	if (strlen(path)==0) break;
 1627: 	image_file=checkimage(path, pend-path, imagename);
 1628: 	path=pend+(*pend==PATHSEP);
 1629:       } while (image_file==NULL);
 1630:   } else {
 1631:     image_file=openimage(imagename);
 1632:   }
 1633: 
 1634:   if (!image_file) {
 1635:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
 1636: 	    progname, imagename, origpath);
 1637:     exit(1);
 1638:   }
 1639: 
 1640:   return image_file;
 1641: }
 1642: #endif
 1643: 
 1644: #ifdef HAS_OS
 1645: UCell convsize(char *s, UCell elemsize)
 1646: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
 1647:    of bytes.  the letter at the end indicates the unit, where e stands
 1648:    for the element size. default is e */
 1649: {
 1650:   char *endp;
 1651:   UCell n,m;
 1652: 
 1653:   m = elemsize;
 1654:   n = strtoul(s,&endp,0);
 1655:   if (endp!=NULL) {
 1656:     if (strcmp(endp,"b")==0)
 1657:       m=1;
 1658:     else if (strcmp(endp,"k")==0)
 1659:       m=1024;
 1660:     else if (strcmp(endp,"M")==0)
 1661:       m=1024*1024;
 1662:     else if (strcmp(endp,"G")==0)
 1663:       m=1024*1024*1024;
 1664:     else if (strcmp(endp,"T")==0) {
 1665: #if (SIZEOF_CHAR_P > 4)
 1666:       m=1024L*1024*1024*1024;
 1667: #else
 1668:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
 1669:       exit(1);
 1670: #endif
 1671:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
 1672:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
 1673:       exit(1);
 1674:     }
 1675:   }
 1676:   return n*m;
 1677: }
 1678: 
 1679: enum {
 1680:   ss_number = 256,
 1681:   ss_states,
 1682:   ss_min_codesize,
 1683:   ss_min_ls,
 1684:   ss_min_lsu,
 1685:   ss_min_nexts,
 1686: };
 1687: 
 1688: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
 1689: {
 1690:   int c;
 1691: 
 1692:   opterr=0;
 1693:   while (1) {
 1694:     int option_index=0;
 1695:     static struct option opts[] = {
 1696:       {"appl-image", required_argument, NULL, 'a'},
 1697:       {"image-file", required_argument, NULL, 'i'},
 1698:       {"dictionary-size", required_argument, NULL, 'm'},
 1699:       {"data-stack-size", required_argument, NULL, 'd'},
 1700:       {"return-stack-size", required_argument, NULL, 'r'},
 1701:       {"fp-stack-size", required_argument, NULL, 'f'},
 1702:       {"locals-stack-size", required_argument, NULL, 'l'},
 1703:       {"path", required_argument, NULL, 'p'},
 1704:       {"version", no_argument, NULL, 'v'},
 1705:       {"help", no_argument, NULL, 'h'},
 1706:       /* put something != 0 into offset_image */
 1707:       {"offset-image", no_argument, &offset_image, 1},
 1708:       {"no-offset-im", no_argument, &offset_image, 0},
 1709:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
 1710:       {"die-on-signal", no_argument, &die_on_signal, 1},
 1711:       {"debug", no_argument, &debug, 1},
 1712:       {"diag", no_argument, &diag, 1},
 1713:       {"no-super", no_argument, &no_super, 1},
 1714:       {"no-dynamic", no_argument, &no_dynamic, 1},
 1715:       {"dynamic", no_argument, &no_dynamic, 0},
 1716:       {"print-metrics", no_argument, &print_metrics, 1},
 1717:       {"ss-number", required_argument, NULL, ss_number},
 1718:       {"ss-states", required_argument, NULL, ss_states},
 1719: #ifndef NO_DYNAMIC
 1720:       {"ss-min-codesize", no_argument, NULL, ss_min_codesize},
 1721: #endif
 1722:       {"ss-min-ls",       no_argument, NULL, ss_min_ls},
 1723:       {"ss-min-lsu",      no_argument, NULL, ss_min_lsu},
 1724:       {"ss-min-nexts",    no_argument, NULL, ss_min_nexts},
 1725:       {"ss-greedy",       no_argument, &ss_greedy, 1},
 1726:       {0,0,0,0}
 1727:       /* no-init-file, no-rc? */
 1728:     };
 1729:     
 1730:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
 1731:     
 1732:     switch (c) {
 1733:     case EOF: return;
 1734:     case '?': optind--; return;
 1735:     case 'a': *imagename = optarg; return;
 1736:     case 'i': *imagename = optarg; break;
 1737:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
 1738:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
 1739:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
 1740:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
 1741:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
 1742:     case 'p': *path = optarg; break;
 1743:     case 'o': offset_image = 1; break;
 1744:     case 'n': offset_image = 0; break;
 1745:     case 'c': clear_dictionary = 1; break;
 1746:     case 's': die_on_signal = 1; break;
 1747:     case 'x': debug = 1; break;
 1748:     case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
 1749:     case ss_number: static_super_number = atoi(optarg); break;
 1750:     case ss_states: maxstates = max(min(atoi(optarg),MAX_STATE),1); break;
 1751: #ifndef NO_DYNAMIC
 1752:     case ss_min_codesize: ss_cost = cost_codesize; break;
 1753: #endif
 1754:     case ss_min_ls:       ss_cost = cost_ls;       break;
 1755:     case ss_min_lsu:      ss_cost = cost_lsu;      break;
 1756:     case ss_min_nexts:    ss_cost = cost_nexts;    break;
 1757:     case 'h': 
 1758:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
 1759: Engine Options:\n\
 1760:   --appl-image FILE		    equivalent to '--image-file=FILE --'\n\
 1761:   --clear-dictionary		    Initialize the dictionary with 0 bytes\n\
 1762:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
 1763:   --debug			    Print debugging information during startup\n\
 1764:   --diag			    Print diagnostic information during startup\n\
 1765:   --die-on-signal		    exit instead of CATCHing some signals\n\
 1766:   --dynamic			    use dynamic native code\n\
 1767:   -f SIZE, --fp-stack-size=SIZE	    Specify floating point stack size\n\
 1768:   -h, --help			    Print this message and exit\n\
 1769:   -i FILE, --image-file=FILE	    Use image FILE instead of `gforth.fi'\n\
 1770:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
 1771:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
 1772:   --no-dynamic			    Use only statically compiled primitives\n\
 1773:   --no-offset-im		    Load image at normal position\n\
 1774:   --no-super                        No dynamically formed superinstructions\n\
 1775:   --offset-image		    Load image at a different position\n\
 1776:   -p PATH, --path=PATH		    Search path for finding image and sources\n\
 1777:   --print-metrics		    Print some code generation metrics on exit\n\
 1778:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
 1779:   --ss-greedy                       greedy, not optimal superinst selection\n\
 1780:   --ss-min-codesize                 select superinsts for smallest native code\n\
 1781:   --ss-min-ls                       minimize loads and stores\n\
 1782:   --ss-min-lsu                      minimize loads, stores, and pointer updates\n\
 1783:   --ss-min-nexts                    minimize the number of static superinsts\n\
 1784:   --ss-number=N                     use N static superinsts (default max)\n\
 1785:   --ss-states=N                     N states for stack caching (default max)\n\
 1786:   -v, --version			    Print engine version and exit\n\
 1787: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
 1788:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
 1789: 	      argv[0]);
 1790:       optind--;
 1791:       return;
 1792:     }
 1793:   }
 1794: }
 1795: #endif
 1796: 
 1797: void print_diag()
 1798: {
 1799: 
 1800: #if !defined(HAVE_GETRUSAGE) || !defined(HAS_FFCALL)
 1801:   fprintf(stderr, "*** missing functionality ***\n"
 1802: #ifndef HAVE_GETRUSAGE
 1803: 	  "    no getrusage -> CPUTIME broken\n"
 1804: #endif
 1805: #ifndef HAS_FFCALL
 1806: 	  "    no ffcall -> only old-style foreign function calls (no fflib.fs)\n"
 1807: #endif
 1808: 	  );
 1809: #endif
 1810:   if((relocs < nonrelocs) ||
 1811: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
 1812:      1
 1813: #else
 1814:      0
 1815: #endif
 1816:      )
 1817:     debugp(stderr, "relocs: %d:%d\n", relocs, nonrelocs);
 1818:     fprintf(stderr, "*** performance problems ***\n%s"
 1819: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
 1820: 	    "    double-cell integer type buggy ->\n        "
 1821: #ifdef BUGGY_LL_CMP
 1822: 	    "CMP, "
 1823: #endif
 1824: #ifdef BUGGY_LL_MUL
 1825: 	    "MUL, "
 1826: #endif
 1827: #ifdef BUGGY_LL_DIV
 1828: 	    "DIV, "
 1829: #endif
 1830: #ifdef BUGGY_LL_ADD
 1831: 	    "ADD, "
 1832: #endif
 1833: #ifdef BUGGY_LL_SHIFT
 1834: 	    "SHIFT, "
 1835: #endif
 1836: #ifdef BUGGY_LL_D2F
 1837: 	    "D2F, "
 1838: #endif
 1839: #ifdef BUGGY_LL_F2D
 1840: 	    "F2D, "
 1841: #endif
 1842: 	    "\b\b slow\n"
 1843: #endif
 1844: #ifndef FORCE_REG
 1845: 	    "    automatic register allocation: performance degradation possible\n"
 1846: #endif
 1847: #if !defined(FORCE_REG) || defined(BUGGY_LONG_LONG)
 1848: 	    "*** Suggested remedy: try ./configure"
 1849: #ifndef FORCE_REG
 1850: 	    " --enable-force-reg"
 1851: #endif
 1852: #ifdef BUGGY_LONG_LONG
 1853: 	    " --enable-force-ll"
 1854: #endif
 1855: 	    "\n"
 1856: #endif
 1857: 	    ,
 1858: 	    (relocs < nonrelocs) ? "    gcc PR 15242 -> no dynamic code generation (use gcc-2.95 instead)\n" : "");
 1859: }
 1860: 
 1861: #ifdef INCLUDE_IMAGE
 1862: extern Cell image[];
 1863: extern const char reloc_bits[];
 1864: #endif
 1865: 
 1866: int main(int argc, char **argv, char **env)
 1867: {
 1868: #ifdef HAS_OS
 1869:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
 1870: #else
 1871:   char *path = DEFAULTPATH;
 1872: #endif
 1873: #ifndef INCLUDE_IMAGE
 1874:   char *imagename="gforth.fi";
 1875:   FILE *image_file;
 1876:   Address image;
 1877: #endif
 1878:   int retvalue;
 1879: 	  
 1880: #if defined(i386) && defined(ALIGNMENT_CHECK)
 1881:   /* turn on alignment checks on the 486.
 1882:    * on the 386 this should have no effect. */
 1883:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
 1884:   /* this is unusable with Linux' libc.4.6.27, because this library is
 1885:      not alignment-clean; we would have to replace some library
 1886:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
 1887:      the stack FP-aligned. */
 1888: #endif
 1889: 
 1890:   /* buffering of the user output device */
 1891: #ifdef _IONBF
 1892:   if (isatty(fileno(stdout))) {
 1893:     fflush(stdout);
 1894:     setvbuf(stdout,NULL,_IONBF,0);
 1895:   }
 1896: #endif
 1897: 
 1898:   progname = argv[0];
 1899: 
 1900: #ifdef HAS_OS
 1901:   gforth_args(argc, argv, &path, &imagename);
 1902: #ifndef NO_DYNAMIC
 1903:   if (no_dynamic && ss_cost == cost_codesize) {
 1904:     ss_cost = cost_nexts;
 1905:     cost_sums[0] = cost_sums[1]; /* don't use cost_codesize for print-metrics */
 1906:     debugp(stderr, "--no-dynamic conflicts with --ss-min-codesize, reverting to --ss-min-nexts\n");
 1907:   }
 1908: #endif /* !defined(NO_DYNAMIC) */
 1909: #endif /* defined(HAS_OS) */
 1910: 
 1911: #ifdef INCLUDE_IMAGE
 1912:   set_stack_sizes((ImageHeader *)image);
 1913:   if(((ImageHeader *)image)->base != image)
 1914:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
 1915: 	     (Label*)engine(0, 0, 0, 0, 0));
 1916:   alloc_stacks((ImageHeader *)image);
 1917: #else
 1918:   image_file = open_image_file(imagename, path);
 1919:   image = loader(image_file, imagename);
 1920: #endif
 1921:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
 1922: 
 1923:   if (diag)
 1924:     print_diag();
 1925:   {
 1926:     char path2[strlen(path)+1];
 1927:     char *p1, *p2;
 1928:     Cell environ[]= {
 1929:       (Cell)argc-(optind-1),
 1930:       (Cell)(argv+(optind-1)),
 1931:       (Cell)strlen(path),
 1932:       (Cell)path2};
 1933:     argv[optind-1] = progname;
 1934:     /*
 1935:        for (i=0; i<environ[0]; i++)
 1936:        printf("%s\n", ((char **)(environ[1]))[i]);
 1937:        */
 1938:     /* make path OS-independent by replacing path separators with NUL */
 1939:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
 1940:       if (*p1==PATHSEP)
 1941: 	*p2 = '\0';
 1942:       else
 1943: 	*p2 = *p1;
 1944:     *p2='\0';
 1945:     retvalue = go_forth(image, 4, environ);
 1946: #ifdef SIGPIPE
 1947:     bsd_signal(SIGPIPE, SIG_IGN);
 1948: #endif
 1949: #ifdef VM_PROFILING
 1950:     vm_print_profile(stderr);
 1951: #endif
 1952:     deprep_terminal();
 1953:   }
 1954:   if (print_metrics) {
 1955:     int i;
 1956:     fprintf(stderr, "code size = %8ld\n", dyncodesize());
 1957:     for (i=0; i<sizeof(cost_sums)/sizeof(cost_sums[0]); i++)
 1958:       fprintf(stderr, "metric %8s: %8ld\n",
 1959: 	      cost_sums[i].metricname, cost_sums[i].sum);
 1960:   }
 1961:   return retvalue;
 1962: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>