Annotation of gforth/prims2x0.6.2.fs, revision 1.6

1.1       anton       1: \ converts primitives to, e.g., C code 
                      2: 
1.2       anton       3: \ Copyright (C) 1995,1996,1997,1998,2000,2003,2008 Free Software Foundation, Inc.
1.1       anton       4: 
                      5: \ This file is part of Gforth.
                      6: 
                      7: \ Gforth is free software; you can redistribute it and/or
                      8: \ modify it under the terms of the GNU General Public License
                      9: \ as published by the Free Software Foundation; either version 2
                     10: \ of the License, or (at your option) any later version.
                     11: 
                     12: \ This program is distributed in the hope that it will be useful,
                     13: \ but WITHOUT ANY WARRANTY; without even the implied warranty of
                     14: \ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     15: \ GNU General Public License for more details.
                     16: 
                     17: \ You should have received a copy of the GNU General Public License
                     18: \ along with this program; if not, write to the Free Software
                     19: \ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
                     20: 
                     21: 
                     22: \ This is not very nice (hard limits, no checking, assumes 1 chars = 1).
                     23: \ And it grew even worse when it aged.
                     24: 
                     25: \ Optimizations:
                     26: \ superfluous stores are removed. GCC removes the superfluous loads by itself
                     27: \ TOS and FTOS can be kept in register( variable)s.
                     28: \ 
                     29: \ Problems:
                     30: \ The TOS optimization is somewhat hairy. The problems by example:
                     31: \ 1) dup ( w -- w w ): w=TOS; sp-=1; sp[1]=w; TOS=w;
                     32: \    The store is not superfluous although the earlier opt. would think so
                     33: \    Alternatively:    sp[0]=TOS; w=TOS; sp-=1; TOS=w;
                     34: \ 2) ( -- .. ): sp[0] = TOS; ... /* This additional store is necessary */
                     35: \ 3) ( .. -- ): ... TOS = sp[0]; /* as well as this load */
                     36: \ 4) ( -- ): /* but here they are unnecessary */
                     37: \ 5) Words that call NEXT themselves have to be done very carefully.
                     38: \
                     39: \ To do:
                     40: \ add the store optimization for doubles
                     41: \ regarding problem 1 above: It would be better (for over) to implement
                     42: \      the alternative
                     43: \ store optimization for combined instructions.
                     44: 
                     45: \ Design Uglyness:
                     46: 
                     47: \ - global state (values, variables) in connection with combined instructions.
                     48: 
                     49: \ - index computation is different for instruction-stream and the
                     50: \ stacks; there are two mechanisms for dealing with that
                     51: \ (stack-in-index-xt and a test for stack==instruction-stream); there
                     52: \ should be only one.
                     53: 
                     54: \ for backwards compatibility, jaw
                     55: require compat/strcomp.fs
                     56: 
                     57: warnings off
                     58: 
                     59: \ redefinitions of kernel words not present in gforth-0.6.1
                     60: : latestxt lastcfa @ ;
                     61: : latest last @ ;
                     62: 
                     63: [IFUNDEF] try
                     64: include startup.fs
                     65: [THEN]
                     66: 
                     67: : struct% struct ; \ struct is redefined in gray
                     68: 
                     69: warnings off
                     70: \ warnings on
                     71: 
                     72: include ./gray.fs
                     73: 128 constant max-effect \ number of things on one side of a stack effect
                     74: 4 constant max-stacks  \ the max. number of stacks (including inst-stream).
                     75: 255 constant maxchar
                     76: maxchar 1+ constant eof-char
                     77: #tab constant tab-char
                     78: #lf constant nl-char
                     79: 
                     80: variable rawinput \ pointer to next character to be scanned
                     81: variable endrawinput \ pointer to the end of the input (the char after the last)
                     82: variable cookedinput \ pointer to the next char to be parsed
                     83: variable line \ line number of char pointed to by input
                     84: variable line-start \ pointer to start of current line (for error messages)
                     85: 0 line !
                     86: 2variable filename \ filename of original input file
                     87: 0 0 filename 2!
                     88: 2variable out-filename \ filename of the output file (for sync lines)
                     89: 0 0 out-filename 2!
                     90: 2variable f-comment
                     91: 0 0 f-comment 2!
                     92: variable skipsynclines \ are sync lines ("#line ...") invisible to the parser?
                     93: skipsynclines on
                     94: variable out-nls \ newlines in output (for output sync lines)
                     95: 0 out-nls !
                     96: variable store-optimization \ use store optimization?
                     97: store-optimization off
                     98: 
                     99: variable include-skipped-insts
                    100: \ does the threaded code for a combined instruction include the cells
                    101: \ for the component instructions (true) or only the cells for the
                    102: \ inline arguments (false)
                    103: include-skipped-insts off
                    104: 
                    105: variable immarg \ values for immediate arguments (to be used in IMM_ARG macros)
                    106: $12340000 immarg !
                    107: 
                    108: : th ( addr1 n -- addr2 )
                    109:     cells + ;
                    110: 
                    111: : holds ( addr u -- )
                    112:     \ like HOLD, but for a string
                    113:     tuck + swap 0 +do
                    114:        1- dup c@ hold
                    115:     loop
                    116:     drop ;
                    117: 
                    118: : insert-wordlist { c-addr u wordlist xt -- }
                    119:     \ adds name "addr u" to wordlist using defining word xt
                    120:     \ xt may cause additional stack effects
                    121:     get-current >r wordlist set-current
                    122:     c-addr u nextname xt execute
                    123:     r> set-current ;
                    124: 
                    125: : start ( -- addr )
                    126:  cookedinput @ ;
                    127: 
                    128: : end ( addr -- addr u )
                    129:  cookedinput @ over - ;
                    130: 
                    131: : print-error-line ( -- )
                    132:     \ print the current line and position
                    133:     line-start @ endrawinput @ over - 2dup nl-char scan drop nip ( start end )
                    134:     over - type cr
                    135:     line-start @ rawinput @ over - typewhite ." ^" cr ;
                    136: 
                    137: : ?print-error { f addr u -- }
                    138:     f ?not? if
                    139:        outfile-id >r try
                    140:            stderr to outfile-id
                    141:            filename 2@ type ." :" line @ 0 .r ." : " addr u type cr
                    142:            print-error-line
                    143:            0
                    144:         endtry-iferror
                    145:         then
                    146:        r> to outfile-id throw
                    147:        1 (bye) \ abort
                    148:     endif ;
                    149: 
                    150: : quote ( -- )
                    151:     [char] " emit ;
                    152: 
                    153: \ count output lines to generate sync lines for output
                    154: 
                    155: : count-nls ( addr u -- )
                    156:     bounds u+do
                    157:        i c@ nl-char = negate out-nls +!
                    158:     loop ;
                    159: 
                    160: :noname ( addr u -- )
                    161:     2dup count-nls
                    162:     defers type ;
                    163: is type
                    164: 
                    165: variable output          \ xt ( -- ) of output word for simple primitives
                    166: variable output-combined \ xt ( -- ) of output word for combined primitives
                    167: 
                    168: struct%
                    169:     cell%    field stack-number \ the number of this stack
                    170:     cell% 2* field stack-pointer \ stackpointer name
                    171:     cell%    field stack-type \ name for default type of stack items
                    172:     cell%    field stack-in-index-xt \ ( in-size item -- in-index )
                    173:     cell%    field stack-access-transform \ ( nitem -- index )
                    174: end-struct stack%
                    175: 
                    176: struct%
                    177:  cell% 2* field item-name   \ name, excluding stack prefixes
                    178:  cell%    field item-stack  \ descriptor for the stack used, 0 is default
                    179:  cell%    field item-type   \ descriptor for the item type
                    180:  cell%    field item-offset \ offset in stack items, 0 for the deepest element
                    181:  cell%   field item-first  \ true if this is the first occurence of the item
                    182: end-struct item%
                    183: 
                    184: struct%
                    185:     cell% 2* field type-c-name
                    186:     cell%    field type-stack \ default stack
                    187:     cell%    field type-size  \ size of type in stack items
                    188:     cell%    field type-fetch \ xt of fetch code generator ( item -- )
                    189:     cell%    field type-store \ xt of store code generator ( item -- )
                    190: end-struct type%
                    191: 
                    192: variable next-stack-number 0 next-stack-number !
                    193: create stacks max-stacks cells allot \ array of stacks
                    194: 
                    195: : stack-in-index ( in-size item -- in-index )
                    196:     item-offset @ - 1- ;
                    197: 
                    198: : inst-in-index ( in-size item -- in-index )
                    199:     nip dup item-offset @ swap item-type @ type-size @ + 1- ;
                    200: 
                    201: : make-stack ( addr-ptr u1 type "stack-name" -- )
                    202:     next-stack-number @ max-stacks < s" too many stacks" ?print-error
                    203:     create stack% %allot >r
                    204:     r@ stacks next-stack-number @ th !
                    205:     next-stack-number @ r@ stack-number !
                    206:     1 next-stack-number +!
                    207:     r@ stack-type !
                    208:     save-mem r@ stack-pointer 2! 
                    209:     ['] stack-in-index r@ stack-in-index-xt !
                    210:     ['] noop r@ stack-access-transform !
                    211:     rdrop ;
                    212: 
                    213: : map-stacks { xt -- }
                    214:     \ perform xt for all stacks
                    215:     next-stack-number @ 0 +do
                    216:        stacks i th @ xt execute
                    217:     loop ;
                    218: 
                    219: : map-stacks1 { xt -- }
                    220:     \ perform xt for all stacks except inst-stream
                    221:     next-stack-number @ 1 +do
                    222:        stacks i th @ xt execute
                    223:     loop ;
                    224: 
                    225: \ stack items
                    226: 
                    227: : init-item ( addr u addr1 -- )
                    228:     \ initialize item at addr1 with name addr u
                    229:     \ !! remove stack prefix
                    230:     dup item% %size erase
                    231:     item-name 2! ;
                    232: 
                    233: : map-items { addr end xt -- }
                    234:     \ perform xt for all items in array addr...end
                    235:     end addr ?do
                    236:        i xt execute
                    237:     item% %size +loop ;
                    238: 
                    239: \ types
                    240: 
                    241: : print-type-prefix ( type -- )
                    242:     body> >head name>string type ;
                    243: 
                    244: \ various variables for storing stuff of one primitive
                    245: 
                    246: struct%
                    247:     cell% 2* field prim-name
                    248:     cell% 2* field prim-wordset
                    249:     cell% 2* field prim-c-name
                    250:     cell% 2* field prim-doc
                    251:     cell% 2* field prim-c-code
                    252:     cell% 2* field prim-forth-code
                    253:     cell% 2* field prim-stack-string
                    254:     cell%    field prim-num            \ ordinal number
                    255:     cell%    field prim-items-wordlist \ unique items
                    256:     item% max-effect * field prim-effect-in
                    257:     item% max-effect * field prim-effect-out
                    258:     cell%    field prim-effect-in-end
                    259:     cell%    field prim-effect-out-end
                    260:     cell% max-stacks * field prim-stacks-in  \ number of in items per stack
                    261:     cell% max-stacks * field prim-stacks-out \ number of out items per stack
                    262: end-struct prim%
                    263: 
                    264: : make-prim ( -- prim )
                    265:     prim% %alloc { p }
                    266:     s" " p prim-doc 2! s" " p prim-forth-code 2! s" " p prim-wordset 2!
                    267:     p ;
                    268: 
                    269: 0 value prim     \ in combined prims either combined or a part
                    270: 0 value combined \ in combined prims the combined prim
                    271: variable in-part \ true if processing a part
                    272:  in-part off
                    273: 
                    274: : prim-context ( ... p xt -- ... )
                    275:     \ execute xt with prim set to p
                    276:     prim >r
                    277:     swap to prim
                    278:     catch
                    279:     r> to prim
                    280:     throw ;
                    281: 
                    282: 1000 constant max-combined
                    283: create combined-prims max-combined cells allot
                    284: variable num-combined
                    285: variable part-num \ current part number during process-combined
                    286: 
                    287: : map-combined { xt -- }
                    288:     \ perform xt for all components of the current combined instruction
                    289:     num-combined @ 0 +do
                    290:        combined-prims i th @ xt execute
                    291:     loop ;
                    292: 
                    293: table constant combinations
                    294:   \ the keys are the sequences of pointers to primitives
                    295: 
                    296: create current-depth max-stacks cells allot
                    297: create max-depth     max-stacks cells allot
                    298: create min-depth     max-stacks cells allot
                    299: 
                    300: create sp-update-in max-stacks cells allot
                    301: \ where max-depth occured the first time
                    302: create max-depths max-stacks max-combined 1+ * cells allot
                    303: \ maximum depth at start of each part: array[parts] of array[stack]
                    304: create max-back-depths max-stacks max-combined 1+ * cells allot
1.4       anton     305: \ maximum depth from end of the combination to the start of the each part
                    306: create depths max-stacks max-combined 1+ * cells allot
                    307: \ depth at the start of each part: array[parts] of array[stack]
1.1       anton     308: 
                    309: : s-c-max-depth ( nstack ncomponent -- addr )
                    310:     max-stacks * + cells max-depths + ;
                    311: 
                    312: : s-c-max-back-depth ( nstack ncomponent -- addr )
                    313:     max-stacks * + cells max-back-depths + ;
                    314: 
1.4       anton     315: : s-c-depth  ( nstack ncomponent -- addr )
                    316:     max-stacks * + cells depths + ;
                    317: 
                    318: : final-max-depth? { nstack ncomponent -- flag }
                    319:     \ does the stack reach its final maxdepth before the component?
                    320:     nstack ncomponent s-c-max-depth @
                    321:     nstack num-combined @ s-c-max-depth @ = ;
                    322: 
1.1       anton     323: wordlist constant primitives
                    324: 
                    325: : create-prim ( prim -- )
                    326:     dup prim-name 2@ primitives ['] constant insert-wordlist ;
                    327: 
                    328: : stack-in ( stack -- addr )
                    329:     \ address of number of stack items in effect in
                    330:     stack-number @ cells prim prim-stacks-in + ;
                    331: 
                    332: : stack-out ( stack -- addr )
                    333:     \ address of number of stack items in effect out
                    334:     stack-number @ cells prim prim-stacks-out + ;
                    335: 
                    336: \ global vars
                    337: variable c-line
                    338: 2variable c-filename
                    339: variable name-line
                    340: 2variable name-filename
                    341: 2variable last-name-filename
                    342: Variable function-number 0 function-number !
                    343: Variable function-old 0 function-old !
                    344: : function-diff ( n -- )
                    345:     ." GROUPADD(" function-number @ function-old @ - 0 .r ." )" cr
                    346:     function-number @ function-old ! ;
                    347: : forth-fdiff ( -- )
                    348:     function-number @ function-old @ - 0 .r ."  groupadd" cr
                    349:     function-number @ function-old ! ;
                    350: 
                    351: \ a few more set ops
                    352: 
                    353: : bit-equivalent ( w1 w2 -- w3 )
                    354:  xor invert ;
                    355: 
                    356: : complement ( set1 -- set2 )
                    357:  empty ['] bit-equivalent binary-set-operation ;
                    358: 
                    359: \ forward declaration for inst-stream (breaks cycle in definitions)
                    360: defer inst-stream-f ( -- stack )
                    361: 
                    362: \ stack access stuff
                    363: 
                    364: : normal-stack-access0 { n stack -- }
                    365:     n stack stack-access-transform @ execute ." [" 0 .r ." ]" ;
                    366:     
                    367: : normal-stack-access1 { n stack -- }
                    368:     stack stack-pointer 2@ type
                    369:     n if
                    370:        n stack normal-stack-access0
                    371:     else
                    372:        ." TOS"
                    373:     endif ;
                    374: 
                    375: : normal-stack-access ( n stack -- )
                    376:     dup inst-stream-f = if
                    377:        ." IMM_ARG(" normal-stack-access1 ." ," immarg ? ." )"
                    378:        1 immarg +!
                    379:     else
                    380:        normal-stack-access1
                    381:     endif ;
                    382: 
                    383: : stack-depth { stack -- n }
                    384:     current-depth stack stack-number @ th @ ;
                    385: 
                    386: : part-stack-access { n stack -- }
                    387:     \ print _<stack><x>, x=inst-stream? n : maxdepth-currentdepth-n-1
                    388:     ." _" stack stack-pointer 2@ type
                    389:     stack stack-number @ { stack# }
                    390:     stack stack-depth n + { access-depth }
                    391:     stack inst-stream-f = if
                    392:        access-depth
                    393:     else
                    394:        combined prim-stacks-in stack# th @
                    395:        assert( dup max-depth stack# th @ = )
                    396:        access-depth - 1-
                    397:     endif
                    398:     0 .r ;
                    399: 
                    400: : part-stack-read { n stack -- }
                    401:     stack stack-depth n + ( ndepth )
                    402:     stack stack-number @ part-num @ s-c-max-depth @
                    403: \    max-depth stack stack-number @ th @ ( ndepth nmaxdepth )
                    404:     over <= if ( ndepth ) \ load from memory
                    405:        stack normal-stack-access
                    406:     else
                    407:        drop n stack part-stack-access
                    408:     endif ;
                    409: 
                    410: : stack-diff ( stack -- n )
                    411:     \ in-out
                    412:     dup stack-in @ swap stack-out @ - ;
                    413: 
                    414: : part-stack-write { n stack -- }
                    415:     stack stack-depth n +
                    416:     stack stack-number @ part-num @ s-c-max-back-depth @
                    417:     over <= if ( ndepth )
                    418:        stack combined ['] stack-diff prim-context -
                    419:        stack normal-stack-access
                    420:     else
                    421:        drop n stack part-stack-access
                    422:     endif ;
                    423: 
                    424: : stack-read ( n stack -- )
                    425:     \ print a stack access at index n of stack
                    426:     in-part @ if
                    427:        part-stack-read
                    428:     else
                    429:        normal-stack-access
                    430:     endif ;
                    431: 
                    432: : stack-write ( n stack -- )
                    433:     \ print a stack access at index n of stack
                    434:     in-part @ if
                    435:        part-stack-write
                    436:     else
                    437:        normal-stack-access
                    438:     endif ;
                    439: 
                    440: : item-in-index { item -- n }
                    441:     \ n is the index of item (in the in-effect)
                    442:     item item-stack @ dup >r stack-in @ ( in-size r:stack )
                    443:     item r> stack-in-index-xt @ execute ;
                    444: 
                    445: : item-stack-type-name ( item -- addr u )
                    446:     item-stack @ stack-type @ type-c-name 2@ ;
                    447: 
                    448: : fetch-single ( item -- )
                    449:     \ fetch a single stack item from its stack
                    450:     >r
                    451:     ." vm_" r@ item-stack-type-name type
                    452:     ." 2" r@ item-type @ print-type-prefix ." ("
                    453:     r@ item-in-index r@ item-stack @ stack-read ." ,"
                    454:     r@ item-name 2@ type
                    455:     ." );" cr
                    456:     rdrop ; 
                    457: 
                    458: : fetch-double ( item -- )
                    459:     \ fetch a double stack item from its stack
                    460:     >r
                    461:     ." vm_two"
                    462:     r@ item-stack-type-name type ." 2"
                    463:     r@ item-type @ print-type-prefix ." ("
                    464:     r@ item-in-index r@ item-stack @ 2dup ." (Cell)" stack-read
                    465:     ." , "                      -1 under+ ." (Cell)" stack-read
                    466:     ." , " r@ item-name 2@ type
                    467:     ." )" cr
                    468:     rdrop ;
                    469: 
                    470: : same-as-in? ( item -- f )
                    471:  \ f is true iff the offset and stack of item is the same as on input
                    472:  >r
                    473:  r@ item-first @ if
                    474:      rdrop false exit
                    475:  endif
                    476:  r@ item-name 2@ prim prim-items-wordlist @ search-wordlist 0= abort" bug"
                    477:  execute @
                    478:  dup r@ =
                    479:  if \ item first appeared in output
                    480:    drop false
                    481:  else
                    482:    dup  item-stack  @ r@ item-stack  @ = 
                    483:    swap item-offset @ r@ item-offset @ = and
                    484:  endif
                    485:  rdrop ;
                    486: 
                    487: : item-out-index ( item -- n )
                    488:     \ n is the index of item (in the in-effect)
                    489:     >r r@ item-stack @ stack-out @ r> item-offset @ - 1- ;
                    490: 
                    491: : really-store-single ( item -- )
                    492:     >r
                    493:     ." vm_"
                    494:     r@ item-type @ print-type-prefix ." 2"
                    495:     r@ item-stack-type-name type ." ("
                    496:     r@ item-name 2@ type ." ,"
                    497:     r@ item-out-index r@ item-stack @ stack-write ." );"
                    498:     rdrop ;
                    499: 
                    500: : store-single ( item -- )
                    501:     >r
                    502:     store-optimization @ in-part @ 0= and r@ same-as-in? and if
                    503:        r@ item-in-index 0= r@ item-out-index 0= xor if
                    504:            ." IF_" r@ item-stack @ stack-pointer 2@ type
                    505:            ." TOS(" r@ really-store-single ." );" cr
                    506:        endif
                    507:     else
                    508:        r@ really-store-single cr
                    509:     endif
                    510:     rdrop ;
                    511: 
                    512: : store-double ( item -- )
                    513: \ !! store optimization is not performed, because it is not yet needed
                    514:  >r
                    515:  ." vm_"
                    516:  r@ item-type @ print-type-prefix ." 2two"
                    517:  r@ item-stack-type-name type ." ("
                    518:  r@ item-name 2@ type ." , "
                    519:  r@ item-out-index r@ item-stack @ 2dup stack-write
                    520:  ." , "                       -1 under+ stack-write
                    521:  ." )" cr
                    522:  rdrop ;
                    523: 
                    524: : single ( -- xt1 xt2 n )
                    525:     ['] fetch-single ['] store-single 1 ;
                    526: 
                    527: : double ( -- xt1 xt2 n )
                    528:     ['] fetch-double ['] store-double 2 ;
                    529: 
                    530: : s, ( addr u -- )
                    531: \ allocate a string
                    532:  here swap dup allot move ;
                    533: 
                    534: wordlist constant prefixes
                    535: 
                    536: : declare ( addr "name" -- )
                    537: \ remember that there is a stack item at addr called name
                    538:  create , ;
                    539: 
                    540: : !default ( w addr -- )
                    541:     dup @ if
                    542:        2drop \ leave nonzero alone
                    543:     else
                    544:        !
                    545:     endif ;
                    546: 
                    547: : create-type { addr u xt1 xt2 n stack -- } ( "prefix" -- )
                    548:     \ describes a type
                    549:     \ addr u specifies the C type name
                    550:     \ stack effect entries of the type start with prefix
                    551:     create type% %allot >r
                    552:     addr u save-mem r@ type-c-name 2!
                    553:     xt1   r@ type-fetch !
                    554:     xt2   r@ type-store !
                    555:     n     r@ type-size !
                    556:     stack r@ type-stack !
                    557:     rdrop ;
                    558: 
                    559: : type-prefix ( addr u xt1 xt2 n stack "prefix" -- )
                    560:     get-current >r prefixes set-current
                    561:     create-type r> set-current
                    562: does> ( item -- )
                    563:     \ initialize item
                    564:     { item typ }
                    565:     typ item item-type !
                    566:     typ type-stack @ item item-stack !default
                    567:     item item-name 2@ prim prim-items-wordlist @ search-wordlist 0= if
                    568:        item item-name 2@ nextname item declare
                    569:        item item-first on
                    570:        \ typ type-c-name 2@ type space type  ." ;" cr
                    571:     else
                    572:        drop
                    573:        item item-first off
                    574:     endif ;
                    575: 
                    576: : execute-prefix ( item addr1 u1 -- )
                    577:     \ execute the word ( item -- ) associated with the longest prefix
                    578:     \ of addr1 u1
                    579:     0 swap ?do
                    580:        dup i prefixes search-wordlist
                    581:        if \ ok, we have the type ( item addr1 xt )
                    582:            nip execute
                    583:            UNLOOP EXIT
                    584:        endif
                    585:        -1 s+loop
                    586:     \ we did not find a type, abort
                    587:     false s" unknown prefix" ?print-error ;
                    588: 
                    589: : declaration ( item -- )
                    590:     dup item-name 2@ execute-prefix ;
                    591: 
                    592: : declaration-list ( addr1 addr2 -- )
                    593:     ['] declaration map-items ;
                    594: 
                    595: : declarations ( -- )
                    596:  wordlist dup prim prim-items-wordlist ! set-current
                    597:  prim prim-effect-in prim prim-effect-in-end @ declaration-list
                    598:  prim prim-effect-out prim prim-effect-out-end @ declaration-list ;
                    599: 
                    600: : print-declaration { item -- }
                    601:     item item-first @ if
                    602:        item item-type @ type-c-name 2@ type space
                    603:        item item-name 2@ type ." ;" cr
                    604:     endif ;
                    605: 
                    606: : print-declarations ( -- )
                    607:     prim prim-effect-in  prim prim-effect-in-end  @ ['] print-declaration map-items
                    608:     prim prim-effect-out prim prim-effect-out-end @ ['] print-declaration map-items ;
                    609:     
                    610: : stack-prefix ( stack "prefix" -- )
                    611:     get-current >r prefixes set-current
                    612:     name tuck nextname create ( stack length ) 2,
                    613:     r> set-current
                    614: does> ( item -- )
                    615:     2@ { item stack prefix-length }
                    616:     item item-name 2@ prefix-length /string item item-name 2!
                    617:     stack item item-stack !
                    618:     item declaration ;
                    619: 
                    620: \ types pointed to by stacks for use in combined prims
                    621: \ !! output-c-combined shouldn't use these names!
                    622: : stack-type-name ( addr u "name" -- )
                    623:     single 0 create-type ;
                    624: 
                    625: wordlist constant type-names \ this is here just to meet the requirement
                    626:                     \ that a type be a word; it is never used for lookup
                    627: 
                    628: : stack ( "name" "stack-pointer" "type" -- )
                    629:     \ define stack
                    630:     name { d: stack-name }
                    631:     name { d: stack-pointer }
                    632:     name { d: stack-type }
                    633:     get-current type-names set-current
                    634:     stack-type 2dup nextname stack-type-name
                    635:     set-current
                    636:     stack-pointer latestxt >body stack-name nextname make-stack ;
                    637: 
                    638: stack inst-stream IP Cell
                    639: ' inst-in-index inst-stream stack-in-index-xt !
                    640: ' inst-stream <is> inst-stream-f
                    641: \ !! initialize stack-in and stack-out
                    642: 
                    643: \ offset computation
                    644: \ the leftmost (i.e. deepest) item has offset 0
                    645: \ the rightmost item has the highest offset
                    646: 
                    647: : compute-offset { item xt -- }
                    648:     \ xt specifies in/out; update stack-in/out and set item-offset
                    649:     item item-type @ type-size @
                    650:     item item-stack @ xt execute dup @ >r +!
                    651:     r> item item-offset ! ;
                    652: 
                    653: : compute-offset-in ( addr1 addr2 -- )
                    654:     ['] stack-in compute-offset ;
                    655: 
                    656: : compute-offset-out ( addr1 addr2 -- )
                    657:     ['] stack-out compute-offset ;
                    658: 
                    659: : compute-offsets ( -- )
                    660:     prim prim-stacks-in  max-stacks cells erase
                    661:     prim prim-stacks-out max-stacks cells erase
                    662:     prim prim-effect-in  prim prim-effect-in-end  @ ['] compute-offset-in  map-items
                    663:     prim prim-effect-out prim prim-effect-out-end @ ['] compute-offset-out map-items
                    664:     inst-stream stack-out @ 0= s" # can only be on the input side" ?print-error ;
                    665: 
                    666: : process-simple ( -- )
                    667:     prim prim { W^ key } key cell
                    668:     combinations ['] constant insert-wordlist
                    669:     declarations compute-offsets
                    670:     output @ execute ;
                    671: 
                    672: : flush-a-tos { stack -- }
                    673:     stack stack-out @ 0<> stack stack-in @ 0= and
                    674:     if
                    675:        ." IF_" stack stack-pointer 2@ 2dup type ." TOS("
                    676:        2dup type 0 stack normal-stack-access0 ."  = " type ." TOS);" cr
                    677:     endif ;
                    678: 
                    679: : flush-tos ( -- )
                    680:     ['] flush-a-tos map-stacks1 ;
                    681: 
                    682: : fill-a-tos { stack -- }
                    683:     stack stack-out @ 0= stack stack-in @ 0<> and
                    684:     if
                    685:        ." IF_" stack stack-pointer 2@ 2dup type ." TOS("
                    686:        2dup type ." TOS = " type 0 stack normal-stack-access0 ." );" cr
                    687:     endif ;
                    688: 
                    689: : fill-tos ( -- )
                    690:     \ !! inst-stream for prefetching?
                    691:     ['] fill-a-tos map-stacks1 ;
                    692: 
                    693: : fetch ( addr -- )
                    694:     dup item-type @ type-fetch @ execute ;
                    695: 
                    696: : fetches ( -- )
                    697:     prim prim-effect-in prim prim-effect-in-end @ ['] fetch map-items ;
                    698: 
                    699: : stack-update-transform ( n1 stack -- n2 )
                    700:     \ n2 is the number by which the stack pointer should be
                    701:     \ incremented to pop n1 items
                    702:     stack-access-transform @ dup >r execute
                    703:     0 r> execute - ;
                    704: 
1.4       anton     705: : n-stack-pointer-update { n stack -- }
                    706:     \ stack pointer update by n
                    707:     n if \ this check is not necessary, gcc would do this for us
1.1       anton     708:        stack inst-stream = if
1.4       anton     709:            ." INC_IP(" n 0 .r ." );" cr
1.1       anton     710:        else
                    711:            stack stack-pointer 2@ type ."  += "
1.4       anton     712:            n stack stack-update-transform 0 .r ." ;" cr
1.1       anton     713:        endif
                    714:     endif ;
                    715: 
1.4       anton     716: : stack-pointer-update { stack -- }
                    717:     \ stacks grow downwards
                    718:     stack stack-diff stack n-stack-pointer-update ;
                    719: 
1.1       anton     720: : stack-pointer-updates ( -- )
                    721:     ['] stack-pointer-update map-stacks ;
                    722: 
                    723: : store ( item -- )
                    724: \ f is true if the item should be stored
                    725: \ f is false if the store is probably not necessary
                    726:  dup item-type @ type-store @ execute ;
                    727: 
                    728: : stores ( -- )
                    729:     prim prim-effect-out prim prim-effect-out-end @ ['] store map-items ;
                    730: 
                    731: : print-debug-arg { item -- }
                    732:     ." fputs(" quote space item item-name 2@ type ." =" quote ." , vm_out); "
                    733:     ." printarg_" item item-type @ print-type-prefix
                    734:     ." (" item item-name 2@ type ." );" cr ;
                    735:     
                    736: : print-debug-args ( -- )
                    737:     ." #ifdef VM_DEBUG" cr
                    738:     ." if (vm_debug) {" cr
                    739:     prim prim-effect-in prim prim-effect-in-end @ ['] print-debug-arg map-items
                    740: \    ." fputc('\n', vm_out);" cr
                    741:     ." }" cr
                    742:     ." #endif" cr ;
                    743: 
                    744: : print-debug-result { item -- }
                    745:     item item-first @ if
                    746:        item print-debug-arg
                    747:     endif ;
                    748: 
                    749: : print-debug-results ( -- )
                    750:     cr
                    751:     ." #ifdef VM_DEBUG" cr
                    752:     ." if (vm_debug) {" cr
                    753:     ." fputs(" quote ."  -- " quote ." , vm_out); "
                    754:     prim prim-effect-out prim prim-effect-out-end @ ['] print-debug-result map-items
                    755:     ." fputc('\n', vm_out);" cr
                    756:     ." }" cr
                    757:     ." #endif" cr ;
                    758: 
                    759: : output-super-end ( -- )
                    760:     prim prim-c-code 2@ s" SET_IP" search if
                    761:        ." SUPER_END;" cr
                    762:     endif
                    763:     2drop ;
                    764: 
                    765: : output-nextp2 ( -- )
                    766:     ." NEXT_P2;" cr ;
                    767: 
                    768: variable tail-nextp2 \ xt to execute for printing NEXT_P2 in INST_TAIL
                    769: ' output-nextp2 tail-nextp2 !
                    770: 
                    771: : output-label2 ( -- )
                    772:     ." LABEL2(" prim prim-c-name 2@ type ." )" cr
                    773:     ." NEXT_P2;" cr ;
                    774: 
                    775: : output-c-tail1 { xt -- }
                    776:     \ the final part of the generated C code, with xt printing LABEL2 or not.
                    777:     output-super-end
                    778:     print-debug-results
                    779:     ." NEXT_P1;" cr
                    780:     stores
                    781:     fill-tos 
                    782:     xt execute ;
                    783: 
                    784: : output-c-tail1-no-stores { xt -- }
                    785:     \ the final part of the generated C code for combinations
                    786:     output-super-end
                    787:     ." NEXT_P1;" cr
                    788:     fill-tos 
                    789:     xt execute ;
                    790: 
                    791: : output-c-tail ( -- )
                    792:     tail-nextp2 @ output-c-tail1 ;
                    793: 
                    794: : output-c-tail2 ( -- )
                    795:     ['] output-label2 output-c-tail1 ;
                    796: 
                    797: : output-c-tail-no-stores ( -- )
                    798:     tail-nextp2 @ output-c-tail1-no-stores ;
                    799: 
                    800: : output-c-tail2-no-stores ( -- )
                    801:     ['] output-label2 output-c-tail1-no-stores ;
                    802: 
                    803: : type-c-code ( c-addr u xt -- )
                    804:     \ like TYPE, but replaces "INST_TAIL;" with tail code produced by xt
                    805:     { xt }
                    806:     ." {" cr
                    807:     ." #line " c-line @ . quote c-filename 2@ type quote cr
                    808:     begin ( c-addr1 u1 )
                    809:        2dup s" INST_TAIL;" search
                    810:     while ( c-addr1 u1 c-addr3 u3 )
                    811:        2dup 2>r drop nip over - type
                    812:        xt execute
                    813:        2r> 10 /string
                    814:        \ !! resync #line missing
                    815:     repeat
                    816:     2drop type
                    817:     ." #line " out-nls @ 2 + . quote out-filename 2@ type quote cr
                    818:     ." }" cr ;
                    819: 
                    820: : print-entry ( -- )
                    821:     ." LABEL(" prim prim-c-name 2@ type ." )" ;
                    822:     
                    823: : output-c ( -- ) 
                    824:     print-entry ."  /* " prim prim-name 2@ type ."  ( " prim prim-stack-string 2@ type ." ) */" cr
                    825:     ." /* " prim prim-doc 2@ type ."  */" cr
                    826:     ." NAME(" quote prim prim-name 2@ type quote ." )" cr \ debugging
                    827:     ." {" cr
                    828:     ." DEF_CA" cr
                    829:     print-declarations
                    830:     ." NEXT_P0;" cr
                    831:     flush-tos
                    832:     fetches
                    833:     print-debug-args
                    834:     stack-pointer-updates
                    835:     prim prim-c-code 2@ ['] output-c-tail type-c-code
                    836:     output-c-tail2
                    837:     ." }" cr
                    838:     cr
                    839: ;
                    840: 
                    841: : disasm-arg { item -- }
                    842:     item item-stack @ inst-stream = if
                    843:        ." {" cr
                    844:        item print-declaration
                    845:        item fetch
                    846:        item print-debug-arg
                    847:        ." }" cr
                    848:     endif ;
                    849: 
                    850: : disasm-args ( -- )
                    851:     prim prim-effect-in prim prim-effect-in-end @ ['] disasm-arg map-items ;
                    852: 
                    853: : output-disasm ( -- )
                    854:     \ generate code for disassembling VM instructions
                    855:     ." if (VM_IS_INST(*ip, " function-number @ 0 .r ." )) {" cr
                    856:     ."   fputs(" quote prim prim-name 2@ type quote ." , vm_out);" cr
                    857:     disasm-args
                    858:     ."   ip += " inst-stream stack-in @ 1+ 0 .r ." ;" cr
                    859:     ."   goto _endif_;" cr
                    860:     ." }" cr ;
                    861: 
                    862: : output-profile ( -- )
                    863:     \ generate code for postprocessing the VM block profile stuff
                    864:     ." if (VM_IS_INST(*ip, " function-number @ 0 .r ." )) {" cr
                    865:     ."   add_inst(b, " quote prim prim-name 2@ type quote ." );" cr
                    866:     ."   ip += " inst-stream stack-in @ 1+ 0 .r ." ;" cr
                    867:     prim prim-c-code 2@  s" SET_IP"    search nip nip
                    868:     prim prim-c-code 2@  s" SUPER_END" search nip nip or if
                    869:        ."   return;" cr
                    870:     else
                    871:        ."   goto _endif_;" cr
                    872:     endif
                    873:     ." }" cr ;
                    874: 
                    875: : output-profile-part ( p )
                    876:     ."   add_inst(b, " quote
                    877:     prim-name 2@ type
                    878:     quote ." );" cr ;
                    879:     
                    880: : output-profile-combined ( -- )
                    881:     \ generate code for postprocessing the VM block profile stuff
                    882:     ." if (VM_IS_INST(*ip, " function-number @ 0 .r ." )) {" cr
                    883:     ['] output-profile-part map-combined
                    884:     ."   ip += " inst-stream stack-in @ 1+ 0 .r ." ;" cr
                    885:     combined-prims num-combined @ 1- th @ prim-c-code 2@  s" SET_IP"    search nip nip
                    886:     combined-prims num-combined @ 1- th @ prim-c-code 2@  s" SUPER_END" search nip nip or if
                    887:        ."   return;" cr
                    888:     else
                    889:        ."   goto _endif_;" cr
                    890:     endif
                    891:     ." }" cr ;
                    892: 
                    893: : output-superend ( -- )
                    894:     \ output flag specifying whether the current word ends a dynamic superinst
                    895:     prim prim-c-code 2@  s" SET_IP"    search nip nip
                    896:     prim prim-c-code 2@  s" SUPER_END" search nip nip or 0<>
                    897:     prim prim-c-code 2@  s" SUPER_CONTINUE" search nip nip 0= and
                    898:     negate 0 .r ." , /* " prim prim-name 2@ type ."  */" cr ;
                    899: 
                    900: : gen-arg-parm { item -- }
                    901:     item item-stack @ inst-stream = if
                    902:        ." , " item item-type @ type-c-name 2@ type space
                    903:        item item-name 2@ type
                    904:     endif ;
                    905: 
                    906: : gen-args-parm ( -- )
                    907:     prim prim-effect-in prim prim-effect-in-end @ ['] gen-arg-parm map-items ;
                    908: 
                    909: : gen-arg-gen { item -- }
                    910:     item item-stack @ inst-stream = if
                    911:        ."   genarg_" item item-type @ print-type-prefix
                    912:         ." (ctp, " item item-name 2@ type ." );" cr
                    913:     endif ;
                    914: 
                    915: : gen-args-gen ( -- )
                    916:     prim prim-effect-in prim prim-effect-in-end @ ['] gen-arg-gen map-items ;
                    917: 
                    918: : output-gen ( -- )
                    919:     \ generate C code for generating VM instructions
                    920:     ." void gen_" prim prim-c-name 2@ type ." (Inst **ctp" gen-args-parm ." )" cr
                    921:     ." {" cr
                    922:     ."   gen_inst(ctp, vm_prim[" function-number @ 0 .r ." ]);" cr
                    923:     gen-args-gen
                    924:     ." }" cr ;
                    925: 
                    926: : stack-used? { stack -- f }
                    927:     stack stack-in @ stack stack-out @ or 0<> ;
                    928: 
                    929: : output-funclabel ( -- )
                    930:   ." &I_" prim prim-c-name 2@ type ." ," cr ;
                    931: 
                    932: : output-forthname ( -- )
                    933:   '" emit prim prim-name 2@ type '" emit ." ," cr ;
                    934: 
                    935: \  : output-c-func ( -- )
                    936: \  \ used for word libraries
                    937: \      ." Cell * I_" prim prim-c-name 2@ type ." (Cell *SP, Cell **FP)      /* " prim prim-name 2@ type
                    938: \      ."  ( " prim prim-stack-string 2@ type ."  ) */" cr
                    939: \      ." /* " prim prim-doc 2@ type ."  */" cr
                    940: \      ." NAME(" quote prim prim-name 2@ type quote ." )" cr
                    941: \      \ debugging
                    942: \      ." {" cr
                    943: \      print-declarations
                    944: \      \ !! don't know what to do about that
                    945: \      inst-stream  stack-used? IF ." Cell *ip=IP;" cr THEN
                    946: \      data-stack   stack-used? IF ." Cell *sp=SP;" cr THEN
                    947: \      fp-stack     stack-used? IF ." Cell *fp=*FP;" cr THEN
                    948: \      return-stack stack-used? IF ." Cell *rp=*RP;" cr THEN
                    949: \      flush-tos
                    950: \      fetches
                    951: \      stack-pointer-updates
                    952: \      fp-stack   stack-used? IF ." *FP=fp;" cr THEN
                    953: \      ." {" cr
                    954: \      ." #line " c-line @ . quote c-filename 2@ type quote cr
                    955: \      prim prim-c-code 2@ type
                    956: \      ." }" cr
                    957: \      stores
                    958: \      fill-tos
                    959: \      ." return (sp);" cr
                    960: \      ." }" cr
                    961: \      cr ;
                    962: 
                    963: : output-label ( -- )  
                    964:     ." INST_ADDR(" prim prim-c-name 2@ type ." )," cr ;
                    965: 
                    966: : output-alias ( -- ) 
                    967:     ( primitive-number @ . ." alias " ) ." Primitive " prim prim-name 2@ type cr ;
                    968: 
                    969: : output-c-prim-num ( -- )
                    970:     ." N_" prim prim-c-name 2@ type ." ," cr ;
                    971: 
                    972: : output-forth ( -- )  
                    973:     prim prim-forth-code @ 0=
                    974:     IF         \ output-alias
                    975:        \ this is bad for ec: an alias is compiled if tho word does not exist!
                    976:        \ JAW
                    977:     ELSE  ." : " prim prim-name 2@ type ."   ( "
                    978:        prim prim-stack-string 2@ type ." )" cr
                    979:        prim prim-forth-code 2@ type cr
                    980:     THEN ;
                    981: 
                    982: : output-tag-file ( -- )
                    983:     name-filename 2@ last-name-filename 2@ compare if
                    984:        name-filename 2@ last-name-filename 2!
                    985:        #ff emit cr
                    986:        name-filename 2@ type
                    987:        ." ,0" cr
                    988:     endif ;
                    989: 
                    990: : output-tag ( -- )
                    991:     output-tag-file
                    992:     prim prim-name 2@ 1+ type
                    993:     127 emit
                    994:     space prim prim-name 2@ type space
                    995:     1 emit
                    996:     name-line @ 0 .r
                    997:     ." ,0" cr ;
                    998: 
                    999: : output-vi-tag ( -- )
                   1000:     name-filename 2@ type #tab emit
                   1001:     prim prim-name 2@ type #tab emit
                   1002:     ." /^" prim prim-name 2@ type ."  *(/" cr ;
                   1003: 
                   1004: [IFDEF] documentation
                   1005: : register-doc ( -- )
                   1006:     prim prim-name 2@ documentation ['] create insert-wordlist
                   1007:     prim prim-name 2@ 2,
                   1008:     prim prim-stack-string 2@ condition-stack-effect 2,
                   1009:     prim prim-wordset 2@ 2,
                   1010:     prim prim-c-name 2@ condition-pronounciation 2,
                   1011:     prim prim-doc 2@ 2, ;
                   1012: [THEN]
                   1013: 
                   1014: 
                   1015: \ combining instructions
                   1016: 
                   1017: \ The input should look like this:
                   1018: 
                   1019: \ lit_+ = lit +
                   1020: 
                   1021: \ The output should look like this:
                   1022: 
                   1023: \  I_lit_+:
                   1024: \  {
                   1025: \  DEF_CA
                   1026: \  Cell _x_ip0;
                   1027: \  Cell _x_sp0;
                   1028: \  Cell _x_sp1;
                   1029: \  NEXT_P0;
                   1030: \  _x_ip0 = (Cell) IPTOS;
                   1031: \  _x_sp0 = (Cell) spTOS;
                   1032: \  INC_IP(1);
                   1033: \  /* sp += 0; */
                   1034: \  /* lit ( #w -- w ) */
                   1035: \  /*  */
                   1036: \  NAME("lit")
                   1037: \  {
                   1038: \  Cell w;
                   1039: \  w = (Cell) _x_ip0;
                   1040: \  #ifdef VM_DEBUG
                   1041: \  if (vm_debug) {
                   1042: \  fputs(" w=", vm_out); printarg_w (w);
                   1043: \  fputc('\n', vm_out);
                   1044: \  }
                   1045: \  #endif
                   1046: \  {
                   1047: \  #line 136 "./prim"
                   1048: \  }
                   1049: \  _x_sp1 = (Cell)w;
                   1050: \  }
                   1051: \  I_plus:     /* + ( n1 n2 -- n ) */
                   1052: \  /*  */
                   1053: \  NAME("+")
                   1054: \  {
                   1055: \  DEF_CA
                   1056: \  Cell n1;
                   1057: \  Cell n2;
                   1058: \  Cell n;
                   1059: \  NEXT_P0;
                   1060: \  n1 = (Cell) _x_sp0;
                   1061: \  n2 = (Cell) _x_sp1;
                   1062: \  #ifdef VM_DEBUG
                   1063: \  if (vm_debug) {
                   1064: \  fputs(" n1=", vm_out); printarg_n (n1);
                   1065: \  fputs(" n2=", vm_out); printarg_n (n2);
                   1066: \  fputc('\n', vm_out);
                   1067: \  }
                   1068: \  #endif
                   1069: \  {
                   1070: \  #line 516 "./prim"
                   1071: \  n = n1+n2;
                   1072: \  }
                   1073: \  _x_sp0 = (Cell)n;
                   1074: \  }
                   1075: \  NEXT_P1;
                   1076: \  spTOS = (Cell)_x_sp0;
                   1077: \  NEXT_P2;
                   1078: 
                   1079: : init-combined ( -- )
                   1080:     prim to combined
                   1081:     0 num-combined !
                   1082:     current-depth max-stacks cells erase
                   1083:     include-skipped-insts @ current-depth 0 th !
                   1084:     max-depth     max-stacks cells erase
                   1085:     min-depth     max-stacks cells erase
                   1086:     prim prim-effect-in  prim prim-effect-in-end  !
                   1087:     prim prim-effect-out prim prim-effect-out-end ! ;
                   1088: 
                   1089: : max! ( n addr -- )
                   1090:     tuck @ max swap ! ;
                   1091: 
                   1092: : min! ( n addr -- )
                   1093:     tuck @ min swap ! ;
                   1094: 
                   1095: : inst-stream-adjustment ( nstack -- n )
                   1096:     \ number of stack items to add for each part
                   1097:     0= include-skipped-insts @ and negate ;
                   1098: 
                   1099: : add-depths { p -- }
                   1100:     \ combine stack effect of p with *-depths
                   1101:     max-stacks 0 ?do
                   1102:        current-depth i th @
                   1103:        p prim-stacks-in  i th @ + i inst-stream-adjustment +
                   1104:        dup max-depth i th max!
                   1105:        p prim-stacks-out i th @ -
                   1106:        dup min-depth i th min!
                   1107:        current-depth i th !
                   1108:     loop ;
                   1109: 
1.4       anton    1110: : copy-maxdepths { n -- }
                   1111:     \ transfer current-depth to depths and max-depth to max-depths
                   1112:     max-depth max-depths n max-stacks * th max-stacks cells move
                   1113:     current-depth depths n max-stacks * th max-stacks cells move ;
1.1       anton    1114: 
                   1115: : add-prim ( addr u -- )
                   1116:     \ add primitive given by "addr u" to combined-prims
                   1117:     primitives search-wordlist s" unknown primitive" ?print-error
                   1118:     execute { p }
                   1119:     p combined-prims num-combined @ th !
                   1120:     num-combined @ copy-maxdepths
                   1121:     1 num-combined +!
                   1122:     p add-depths
                   1123:     num-combined @ copy-maxdepths ;
                   1124: 
                   1125: : compute-effects { q -- }
                   1126:     \ compute the stack effects of q from the depths
                   1127:     max-stacks 0 ?do
                   1128:        max-depth i th @ dup
                   1129:        q prim-stacks-in i th !
                   1130:        current-depth i th @ -
                   1131:        q prim-stacks-out i th !
                   1132:     loop ;
                   1133: 
                   1134: : make-effect-items { stack# items effect-endp -- }
                   1135:     \ effect-endp points to a pointer to the end of the current item-array
                   1136:     \ and has to be updated
                   1137:     stacks stack# th @ { stack }
                   1138:     items 0 +do
                   1139:        effect-endp @ { item }
                   1140:        i 0 <# #s stack stack-pointer 2@ holds [char] _ hold #> save-mem
                   1141:        item item-name 2!
                   1142:        stack item item-stack !
                   1143:        stack stack-type @ item item-type !
                   1144:        i item item-offset !
                   1145:        item item-first on
                   1146:        item% %size effect-endp +!
                   1147:     loop ;
                   1148: 
                   1149: : init-effects { q -- }
                   1150:     \ initialize effects field for FETCHES and STORES
                   1151:     max-stacks 0 ?do
                   1152:        i q prim-stacks-in  i th @ q prim-effect-in-end  make-effect-items
                   1153:        i q prim-stacks-out i th @ q prim-effect-out-end make-effect-items
                   1154:     loop ;
                   1155: 
                   1156: : compute-stack-max-back-depths ( stack -- )
                   1157:     stack-number @ { stack# }
                   1158:     current-depth stack# th @ dup
                   1159:     dup stack# num-combined @ s-c-max-back-depth !
                   1160:     -1 num-combined @ 1- -do ( max-depth current-depth )
                   1161:        combined-prims i th @ { p }
                   1162:        p prim-stacks-out stack# th @ +
                   1163:        dup >r max r>
                   1164:        over stack# i s-c-max-back-depth !
                   1165:        p prim-stacks-in stack# th @ -
                   1166:        stack# inst-stream-adjustment -
                   1167:     1 -loop
                   1168:     assert( dup stack# inst-stream-adjustment negate = )
                   1169:     assert( over max-depth stack# th @ = )
                   1170:     2drop ;
                   1171: 
                   1172: : compute-max-back-depths ( -- )
                   1173:     \ compute max-back-depths.
                   1174:     \ assumes that current-depths is correct for the end of the combination
                   1175:     ['] compute-stack-max-back-depths map-stacks ;
                   1176: 
                   1177: : process-combined ( -- )
                   1178:     combined combined-prims num-combined @ cells
                   1179:     combinations ['] constant insert-wordlist
                   1180:     combined-prims num-combined @ 1- th ( last-part )
                   1181:     @ prim-c-code 2@ prim prim-c-code 2! \ used by output-super-end
                   1182:     prim compute-effects
                   1183:     prim init-effects
                   1184:     compute-max-back-depths
                   1185:     output-combined perform ;
                   1186: 
                   1187: \ C output
                   1188: 
                   1189: : print-item { n stack -- }
                   1190:     \ print nth stack item name
                   1191:     stack stack-type @ type-c-name 2@ type space
                   1192:     ." MAYBE_UNUSED _" stack stack-pointer 2@ type n 0 .r ;
                   1193: 
                   1194: : print-declarations-combined ( -- )
                   1195:     max-stacks 0 ?do
                   1196:        max-depth i th @ min-depth i th @ - 0 +do
                   1197:            i stacks j th @ print-item ." ;" cr
                   1198:        loop
                   1199:     loop ;
                   1200: 
                   1201: : part-fetches ( -- )
                   1202:     fetches ;
                   1203: 
                   1204: : part-output-c-tail ( -- )
                   1205:     print-debug-results
                   1206:     stores ;
                   1207: 
1.6     ! anton    1208: : stack-combined-tail-stores { stack -- }
        !          1209:     \ the top stack-out items of this part are stored elsewhere; so
        !          1210:     \ this store everything between max-depth, unless it was stored
        !          1211:     \ previously (below back-max-depth) and stack-out
        !          1212:     stack stack-number @ part-num @ 2dup 2>r s-c-max-depth @ 
        !          1213:     2r> s-c-max-back-depth @ min
        !          1214:     stack stack-depth -
        !          1215:     stack stack-out @ +do
        !          1216:         i stack normal-stack-access ."  = "
        !          1217:         i stack part-stack-access ." ;" cr
        !          1218:     loop ;
        !          1219: 
        !          1220: : combined-tail-stores ( -- )
        !          1221:     \ All the stores we have yet to do on an INST_TAIL that are the
        !          1222:     \ result of earlier parts (and will be consumed by other parts in
        !          1223:     \ the fallthrough path, and thus have not been stored in the
        !          1224:     \ earlier part).
        !          1225:     ['] stack-combined-tail-stores map-stacks ;
        !          1226: 
1.4       anton    1227: : combined-tail-stack-pointer-update { stack -- }
                   1228:     stack stack-number @ { nstack }
                   1229:     nstack part-num @ 1+ s-c-depth @ ( nupdate-raw )
                   1230:     \ correct for possible earlier update
                   1231:     nstack part-num @ 1+ final-max-depth? if
                   1232:         stack combined ['] stack-diff prim-context - endif
                   1233:     stack n-stack-pointer-update ;
                   1234: 
                   1235: : combined-tail-stack-pointer-updates ( -- )
                   1236:     ['] combined-tail-stack-pointer-update map-stacks ;
                   1237: 
1.1       anton    1238: : output-combined-tail ( -- )
1.3       anton    1239:     in-part @ >r in-part off
1.5       anton    1240:     combined-tail-stack-pointer-updates
1.1       anton    1241:     part-output-c-tail
1.6     ! anton    1242:     combined-tail-stores
1.1       anton    1243:     combined ['] output-c-tail-no-stores prim-context
                   1244:     r> in-part ! ;
                   1245: 
                   1246: : part-stack-pointer-updates ( -- )
                   1247:     next-stack-number @ 0 +do
1.4       anton    1248:         i part-num @ 1+ final-max-depth? \ reached afterwards
                   1249:         i part-num @ final-max-depth? 0= \ but not before
                   1250:         part-num @ 0= \ exception: first part
1.1       anton    1251:        or and if
                   1252:            stacks i th @ stack-pointer-update
                   1253:        endif
                   1254:     loop ;
                   1255: 
                   1256: : output-part ( p -- )
                   1257:     to prim
                   1258:     ." /* " prim prim-name 2@ type ."  ( " prim prim-stack-string 2@ type ." ) */" cr
                   1259:     ." NAME(" quote prim prim-name 2@ type quote ." )" cr \ debugging
                   1260:     ." {" cr
                   1261:     print-declarations
                   1262:     part-fetches
                   1263:     print-debug-args
                   1264:     combined ['] part-stack-pointer-updates prim-context
                   1265:     prim add-depths \ !! right place?
                   1266:     prim prim-c-code 2@ ['] output-combined-tail type-c-code
1.4       anton    1267:     1 part-num +!
1.1       anton    1268:     part-output-c-tail
                   1269:     ." }" cr ;
                   1270: 
                   1271: : output-parts ( -- )
                   1272:     prim >r in-part on
                   1273:     current-depth max-stacks cells erase
                   1274:     0 part-num !
                   1275:     ['] output-part map-combined
                   1276:     in-part off
                   1277:     r> to prim ;
                   1278: 
                   1279: : output-c-combined ( -- )
                   1280:     print-entry cr
                   1281:     \ debugging messages just in parts
                   1282:     ." {" cr
                   1283:     ." DEF_CA" cr
                   1284:     print-declarations-combined
                   1285:     ." NEXT_P0;" cr
                   1286:     flush-tos
                   1287:     \ fetches \ now in parts
                   1288:     \ print-debug-args
                   1289:     \ stack-pointer-updates now in parts
                   1290:     output-parts
                   1291:     output-c-tail2-no-stores
                   1292:     ." }" cr
                   1293:     cr ;
                   1294: 
                   1295: : output-forth-combined ( -- )
                   1296: ;
                   1297: 
                   1298: 
                   1299: \ peephole optimization rules
                   1300: 
                   1301: \ data for a simple peephole optimizer that always tries to combine
                   1302: \ the currently compiled instruction with the last one.
                   1303: 
                   1304: \ in order for this to work as intended, shorter combinations for each
                   1305: \ length must be present, and the longer combinations must follow
                   1306: \ shorter ones (this restriction may go away in the future).
                   1307:   
                   1308: : output-peephole ( -- )
                   1309:     combined-prims num-combined @ 1- cells combinations search-wordlist
                   1310:     s" the prefix for this superinstruction must be defined earlier" ?print-error
                   1311:     ." {"
                   1312:     execute prim-num @ 5 .r ." ,"
                   1313:     combined-prims num-combined @ 1- th @ prim-num @ 5 .r ." ,"
                   1314:     combined prim-num @ 5 .r ." }, /* "
                   1315:     combined prim-c-name 2@ type ."  */"
                   1316:     cr ;
                   1317: 
                   1318: 
                   1319: \ cost and superinstruction data for a sophisticated combiner (e.g.,
                   1320: \ shortest path)
                   1321: 
                   1322: \ This is intended as initializer for a structure like this
                   1323: 
                   1324: \  struct cost {
                   1325: \    int loads;       /* number of stack loads */
                   1326: \    int stores;      /* number of stack stores */
                   1327: \    int updates;     /* number of stack pointer updates */
                   1328: \    int offset;      /* offset into super2 table */
                   1329: \    int length;      /* number of components */
                   1330: \  };
                   1331: 
                   1332: \ How do you know which primitive or combined instruction this
                   1333: \ structure refers to?  By the order of cost structures, as in most
                   1334: \ other cases.
                   1335: 
                   1336: : super2-length ( -- n )
                   1337:     combined if
                   1338:        num-combined @
                   1339:     else
                   1340:        1
                   1341:     endif ;
                   1342: 
                   1343: : compute-costs { p -- nloads nstores nupdates }
                   1344:     \ compute the number of loads, stores, and stack pointer updates
                   1345:     \ of a primitive or combined instruction; does not take TOS
                   1346:     \ caching into account
                   1347:     0 max-stacks 0 +do
                   1348:        p prim-stacks-in i th @ +
                   1349:     loop
                   1350:     super2-length 1- - \ don't count instruction fetches of subsumed insts
                   1351:     0 max-stacks 0 +do
                   1352:        p prim-stacks-out i th @ +
                   1353:     loop
                   1354:     0 max-stacks 1 +do \ don't count ip updates, therefore "1 +do"
                   1355:        p prim-stacks-in i th @ p prim-stacks-out i th @ <> -
                   1356:     loop ;
                   1357: 
                   1358: : output-num-part ( p -- )
                   1359:     ." N_" prim-c-name 2@ type ." ," ;
                   1360:     \ prim-num @ 4 .r ." ," ;
                   1361: 
                   1362: : output-name-comment ( -- )
                   1363:     ."  /* " prim prim-name 2@ type ."  */" ;
                   1364: 
                   1365: variable offset-super2  0 offset-super2 ! \ offset into the super2 table
                   1366: 
                   1367: : output-costs-gforth-simple ( -- )
                   1368:      ." {" prim compute-costs
                   1369:     rot 2 .r ." ," swap 2 .r ." ," 2 .r ." , "
                   1370:     prim output-num-part
                   1371:     1 2 .r ." },"
                   1372:     output-name-comment
                   1373:     cr ;
                   1374: 
                   1375: : output-costs-gforth-combined ( -- )
                   1376:     ." {" prim compute-costs
                   1377:     rot 2 .r ." ," swap 2 .r ." ," 2 .r ." , "
                   1378:     ." N_START_SUPER+" offset-super2 @ 5 .r ." ,"
                   1379:     super2-length dup 2 .r ." }," offset-super2 +!
                   1380:     output-name-comment
                   1381:     cr ;
                   1382: 
                   1383: : output-costs ( -- )
                   1384:     \ description of superinstructions and simple instructions
                   1385:     ." {" prim compute-costs
                   1386:     rot 2 .r ." ," swap 2 .r ." ," 2 .r ." ,"
                   1387:     offset-super2 @ 5 .r ." ,"
                   1388:     super2-length dup 2 .r ." }," offset-super2 +!
                   1389:     output-name-comment
                   1390:     cr ;
                   1391: 
                   1392: : output-super2 ( -- )
                   1393:     \ table of superinstructions without requirement for existing prefixes
                   1394:     combined if
                   1395:        ['] output-num-part map-combined 
                   1396:     else
                   1397:        prim output-num-part
                   1398:     endif
                   1399:     output-name-comment
                   1400:     cr ;   
                   1401: 
                   1402: \ the parser
                   1403: 
                   1404: eof-char max-member \ the whole character set + EOF
                   1405: 
                   1406: : getinput ( -- n )
                   1407:  rawinput @ endrawinput @ =
                   1408:  if
                   1409:    eof-char
                   1410:  else
                   1411:    cookedinput @ c@
                   1412:  endif ;
                   1413: 
                   1414: :noname ( n -- )
                   1415:  dup bl > if
                   1416:   emit space
                   1417:  else
                   1418:   .
                   1419:  endif ;
                   1420: print-token !
                   1421: 
                   1422: : testchar? ( set -- f )
                   1423:  getinput member? ;
                   1424: ' testchar? test-vector !
                   1425: 
                   1426: : checksynclines ( -- )
                   1427:     \ when input points to a newline, check if the next line is a
                   1428:     \ sync line.  If it is, perform the appropriate actions.
                   1429:     rawinput @ begin >r
                   1430:        s" #line " r@ over compare if
                   1431:            rdrop 1 line +! EXIT
                   1432:        endif
                   1433:        0. r> 6 chars + 20 >number drop >r drop line ! r> ( c-addr )
                   1434:        dup c@ bl = if
                   1435:            char+ dup c@ [char] " <> 0= s" sync line syntax" ?print-error
                   1436:            char+ dup 100 [char] " scan drop swap 2dup - save-mem filename 2!
                   1437:            char+
                   1438:        endif
                   1439:        dup c@ nl-char <> 0= s" sync line syntax" ?print-error
                   1440:        skipsynclines @ if
                   1441:            char+ dup rawinput !
                   1442:            rawinput @ c@ cookedinput @ c!
                   1443:        endif
                   1444:     again ;
                   1445: 
                   1446: : ?nextchar ( f -- )
                   1447:     s" syntax error, wrong char" ?print-error
                   1448:     rawinput @ endrawinput @ <> if
                   1449:        rawinput @ c@
                   1450:        1 chars rawinput +!
                   1451:        1 chars cookedinput +!
                   1452:        nl-char = if
                   1453:            checksynclines
                   1454:            rawinput @ line-start !
                   1455:        endif
                   1456:        rawinput @ c@
                   1457:        cookedinput @ c!
                   1458:     endif ;
                   1459: 
                   1460: : charclass ( set "name" -- )
                   1461:  ['] ?nextchar terminal ;
                   1462: 
                   1463: : .. ( c1 c2 -- set )
                   1464:  ( creates a set that includes the characters c, c1<=c<=c2 )
                   1465:  empty copy-set
                   1466:  swap 1+ rot do
                   1467:   i over add-member
                   1468:  loop ;
                   1469: 
                   1470: : ` ( -- terminal ) ( use: ` c )
                   1471:  ( creates anonymous terminal for the character c )
                   1472:  char singleton ['] ?nextchar make-terminal ;
                   1473: 
                   1474: char a char z ..  char A char Z ..  union char _ singleton union  charclass letter
                   1475: char 0 char 9 ..                                       charclass digit
                   1476: bl singleton tab-char over add-member                  charclass white
                   1477: nl-char singleton eof-char over add-member complement  charclass nonl
                   1478: nl-char singleton eof-char over add-member
                   1479:     char : over add-member complement                   charclass nocolonnl
                   1480: nl-char singleton eof-char over add-member
                   1481:     char } over add-member complement                   charclass nobracenl
                   1482: bl 1+ maxchar .. char \ singleton complement intersection
                   1483:                                                         charclass nowhitebq
                   1484: bl 1+ maxchar ..                                        charclass nowhite
                   1485: char " singleton eof-char over add-member complement   charclass noquote
                   1486: nl-char singleton                                      charclass nl
                   1487: eof-char singleton                                     charclass eof
                   1488: nl-char singleton eof-char over add-member             charclass nleof
                   1489: 
                   1490: (( letter (( letter || digit )) **
                   1491: )) <- c-ident ( -- )
                   1492: 
                   1493: (( ` # ?? (( letter || digit || ` : )) ++
                   1494: )) <- stack-ident ( -- )
                   1495: 
                   1496: (( nowhitebq nowhite ** ))
                   1497: <- forth-ident ( -- )
                   1498: 
                   1499: Variable forth-flag
                   1500: Variable c-flag
                   1501: 
                   1502: (( (( ` e || ` E )) {{ start }} nonl ** 
                   1503:    {{ end evaluate }}
                   1504: )) <- eval-comment ( ... -- ... )
                   1505: 
                   1506: (( (( ` f || ` F )) {{ start }} nonl ** 
                   1507:    {{ end forth-flag @ IF type cr ELSE 2drop THEN }}
                   1508: )) <- forth-comment ( -- )
                   1509: 
                   1510: (( (( ` c || ` C )) {{ start }} nonl ** 
                   1511:    {{ end c-flag @ IF type cr ELSE 2drop THEN }}
                   1512: )) <- c-comment ( -- )
                   1513: 
                   1514: (( ` - nonl ** {{ 
                   1515:        forth-flag @ IF forth-fdiff ." [ELSE]" cr THEN
                   1516:        c-flag @ IF
                   1517:            function-diff
                   1518:            ." #else /* " function-number @ 0 .r ."  */" cr THEN }}
                   1519: )) <- else-comment
                   1520: 
                   1521: (( ` + {{ start }} nonl ** {{ end
                   1522:        dup
                   1523:        IF      c-flag @
                   1524:            IF
                   1525:                function-diff
                   1526:                ." #ifdef HAS_" bounds ?DO  I c@ toupper emit  LOOP cr
                   1527:                THEN
                   1528:                forth-flag @
                   1529:                IF  forth-fdiff  ." has? " type ."  [IF]"  cr THEN
                   1530:        ELSE    2drop
                   1531:            c-flag @      IF
                   1532:                function-diff  ." #endif" cr THEN
                   1533:            forth-flag @  IF  forth-fdiff  ." [THEN]"  cr THEN
                   1534:        THEN }}
                   1535: )) <- if-comment
                   1536: 
                   1537: (( (( ` g || ` G )) {{ start }} nonl **
                   1538:    {{ end
                   1539:       forth-flag @ IF  forth-fdiff  ." group " type cr  THEN
                   1540:       c-flag @     IF  function-diff
                   1541:          ." GROUP(" type ." , " function-number @ 0 .r ." )" cr  THEN }}
                   1542: )) <- group-comment
                   1543: 
                   1544: (( (( eval-comment || forth-comment || c-comment || else-comment || if-comment || group-comment )) ?? nonl ** )) <- comment-body
                   1545: 
                   1546: (( ` \ comment-body nleof )) <- comment ( -- )
                   1547: 
                   1548: (( {{ start }} stack-ident {{ end 2 pick init-item item% %size + }} white ** )) **
                   1549: <- stack-items
                   1550: 
                   1551: (( {{ prim prim-effect-in }}  stack-items {{ prim prim-effect-in-end ! }}
                   1552:    ` - ` - white **
                   1553:    {{ prim prim-effect-out }} stack-items {{ prim prim-effect-out-end ! }}
                   1554: )) <- stack-effect ( -- )
                   1555: 
                   1556: (( {{ prim create-prim }}
                   1557:    ` ( white ** {{ start }} stack-effect {{ end prim prim-stack-string 2! }} ` ) white **
                   1558:    (( {{ start }} forth-ident {{ end prim prim-wordset 2! }} white **
                   1559:       (( {{ start }}  c-ident {{ end prim prim-c-name 2! }} )) ??
                   1560:    )) ??  nleof
                   1561:    (( ` " ` "  {{ start }} (( noquote ++ ` " )) ++ {{ end 1- prim prim-doc 2! }} ` " white ** nleof )) ??
                   1562:    {{ skipsynclines off line @ c-line ! filename 2@ c-filename 2! start }}
                   1563:    (( (( ` { nonl ** nleof (( (( nobracenl {{ line @ drop }} nonl ** )) ?? nleof )) ** ` } white ** nleof white ** ))
                   1564:    || (( nocolonnl nonl **  nleof white ** )) ** ))
                   1565:    {{ end prim prim-c-code 2! skipsynclines on }}
                   1566:    (( ` :  white ** nleof
                   1567:       {{ start }} (( nonl ++  nleof white ** )) ++ {{ end prim prim-forth-code 2! }}
                   1568:    )) ?? {{ process-simple }}
                   1569:    nleof
                   1570: )) <- simple-primitive ( -- )
                   1571: 
                   1572: (( {{ init-combined }}
                   1573:    ` = white ** (( {{ start }} forth-ident {{ end add-prim }} white ** )) ++
                   1574:    nleof {{ process-combined }}
                   1575: )) <- combined-primitive
                   1576: 
                   1577: (( {{ make-prim to prim 0 to combined
                   1578:       line @ name-line ! filename 2@ name-filename 2!
                   1579:       function-number @ prim prim-num !
                   1580:       start }} [ifdef] vmgen c-ident [else] forth-ident [then] {{ end
                   1581:       2dup prim prim-name 2! prim prim-c-name 2! }}  white **
                   1582:    (( ` / white ** {{ start }} c-ident {{ end prim prim-c-name 2! }} white ** )) ??
                   1583:    (( simple-primitive || combined-primitive ))
                   1584:    {{ 1 function-number +! }}
                   1585: )) <- primitive ( -- )
                   1586: 
                   1587: (( (( comment || primitive || nl white ** )) ** eof ))
                   1588: parser primitives2something
                   1589: warnings @ [IF]
                   1590: .( parser generated ok ) cr
                   1591: [THEN]
                   1592: 
                   1593: 
                   1594: \ run with gforth-0.5.0 (slurp-file is missing)
                   1595: [IFUNDEF] slurp-file
                   1596: : slurp-file ( c-addr1 u1 -- c-addr2 u2 )
                   1597:     \ c-addr1 u1 is the filename, c-addr2 u2 is the file's contents
                   1598:     r/o bin open-file throw >r
                   1599:     r@ file-size throw abort" file too large"
                   1600:     dup allocate throw swap
                   1601:     2dup r@ read-file throw over <> abort" could not read whole file"
                   1602:     r> close-file throw ;
                   1603: [THEN]
                   1604: 
                   1605: : primfilter ( addr u -- )
                   1606:     \ process the string at addr u
                   1607:     over dup rawinput ! dup line-start ! cookedinput !
                   1608:     + endrawinput !
                   1609:     checksynclines
                   1610:     primitives2something ;    
                   1611: 
                   1612: : unixify ( c-addr u1 -- c-addr u2 )
                   1613:     \ delete crs from the string
                   1614:     bounds tuck tuck ?do ( c-addr1 )
                   1615:        i c@ dup #cr <> if
                   1616:            over c! char+
                   1617:        else
                   1618:            drop
                   1619:        endif
                   1620:     loop
                   1621:     over - ;
                   1622: 
                   1623: : process-file ( addr u xt-simple x-combined -- )
                   1624:     output-combined ! output !
                   1625:     save-mem 2dup filename 2!
                   1626:     slurp-file unixify
                   1627:     warnings @ if
                   1628:        ." ------------ CUT HERE -------------" cr  endif
                   1629:     primfilter ;
                   1630: 
                   1631: \  : process      ( xt -- )
                   1632: \      bl word count rot
                   1633: \      process-file ;

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