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

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

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