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

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

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