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