File:  [gforth] / gforth / engine / main.c
Revision 1.220: download - view: text, annotated - select for diffs
Sun May 24 13:36:55 2009 UTC (14 years, 11 months ago) by anton
Branches: MAIN
CVS tags: HEAD
set 387 precision control to 53-bit mantissae to get rid of FLAW in paranoia.fs

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

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