File:  [gforth] / gforth / engine / main.c
Revision 1.184: download - view: text, annotated - select for diffs
Sat Jun 30 20:28:55 2007 UTC (16 years, 9 months ago) by anton
Branches: MAIN
CVS tags: HEAD
fixed minor bug in -falign-* configure tests
cleaned up dependencies on .h files in engine/Makefile.in
made Alpha port compile with gcc-2.95 (disabled longlong.h division)
optimized Alpha port:
  use old division code
  native code after a jump is now aligned.  Speed effect:
   sieve bubble matrix  fib
    1.950 1.605  1.259 1.653 b1 gcc-3.3.5
    1.453 1.932  1.230 1.458 b1 gcc-3.3.5 with alignment
  aligning branch targets would probably also help

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

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