File:  [gforth] / gforth / engine / main.c
Revision 1.228: download - view: text, annotated - select for diffs
Sun Feb 14 18:13:31 2010 UTC (14 years, 2 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Moved setlocale out of io.c

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

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