Annotation of gforth/engine/main.c, revision 1.184

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

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