Annotation of gforth/doc/vmgen.texi, revision 1.21

1.10      anton       1: \input texinfo    @c -*-texinfo-*-
                      2: @comment %**start of header
                      3: @setfilename vmgen.info
1.1       anton       4: @include version.texi
1.10      anton       5: @settitle Vmgen (Gforth @value{VERSION})
                      6: @c @syncodeindex pg cp
                      7: @comment %**end of header
                      8: @copying
                      9: This manual is for Vmgen
                     10: (version @value{VERSION}, @value{UPDATED}),
                     11: the virtual machine interpreter generator
                     12: 
                     13: Copyright @copyright{} 2002 Free Software Foundation, Inc.
                     14: 
                     15: @quotation
                     16: Permission is granted to copy, distribute and/or modify this document
                     17: under the terms of the GNU Free Documentation License, Version 1.1 or
                     18: any later version published by the Free Software Foundation; with no
                     19: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     20: and with the Back-Cover Texts as in (a) below.  A copy of the
                     21: license is included in the section entitled ``GNU Free Documentation
                     22: License.''
                     23: 
                     24: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     25: this GNU Manual, like GNU software.  Copies published by the Free
                     26: Software Foundation raise funds for GNU development.''
                     27: @end quotation
                     28: @end copying
                     29: 
                     30: @dircategory GNU programming tools
                     31: @direntry
1.11      anton      32: * Vmgen: (vmgen).               Interpreter generator
1.10      anton      33: @end direntry
                     34: 
                     35: @titlepage
                     36: @title Vmgen
                     37: @subtitle for Gforth version @value{VERSION}, @value{UPDATED}
1.11      anton      38: @author M. Anton Ertl (@email{anton@@mips.complang.tuwien.ac.at})
1.10      anton      39: @page
                     40: @vskip 0pt plus 1filll
                     41: @insertcopying
                     42: @end titlepage
                     43: 
                     44: @contents
                     45: 
                     46: @ifnottex
                     47: @node Top, Introduction, (dir), (dir)
                     48: @top Vmgen
                     49: 
                     50: @insertcopying
                     51: @end ifnottex
                     52: 
                     53: @menu
                     54: * Introduction::                What can Vmgen do for you?
                     55: * Why interpreters?::           Advantages and disadvantages
                     56: * Concepts::                    VM interpreter background
1.11      anton      57: * Invoking Vmgen::              
1.10      anton      58: * Example::                     
                     59: * Input File Format::           
1.13      anton      60: * Error messages::              reported by Vmgen
1.10      anton      61: * Using the generated code::    
1.13      anton      62: * Hints::                       VM archictecture, efficiency
                     63: * The future::                  
1.10      anton      64: * Changes::                     from earlier versions
                     65: * Contact::                     Bug reporting etc.
                     66: * Copying This Manual::         Manual License
                     67: * Index::                       
                     68: 
                     69: @detailmenu
                     70:  --- The Detailed Node Listing ---
                     71: 
                     72: Concepts
                     73: 
                     74: * Front end and VM interpreter::  Modularizing an interpretive system
                     75: * Data handling::               Stacks, registers, immediate arguments
                     76: * Dispatch::                    From one VM instruction to the next
                     77: 
                     78: Example
                     79: 
                     80: * Example overview::            
                     81: * Using profiling to create superinstructions::  
                     82: 
                     83: Input File Format
                     84: 
                     85: * Input File Grammar::          
                     86: * Simple instructions::         
                     87: * Superinstructions::           
1.18      anton      88: * Store Optimization::          
1.11      anton      89: * Register Machines::           How to define register VM instructions
1.10      anton      90: 
1.17      anton      91: Input File Grammar
                     92: 
                     93: * Eval escapes::                what follows \E
                     94: 
1.10      anton      95: Simple instructions
                     96: 
                     97: * C Code Macros::               Macros recognized by Vmgen
                     98: * C Code restrictions::         Vmgen makes assumptions about C code
                     99: 
                    100: Using the generated code
                    101: 
                    102: * VM engine::                   Executing VM code
                    103: * VM instruction table::        
                    104: * VM code generation::          Creating VM code (in the front-end)
                    105: * Peephole optimization::       Creating VM superinstructions
                    106: * VM disassembler::             for debugging the front end
                    107: * VM profiler::                 for finding worthwhile superinstructions
                    108: 
1.13      anton     109: Hints
                    110: 
                    111: * Floating point::              and stacks
                    112: 
1.10      anton     113: Copying This Manual
                    114: 
                    115: * GNU Free Documentation License::  License for copying this manual.
                    116: 
                    117: @end detailmenu
                    118: @end menu
1.1       anton     119: 
                    120: @c @ifnottex
1.11      anton     121: @c This file documents Vmgen (Gforth @value{VERSION}).
1.1       anton     122: 
1.10      anton     123: @c ************************************************************
                    124: @node Introduction, Why interpreters?, Top, Top
1.2       anton     125: @chapter Introduction
1.1       anton     126: 
                    127: Vmgen is a tool for writing efficient interpreters.  It takes a simple
                    128: virtual machine description and generates efficient C code for dealing
                    129: with the virtual machine code in various ways (in particular, executing
                    130: it).  The run-time efficiency of the resulting interpreters is usually
                    131: within a factor of 10 of machine code produced by an optimizing
                    132: compiler.
                    133: 
1.11      anton     134: The interpreter design strategy supported by Vmgen is to divide the
1.1       anton     135: interpreter into two parts:
                    136: 
                    137: @itemize @bullet
                    138: 
                    139: @item The @emph{front end} takes the source code of the language to be
                    140: implemented, and translates it into virtual machine code.  This is
                    141: similar to an ordinary compiler front end; typically an interpreter
                    142: front-end performs no optimization, so it is relatively simple to
                    143: implement and runs fast.
                    144: 
                    145: @item The @emph{virtual machine interpreter} executes the virtual
                    146: machine code.
                    147: 
                    148: @end itemize
                    149: 
                    150: Such a division is usually used in interpreters, for modularity as well
1.6       anton     151: as for efficiency.  The virtual machine code is typically passed between
                    152: front end and virtual machine interpreter in memory, like in a
1.1       anton     153: load-and-go compiler; this avoids the complexity and time cost of
                    154: writing the code to a file and reading it again.
                    155: 
                    156: A @emph{virtual machine} (VM) represents the program as a sequence of
                    157: @emph{VM instructions}, following each other in memory, similar to real
                    158: machine code.  Control flow occurs through VM branch instructions, like
                    159: in a real machine.
                    160: 
1.12      anton     161: @cindex functionality features overview
1.11      anton     162: In this setup, Vmgen can generate most of the code dealing with virtual
1.1       anton     163: machine instructions from a simple description of the virtual machine
1.11      anton     164: instructions (@pxref{Input File Format}), in particular:
1.1       anton     165: 
1.13      anton     166: @table @strong
1.1       anton     167: 
                    168: @item VM instruction execution
                    169: 
                    170: @item VM code generation
                    171: Useful in the front end.
                    172: 
                    173: @item VM code decompiler
                    174: Useful for debugging the front end.
                    175: 
                    176: @item VM code tracing
                    177: Useful for debugging the front end and the VM interpreter.  You will
                    178: typically provide other means for debugging the user's programs at the
                    179: source level.
                    180: 
                    181: @item VM code profiling
1.12      anton     182: Useful for optimizing the VM interpreter with superinstructions
1.11      anton     183: (@pxref{VM profiler}).
1.1       anton     184: 
                    185: @end table
                    186: 
1.13      anton     187: To create parts of the interpretive system that do not deal with VM
                    188: instructions, you have to use other tools (e.g., @command{bison}) and/or
                    189: hand-code them.
                    190: 
1.12      anton     191: @cindex efficiency features overview
1.11      anton     192: @noindent
                    193: Vmgen supports efficient interpreters though various optimizations, in
1.1       anton     194: particular
                    195: 
1.11      anton     196: @itemize @bullet
1.1       anton     197: 
                    198: @item Threaded code
                    199: 
                    200: @item Caching the top-of-stack in a register
                    201: 
                    202: @item Combining VM instructions into superinstructions
                    203: 
                    204: @item
                    205: Replicating VM (super)instructions for better BTB prediction accuracy
                    206: (not yet in vmgen-ex, but already in Gforth).
                    207: 
                    208: @end itemize
                    209: 
1.12      anton     210: @cindex speed for JVM
1.11      anton     211: As a result, Vmgen-based interpreters are only about an order of
                    212: magnitude slower than native code from an optimizing C compiler on small
1.1       anton     213: benchmarks; on large benchmarks, which spend more time in the run-time
1.2       anton     214: system, the slowdown is often less (e.g., the slowdown of a
                    215: Vmgen-generated JVM interpreter over the best JVM JIT compiler we
                    216: measured is only a factor of 2-3 for large benchmarks; some other JITs
                    217: and all other interpreters we looked at were slower than our
                    218: interpreter).
1.1       anton     219: 
                    220: VMs are usually designed as stack machines (passing data between VM
1.11      anton     221: instructions on a stack), and Vmgen supports such designs especially
1.12      anton     222: well; however, you can also use Vmgen for implementing a register VM
                    223: (@pxref{Register Machines}) and still benefit from most of the advantages
                    224: offered by Vmgen.
1.1       anton     225: 
1.2       anton     226: There are many potential uses of the instruction descriptions that are
                    227: not implemented at the moment, but we are open for feature requests, and
1.13      anton     228: we will consider new features if someone asks for them; so the feature
1.2       anton     229: list above is not exhaustive.
1.1       anton     230: 
1.2       anton     231: @c *********************************************************************
1.10      anton     232: @node Why interpreters?, Concepts, Introduction, Top
1.2       anton     233: @chapter Why interpreters?
1.12      anton     234: @cindex interpreters, advantages
                    235: @cindex advantages of interpreters
                    236: @cindex advantages of vmgen
1.2       anton     237: 
                    238: Interpreters are a popular language implementation technique because
                    239: they combine all three of the following advantages:
                    240: 
1.11      anton     241: @itemize @bullet
1.2       anton     242: 
                    243: @item Ease of implementation
                    244: 
                    245: @item Portability
                    246: 
                    247: @item Fast edit-compile-run cycle
                    248: 
                    249: @end itemize
                    250: 
1.12      anton     251: Vmgen makes it even easier to implement interpreters.
                    252: 
                    253: @cindex speed of interpreters
1.2       anton     254: The main disadvantage of interpreters is their run-time speed.  However,
                    255: there are huge differences between different interpreters in this area:
                    256: the slowdown over optimized C code on programs consisting of simple
                    257: operations is typically a factor of 10 for the more efficient
                    258: interpreters, and a factor of 1000 for the less efficient ones (the
                    259: slowdown for programs executing complex operations is less, because the
                    260: time spent in libraries for executing complex operations is the same in
                    261: all implementation strategies).
                    262: 
1.12      anton     263: Vmgen supports techniques for building efficient interpreters.
1.2       anton     264: 
                    265: @c ********************************************************************
1.11      anton     266: @node Concepts, Invoking Vmgen, Why interpreters?, Top
1.2       anton     267: @chapter Concepts
                    268: 
1.10      anton     269: @menu
                    270: * Front end and VM interpreter::  Modularizing an interpretive system
                    271: * Data handling::               Stacks, registers, immediate arguments
                    272: * Dispatch::                    From one VM instruction to the next
                    273: @end menu
                    274: 
1.2       anton     275: @c --------------------------------------------------------------------
1.10      anton     276: @node Front end and VM interpreter, Data handling, Concepts, Concepts
                    277: @section Front end and VM interpreter
1.12      anton     278: @cindex modularization of interpreters
1.2       anton     279: 
                    280: @cindex front-end
                    281: Interpretive systems are typically divided into a @emph{front end} that
                    282: parses the input language and produces an intermediate representation
                    283: for the program, and an interpreter that executes the intermediate
                    284: representation of the program.
                    285: 
                    286: @cindex virtual machine
                    287: @cindex VM
1.12      anton     288: @cindex VM instruction
1.2       anton     289: @cindex instruction, VM
1.12      anton     290: @cindex VM branch instruction
                    291: @cindex branch instruction, VM
                    292: @cindex VM register
                    293: @cindex register, VM
                    294: @cindex opcode, VM instruction
                    295: @cindex immediate argument, VM instruction
1.2       anton     296: For efficient interpreters the intermediate representation of choice is
                    297: virtual machine code (rather than, e.g., an abstract syntax tree).
                    298: @emph{Virtual machine} (VM) code consists of VM instructions arranged
                    299: sequentially in memory; they are executed in sequence by the VM
1.12      anton     300: interpreter, but VM branch instructions can change the control flow and
                    301: are used for implementing control structures.  The conceptual similarity
                    302: to real machine code results in the name @emph{virtual machine}.
                    303: Various terms similar to terms for real machines are used; e.g., there
                    304: are @emph{VM registers} (like the instruction pointer and stack
                    305: pointer(s)), and the VM instruction consists of an @emph{opcode} and
                    306: @emph{immediate arguments}.
1.2       anton     307: 
1.11      anton     308: In this framework, Vmgen supports building the VM interpreter and any
1.2       anton     309: other component dealing with VM instructions.  It does not have any
                    310: support for the front end, apart from VM code generation support.  The
                    311: front end can be implemented with classical compiler front-end
1.3       anton     312: techniques, supported by tools like @command{flex} and @command{bison}.
1.2       anton     313: 
                    314: The intermediate representation is usually just internal to the
                    315: interpreter, but some systems also support saving it to a file, either
                    316: as an image file, or in a full-blown linkable file format (e.g., JVM).
                    317: Vmgen currently has no special support for such features, but the
                    318: information in the instruction descriptions can be helpful, and we are
1.13      anton     319: open to feature requests and suggestions.
1.3       anton     320: 
1.10      anton     321: @c --------------------------------------------------------------------
                    322: @node Data handling, Dispatch, Front end and VM interpreter, Concepts
1.3       anton     323: @section Data handling
                    324: 
                    325: @cindex stack machine
                    326: @cindex register machine
                    327: Most VMs use one or more stacks for passing temporary data between VM
                    328: instructions.  Another option is to use a register machine architecture
1.13      anton     329: for the virtual machine; we believe that using a stack architecture is
                    330: usually both simpler and faster.
                    331: 
                    332: however, this option is slower or
1.3       anton     333: significantly more complex to implement than a stack machine architecture.
                    334: 
                    335: Vmgen has special support and optimizations for stack VMs, making their
                    336: implementation easy and efficient.
                    337: 
1.11      anton     338: You can also implement a register VM with Vmgen (@pxref{Register
                    339: Machines}), and you will still profit from most Vmgen features.
1.3       anton     340: 
                    341: @cindex stack item size
                    342: @cindex size, stack items
                    343: Stack items all have the same size, so they typically will be as wide as
                    344: an integer, pointer, or floating-point value.  Vmgen supports treating
                    345: two consecutive stack items as a single value, but anything larger is
                    346: best kept in some other memory area (e.g., the heap), with pointers to
                    347: the data on the stack.
                    348: 
                    349: @cindex instruction stream
                    350: @cindex immediate arguments
                    351: Another source of data is immediate arguments VM instructions (in the VM
                    352: instruction stream).  The VM instruction stream is handled similar to a
1.11      anton     353: stack in Vmgen.
1.3       anton     354: 
                    355: @cindex garbage collection
                    356: @cindex reference counting
1.12      anton     357: Vmgen has no built-in support for, nor restrictions against
                    358: @emph{garbage collection}.  If you need garbage collection, you need to
                    359: provide it in your run-time libraries.  Using @emph{reference counting}
                    360: is probably harder, but might be possible (contact us if you are
                    361: interested).
1.3       anton     362: @c reference counting might be possible by including counting code in 
                    363: @c the conversion macros.
                    364: 
1.10      anton     365: @c --------------------------------------------------------------------
                    366: @node Dispatch,  , Data handling, Concepts
1.6       anton     367: @section Dispatch
1.12      anton     368: @cindex Dispatch of VM instructions
                    369: @cindex main interpreter loop
1.6       anton     370: 
1.11      anton     371: Understanding this section is probably not necessary for using Vmgen,
1.6       anton     372: but it may help.  You may want to skip it now, and read it if you find statements about dispatch methods confusing.
                    373: 
                    374: After executing one VM instruction, the VM interpreter has to dispatch
1.11      anton     375: the next VM instruction (Vmgen calls the dispatch routine @samp{NEXT}).
1.6       anton     376: Vmgen supports two methods of dispatch:
                    377: 
1.13      anton     378: @table @strong
1.6       anton     379: 
                    380: @item switch dispatch
1.12      anton     381: @cindex switch dispatch
1.6       anton     382: In this method the VM interpreter contains a giant @code{switch}
                    383: statement, with one @code{case} for each VM instruction.  The VM
1.12      anton     384: instruction opcodes are represented by integers (e.g., produced by an
                    385: @code{enum}) in the VM code, and dispatch occurs by loading the next
                    386: opcode, @code{switch}ing on it, and continuing at the appropriate
                    387: @code{case}; after executing the VM instruction, the VM interpreter
                    388: jumps back to the dispatch code.
1.6       anton     389: 
                    390: @item threaded code
1.12      anton     391: @cindex threaded code
                    392: This method represents a VM instruction opcode by the address of the
                    393: start of the machine code fragment for executing the VM instruction.
1.6       anton     394: Dispatch consists of loading this address, jumping to it, and
                    395: incrementing the VM instruction pointer.  Typically the threaded-code
                    396: dispatch code is appended directly to the code for executing the VM
                    397: instruction.  Threaded code cannot be implemented in ANSI C, but it can
1.11      anton     398: be implemented using GNU C's labels-as-values extension (@pxref{Labels
                    399: as Values, , Labels as Values, gcc.info, GNU C Manual}).
1.6       anton     400: 
1.13      anton     401: @c call threading
1.6       anton     402: @end table
                    403: 
1.12      anton     404: Threaded code can be twice as fast as switch dispatch, depending on the
                    405: interpreter, the benchmark, and the machine.
                    406: 
1.3       anton     407: @c *************************************************************
1.11      anton     408: @node Invoking Vmgen, Example, Concepts, Top
                    409: @chapter Invoking Vmgen
1.12      anton     410: @cindex Invoking Vmgen
1.3       anton     411: 
1.11      anton     412: The usual way to invoke Vmgen is as follows:
1.3       anton     413: 
                    414: @example
1.13      anton     415: vmgen @var{inputfile}
1.3       anton     416: @end example
                    417: 
1.13      anton     418: Here @var{inputfile} is the VM instruction description file, which
                    419: usually ends in @file{.vmg}.  The output filenames are made by taking
                    420: the basename of @file{inputfile} (i.e., the output files will be created
                    421: in the current working directory) and replacing @file{.vmg} with
                    422: @file{-vm.i}, @file{-disasm.i}, @file{-gen.i}, @file{-labels.i},
                    423: @file{-profile.i}, and @file{-peephole.i}.  E.g., @command{vmgen
                    424: hack/foo.vmg} will create @file{foo-vm.i}, @file{foo-disasm.i},
                    425: @file{foo-gen.i}, @file{foo-labels.i}, @file{foo-profile.i} and
                    426: @file{foo-peephole.i}.
1.3       anton     427: 
1.11      anton     428: The command-line options supported by Vmgen are
1.3       anton     429: 
                    430: @table @option
                    431: 
                    432: @cindex -h, command-line option
                    433: @cindex --help, command-line option
                    434: @item --help
                    435: @itemx -h
                    436: Print a message about the command-line options
                    437: 
                    438: @cindex -v, command-line option
                    439: @cindex --version, command-line option
                    440: @item --version
                    441: @itemx -v
                    442: Print version and exit
                    443: @end table
                    444: 
                    445: @c env vars GFORTHDIR GFORTHDATADIR
                    446: 
1.5       anton     447: @c ****************************************************************
1.11      anton     448: @node Example, Input File Format, Invoking Vmgen, Top
1.5       anton     449: @chapter Example
1.12      anton     450: @cindex example of a Vmgen-based interpreter
1.5       anton     451: 
1.10      anton     452: @menu
                    453: * Example overview::            
                    454: * Using profiling to create superinstructions::  
                    455: @end menu
                    456: 
                    457: @c --------------------------------------------------------------------
                    458: @node Example overview, Using profiling to create superinstructions, Example, Example
1.5       anton     459: @section Example overview
1.12      anton     460: @cindex example overview
                    461: @cindex @file{vmgen-ex}
                    462: @cindex @file{vmgen-ex2}
1.5       anton     463: 
1.11      anton     464: There are two versions of the same example for using Vmgen:
1.5       anton     465: @file{vmgen-ex} and @file{vmgen-ex2} (you can also see Gforth as
                    466: example, but it uses additional (undocumented) features, and also
                    467: differs in some other respects).  The example implements @emph{mini}, a
                    468: tiny Modula-2-like language with a small JavaVM-like virtual machine.
1.12      anton     469: 
1.5       anton     470: The difference between the examples is that @file{vmgen-ex} uses many
                    471: casts, and @file{vmgen-ex2} tries to avoids most casts and uses unions
1.12      anton     472: instead.  In the rest of this manual we usually mention just files in
                    473: @file{vmgen-ex}; if you want to use unions, use the equivalent file in
                    474: @file{vmgen-ex2}.
                    475: @cindex unions example
                    476: @cindex casts example
1.5       anton     477: 
                    478: The files provided with each example are:
1.12      anton     479: @cindex example files
1.5       anton     480: 
                    481: @example
                    482: Makefile
                    483: README
                    484: disasm.c           wrapper file
                    485: engine.c           wrapper file
                    486: peephole.c         wrapper file
                    487: profile.c          wrapper file
                    488: mini-inst.vmg      simple VM instructions
                    489: mini-super.vmg     superinstructions (empty at first)
                    490: mini.h             common declarations
                    491: mini.l             scanner
                    492: mini.y             front end (parser, VM code generator)
                    493: support.c          main() and other support functions
                    494: fib.mini           example mini program
                    495: simple.mini        example mini program
                    496: test.mini          example mini program (tests everything)
                    497: test.out           test.mini output
                    498: stat.awk           script for aggregating profile information
                    499: peephole-blacklist list of instructions not allowed in superinstructions
                    500: seq2rule.awk       script for creating superinstructions
                    501: @end example
                    502: 
                    503: For your own interpreter, you would typically copy the following files
                    504: and change little, if anything:
1.12      anton     505: @cindex wrapper files
1.5       anton     506: 
                    507: @example
                    508: disasm.c           wrapper file
                    509: engine.c           wrapper file
                    510: peephole.c         wrapper file
                    511: profile.c          wrapper file
                    512: stat.awk           script for aggregating profile information
                    513: seq2rule.awk       script for creating superinstructions
                    514: @end example
                    515: 
1.11      anton     516: @noindent
1.5       anton     517: You would typically change much in or replace the following files:
                    518: 
                    519: @example
                    520: Makefile
                    521: mini-inst.vmg      simple VM instructions
                    522: mini.h             common declarations
                    523: mini.l             scanner
                    524: mini.y             front end (parser, VM code generator)
                    525: support.c          main() and other support functions
                    526: peephole-blacklist list of instructions not allowed in superinstructions
                    527: @end example
                    528: 
                    529: You can build the example by @code{cd}ing into the example's directory,
1.12      anton     530: and then typing @code{make}; you can check that it works with @code{make
1.5       anton     531: check}.  You can run run mini programs like this:
                    532: 
                    533: @example
                    534: ./mini fib.mini
                    535: @end example
                    536: 
1.12      anton     537: To learn about the options, type @code{./mini -h}.
1.5       anton     538: 
1.10      anton     539: @c --------------------------------------------------------------------
                    540: @node Using profiling to create superinstructions,  , Example overview, Example
1.5       anton     541: @section Using profiling to create superinstructions
1.12      anton     542: @cindex profiling example
                    543: @cindex superinstructions example
1.5       anton     544: 
                    545: I have not added rules for this in the @file{Makefile} (there are many
                    546: options for selecting superinstructions, and I did not want to hardcode
                    547: one into the @file{Makefile}), but there are some supporting scripts, and
                    548: here's an example:
                    549: 
                    550: Suppose you want to use @file{fib.mini} and @file{test.mini} as training
                    551: programs, you get the profiles like this:
                    552: 
                    553: @example
                    554: make fib.prof test.prof #takes a few seconds
                    555: @end example
                    556: 
                    557: You can aggregate these profiles with @file{stat.awk}:
                    558: 
                    559: @example
                    560: awk -f stat.awk fib.prof test.prof
                    561: @end example
                    562: 
                    563: The result contains lines like:
                    564: 
                    565: @example
                    566:       2      16        36910041 loadlocal lit
                    567: @end example
                    568: 
                    569: This means that the sequence @code{loadlocal lit} statically occurs a
                    570: total of 16 times in 2 profiles, with a dynamic execution count of
                    571: 36910041.
                    572: 
                    573: The numbers can be used in various ways to select superinstructions.
                    574: E.g., if you just want to select all sequences with a dynamic
                    575: execution count exceeding 10000, you would use the following pipeline:
                    576: 
                    577: @example
                    578: awk -f stat.awk fib.prof test.prof|
                    579: awk '$3>=10000'|                #select sequences
                    580: fgrep -v -f peephole-blacklist| #eliminate wrong instructions
1.12      anton     581: awk -f seq2rule.awk|  #transform sequences into superinstruction rules
1.5       anton     582: sort -k 3 >mini-super.vmg       #sort sequences
                    583: @end example
                    584: 
                    585: The file @file{peephole-blacklist} contains all instructions that
                    586: directly access a stack or stack pointer (for mini: @code{call},
                    587: @code{return}); the sort step is necessary to ensure that prefixes
1.13      anton     588: precede larger superinstructions.
1.5       anton     589: 
                    590: Now you can create a version of mini with superinstructions by just
                    591: saying @samp{make}
                    592: 
1.10      anton     593: 
1.3       anton     594: @c ***************************************************************
1.13      anton     595: @node Input File Format, Error messages, Example, Top
1.3       anton     596: @chapter Input File Format
1.12      anton     597: @cindex input file format
                    598: @cindex format, input file
1.3       anton     599: 
                    600: Vmgen takes as input a file containing specifications of virtual machine
                    601: instructions.  This file usually has a name ending in @file{.vmg}.
                    602: 
1.5       anton     603: Most examples are taken from the example in @file{vmgen-ex}.
1.3       anton     604: 
1.10      anton     605: @menu
                    606: * Input File Grammar::          
                    607: * Simple instructions::         
                    608: * Superinstructions::           
1.18      anton     609: * Store Optimization::          
1.11      anton     610: * Register Machines::           How to define register VM instructions
1.10      anton     611: @end menu
                    612: 
                    613: @c --------------------------------------------------------------------
                    614: @node Input File Grammar, Simple instructions, Input File Format, Input File Format
1.3       anton     615: @section Input File Grammar
1.12      anton     616: @cindex grammar, input file
                    617: @cindex input file grammar
1.3       anton     618: 
                    619: The grammar is in EBNF format, with @code{@var{a}|@var{b}} meaning
                    620: ``@var{a} or @var{b}'', @code{@{@var{c}@}} meaning 0 or more repetitions
                    621: of @var{c} and @code{[@var{d}]} meaning 0 or 1 repetitions of @var{d}.
                    622: 
1.12      anton     623: @cindex free-format, not
1.15      anton     624: @cindex newlines, significance in syntax
1.3       anton     625: Vmgen input is not free-format, so you have to take care where you put
1.15      anton     626: newlines (and, in a few cases, white space).
1.3       anton     627: 
                    628: @example
1.15      anton     629: description: @{instruction|comment|eval-escape|c-escape@}
1.3       anton     630: 
                    631: instruction: simple-inst|superinst
                    632: 
1.15      anton     633: simple-inst: ident '(' stack-effect ')' newline c-code newline newline
1.3       anton     634: 
1.15      anton     635: stack-effect: @{ident@} '--' @{ident@}
1.3       anton     636: 
1.15      anton     637: super-inst: ident '=' ident @{ident@}  
1.3       anton     638: 
1.12      anton     639: comment:      '\ '  text newline
1.3       anton     640: 
1.13      anton     641: eval-escape:  '\E ' text newline
1.15      anton     642: 
                    643: c-escape:     '\C ' text newline
1.3       anton     644: @end example
                    645: @c \+ \- \g \f \c
                    646: 
                    647: Note that the @code{\}s in this grammar are meant literally, not as
1.5       anton     648: C-style encodings for non-printable characters.
1.3       anton     649: 
1.15      anton     650: There are two ways to delimit the C code in @code{simple-inst}:
                    651: 
                    652: @itemize @bullet
                    653: 
                    654: @item
                    655: If you start it with a @samp{@{} at the start of a line (i.e., not even
                    656: white space before it), you have to end it with a @samp{@}} at the start
                    657: of a line (followed by a newline).  In this case you may have empty
                    658: lines within the C code (typically used between variable definitions and
                    659: statements).
                    660: 
                    661: @item
                    662: You do not start it with @samp{@{}.  Then the C code ends at the first
                    663: empty line, so you cannot have empty lines within this code.
                    664: 
                    665: @end itemize
                    666: 
                    667: The text in @code{comment}, @code{eval-escape} and @code{c-escape} must
                    668: not contain a newline.  @code{Ident} must conform to the usual
                    669: conventions of C identifiers (otherwise the C compiler would choke on
                    670: the Vmgen output), except that idents in @code{stack-effect} may have a
                    671: stack prefix (for stack prefix syntax, @pxref{Eval escapes}).
                    672: 
                    673: @cindex C escape
                    674: @cindex @code{\C}
                    675: @cindex conditional compilation of Vmgen output
                    676: The @code{c-escape} passes the text through to each output file (without
                    677: the @samp{\C}).  This is useful mainly for conditional compilation
                    678: (i.e., you write @samp{\C #if ...} etc.).
                    679: 
                    680: @cindex sync lines
                    681: @cindex @code{#line}
                    682: In addition to the syntax given in the grammer, Vmgen also processes
                    683: sync lines (lines starting with @samp{#line}), as produced by @samp{m4
                    684: -s} (@pxref{Invoking m4, , Invoking m4, m4.info, GNU m4}) and similar
                    685: tools.  This allows associating C compiler error messages with the
                    686: original source of the C code.
1.3       anton     687: 
                    688: Vmgen understands a few extensions beyond the grammar given here, but
                    689: these extensions are only useful for building Gforth.  You can find a
                    690: description of the format used for Gforth in @file{prim}.
                    691: 
1.17      anton     692: @menu
                    693: * Eval escapes::                what follows \E
                    694: @end menu
                    695: 
                    696: @node Eval escapes,  , Input File Grammar, Input File Grammar
1.10      anton     697: @subsection Eval escapes
1.12      anton     698: @cindex escape to Forth
                    699: @cindex eval escape
1.15      anton     700: @cindex @code{\E}
1.13      anton     701: 
1.3       anton     702: @c woanders?
                    703: The text in @code{eval-escape} is Forth code that is evaluated when
1.13      anton     704: Vmgen reads the line.  You will normally use this feature to define
                    705: stacks and types.
                    706: 
                    707: If you do not know (and do not want to learn) Forth, you can build the
                    708: text according to the following grammar; these rules are normally all
                    709: Forth you need for using Vmgen:
1.3       anton     710: 
                    711: @example
1.18      anton     712: text: stack-decl|type-prefix-decl|stack-prefix-decl|set-flag
1.3       anton     713: 
1.12      anton     714: stack-decl: 'stack ' ident ident ident
1.3       anton     715: type-prefix-decl: 
1.12      anton     716:     's" ' string '" ' ('single'|'double') ident 'type-prefix' ident
                    717: stack-prefix-decl:  ident 'stack-prefix' string
1.18      anton     718: set-flag: 'store-optimization' ('on'|'off')
1.3       anton     719: @end example
                    720: 
                    721: Note that the syntax of this code is not checked thoroughly (there are
1.13      anton     722: many other Forth program fragments that could be written in an
                    723: eval-escape).
1.3       anton     724: 
1.14      anton     725: A stack prefix can contain letters, digits, or @samp{:}, and may start
                    726: with an @samp{#}; e.g., in Gforth the return stack has the stack prefix
                    727: @samp{R:}.  This restriction is not checked during the stack prefix
                    728: definition, but it is enforced by the parsing rules for stack items
                    729: later.
                    730: 
1.3       anton     731: If you know Forth, the stack effects of the non-standard words involved
                    732: are:
1.12      anton     733: @findex stack
                    734: @findex type-prefix
                    735: @findex single
                    736: @findex double
                    737: @findex stack-prefix
1.18      anton     738: @findex store-optimization
1.3       anton     739: @example
1.18      anton     740: stack              ( "name" "pointer" "type" -- )
                    741:                    ( name execution: -- stack )
                    742: type-prefix        ( addr u item-size stack "prefix" -- )
                    743: single             ( -- item-size )
                    744: double             ( -- item-size )
                    745: stack-prefix       ( stack "prefix" -- )
                    746: store-optimization ( -- addr )
1.3       anton     747: @end example
                    748: 
1.14      anton     749: An @var{item-size} takes three cells on the stack.
1.5       anton     750: 
1.10      anton     751: @c --------------------------------------------------------------------
                    752: @node Simple instructions, Superinstructions, Input File Grammar, Input File Format
1.3       anton     753: @section Simple instructions
1.12      anton     754: @cindex simple VM instruction
                    755: @cindex instruction, simple VM
1.3       anton     756: 
                    757: We will use the following simple VM instruction description as example:
                    758: 
                    759: @example
                    760: sub ( i1 i2 -- i )
                    761: i = i1-i2;
                    762: @end example
                    763: 
                    764: The first line specifies the name of the VM instruction (@code{sub}) and
                    765: its stack effect (@code{i1 i2 -- i}).  The rest of the description is
                    766: just plain C code.
                    767: 
                    768: @cindex stack effect
1.12      anton     769: @cindex effect, stack
1.3       anton     770: The stack effect specifies that @code{sub} pulls two integers from the
1.12      anton     771: data stack and puts them in the C variables @code{i1} and @code{i2}
                    772: (with the rightmost item (@code{i2}) taken from the top of stack;
                    773: intuition: if you push @code{i1}, then @code{i2} on the stack, the
                    774: resulting stack picture is @code{i1 i2}) and later pushes one integer
                    775: (@code{i}) on the data stack (the rightmost item is on the top
                    776: afterwards).
                    777: 
                    778: @cindex prefix, type
                    779: @cindex type prefix
                    780: @cindex default stack of a type prefix
1.3       anton     781: How do we know the type and stack of the stack items?  Vmgen uses
                    782: prefixes, similar to Fortran; in contrast to Fortran, you have to
                    783: define the prefix first:
                    784: 
                    785: @example
                    786: \E s" Cell"   single data-stack type-prefix i
                    787: @end example
                    788: 
                    789: This defines the prefix @code{i} to refer to the type @code{Cell}
                    790: (defined as @code{long} in @file{mini.h}) and, by default, to the
                    791: @code{data-stack}.  It also specifies that this type takes one stack
                    792: item (@code{single}).  The type prefix is part of the variable name.
                    793: 
1.12      anton     794: @cindex stack definition
                    795: @cindex defining a stack
1.3       anton     796: Before we can use @code{data-stack} in this way, we have to define it:
                    797: 
                    798: @example
                    799: \E stack data-stack sp Cell
                    800: @end example
                    801: @c !! use something other than Cell
                    802: 
1.12      anton     803: @cindex stack basic type
                    804: @cindex basic type of a stack
                    805: @cindex type of a stack, basic
                    806: @cindex stack growth direction
1.3       anton     807: This line defines the stack @code{data-stack}, which uses the stack
                    808: pointer @code{sp}, and each item has the basic type @code{Cell}; other
                    809: types have to fit into one or two @code{Cell}s (depending on whether the
1.12      anton     810: type is @code{single} or @code{double} wide), and are cast from and to
                    811: Cells on accessing the @code{data-stack} with type cast macros
1.11      anton     812: (@pxref{VM engine}).  Stacks grow towards lower addresses in
                    813: Vmgen-erated interpreters.
1.3       anton     814: 
1.12      anton     815: @cindex stack prefix
                    816: @cindex prefix, stack
1.3       anton     817: We can override the default stack of a stack item by using a stack
                    818: prefix.  E.g., consider the following instruction:
                    819: 
                    820: @example
                    821: lit ( #i -- i )
                    822: @end example
                    823: 
                    824: The VM instruction @code{lit} takes the item @code{i} from the
1.5       anton     825: instruction stream (indicated by the prefix @code{#}), and pushes it on
1.3       anton     826: the (default) data stack.  The stack prefix is not part of the variable
                    827: name.  Stack prefixes are defined like this:
                    828: 
                    829: @example
                    830: \E inst-stream stack-prefix #
                    831: @end example
                    832: 
1.5       anton     833: This definition defines that the stack prefix @code{#} specifies the
1.3       anton     834: ``stack'' @code{inst-stream}.  Since the instruction stream behaves a
                    835: little differently than an ordinary stack, it is predefined, and you do
                    836: not need to define it.
                    837: 
1.12      anton     838: @cindex instruction stream
1.3       anton     839: The instruction stream contains instructions and their immediate
                    840: arguments, so specifying that an argument comes from the instruction
                    841: stream indicates an immediate argument.  Of course, instruction stream
                    842: arguments can only appear to the left of @code{--} in the stack effect.
                    843: If there are multiple instruction stream arguments, the leftmost is the
                    844: first one (just as the intuition suggests).
                    845: 
1.10      anton     846: @menu
                    847: * C Code Macros::               Macros recognized by Vmgen
                    848: * C Code restrictions::         Vmgen makes assumptions about C code
                    849: @end menu
                    850: 
                    851: @c --------------------------------------------------------------------
                    852: @node C Code Macros, C Code restrictions, Simple instructions, Simple instructions
                    853: @subsection C Code Macros
1.12      anton     854: @cindex macros recognized by Vmgen
                    855: @cindex basic block, VM level
1.5       anton     856: 
                    857: Vmgen recognizes the following strings in the C code part of simple
                    858: instructions:
                    859: 
1.12      anton     860: @table @code
1.5       anton     861: 
                    862: @item SET_IP
1.12      anton     863: @findex SET_IP
1.11      anton     864: As far as Vmgen is concerned, a VM instruction containing this ends a VM
1.5       anton     865: basic block (used in profiling to delimit profiled sequences).  On the C
                    866: level, this also sets the instruction pointer.
                    867: 
                    868: @item SUPER_END
1.12      anton     869: @findex SUPER_END
                    870: This ends a basic block (for profiling), even if the instruction
                    871: contains no @code{SET_IP}.
1.5       anton     872: 
1.13      anton     873: @item INST_TAIL;
                    874: @findex INST_TAIL;
                    875: Vmgen replaces @samp{INST_TAIL;} with code for ending a VM instruction and
                    876: dispatching the next VM instruction.  Even without a @samp{INST_TAIL;} this
1.12      anton     877: happens automatically when control reaches the end of the C code.  If
                    878: you want to have this in the middle of the C code, you need to use
1.13      anton     879: @samp{INST_TAIL;}.  A typical example is a conditional VM branch:
1.5       anton     880: 
                    881: @example
1.11      anton     882: if (branch_condition) @{
1.13      anton     883:   SET_IP(target); INST_TAIL;
1.11      anton     884: @}
1.5       anton     885: /* implicit tail follows here */
                    886: @end example
                    887: 
1.13      anton     888: In this example, @samp{INST_TAIL;} is not strictly necessary, because there
1.5       anton     889: is another one implicitly after the if-statement, but using it improves
                    890: branch prediction accuracy slightly and allows other optimizations.
                    891: 
                    892: @item SUPER_CONTINUE
1.12      anton     893: @findex SUPER_CONTINUE
1.5       anton     894: This indicates that the implicit tail at the end of the VM instruction
                    895: dispatches the sequentially next VM instruction even if there is a
                    896: @code{SET_IP} in the VM instruction.  This enables an optimization that
                    897: is not yet implemented in the vmgen-ex code (but in Gforth).  The
                    898: typical application is in conditional VM branches:
                    899: 
                    900: @example
1.11      anton     901: if (branch_condition) @{
1.13      anton     902:   SET_IP(target); INST_TAIL; /* now this INST_TAIL is necessary */
1.11      anton     903: @}
1.5       anton     904: SUPER_CONTINUE;
                    905: @end example
                    906: 
                    907: @end table
                    908: 
1.11      anton     909: Note that Vmgen is not smart about C-level tokenization, comments,
1.5       anton     910: strings, or conditional compilation, so it will interpret even a
                    911: commented-out SUPER_END as ending a basic block (or, e.g.,
1.13      anton     912: @samp{RESET_IP;} as @samp{SET_IP;}).  Conversely, Vmgen requires the literal
1.11      anton     913: presence of these strings; Vmgen will not see them if they are hiding in
1.5       anton     914: a C preprocessor macro.
                    915: 
                    916: 
1.10      anton     917: @c --------------------------------------------------------------------
                    918: @node C Code restrictions,  , C Code Macros, Simple instructions
                    919: @subsection C Code restrictions
1.12      anton     920: @cindex C code restrictions
                    921: @cindex restrictions on C code
                    922: @cindex assumptions about C code
                    923: 
                    924: @cindex accessing stack (pointer)
                    925: @cindex stack pointer, access
                    926: @cindex instruction pointer, access
1.5       anton     927: Vmgen generates code and performs some optimizations under the
                    928: assumption that the user-supplied C code does not access the stack
                    929: pointers or stack items, and that accesses to the instruction pointer
                    930: only occur through special macros.  In general you should heed these
                    931: restrictions.  However, if you need to break these restrictions, read
                    932: the following.
                    933: 
                    934: Accessing a stack or stack pointer directly can be a problem for several
                    935: reasons: 
1.12      anton     936: @cindex stack caching, restriction on C code
                    937: @cindex superinstructions, restrictions on components
1.5       anton     938: 
1.11      anton     939: @itemize @bullet
1.5       anton     940: 
                    941: @item
1.12      anton     942: Vmgen optionally supports caching the top-of-stack item in a local
                    943: variable (that is allocated to a register).  This is the most frequent
                    944: source of trouble.  You can deal with it either by not using
                    945: top-of-stack caching (slowdown factor 1-1.4, depending on machine), or
                    946: by inserting flushing code (e.g., @samp{IF_spTOS(sp[...] = spTOS);}) at
                    947: the start and reloading code (e.g., @samp{IF_spTOS(spTOS = sp[0])}) at
                    948: the end of problematic C code.  Vmgen inserts a stack pointer update
                    949: before the start of the user-supplied C code, so the flushing code has
                    950: to use an index that corrects for that.  In the future, this flushing
                    951: may be done automatically by mentioning a special string in the C code.
1.5       anton     952: @c sometimes flushing and/or reloading unnecessary
                    953: 
                    954: @item
1.11      anton     955: The Vmgen-erated code loads the stack items from stack-pointer-indexed
1.5       anton     956: memory into variables before the user-supplied C code, and stores them
                    957: from variables to stack-pointer-indexed memory afterwards.  If you do
                    958: any writes to the stack through its stack pointer in your C code, it
1.13      anton     959: will not affect the variables, and your write may be overwritten by the
1.5       anton     960: stores after the C code.  Similarly, a read from a stack using a stack
                    961: pointer will not reflect computations of stack items in the same VM
                    962: instruction.
                    963: 
                    964: @item
                    965: Superinstructions keep stack items in variables across the whole
                    966: superinstruction.  So you should not include VM instructions, that
1.12      anton     967: access a stack or stack pointer, as components of superinstructions
                    968: (@pxref{VM profiler}).
1.5       anton     969: 
                    970: @end itemize
                    971: 
                    972: You should access the instruction pointer only through its special
                    973: macros (@samp{IP}, @samp{SET_IP}, @samp{IPTOS}); this ensure that these
                    974: macros can be implemented in several ways for best performance.
                    975: @samp{IP} points to the next instruction, and @samp{IPTOS} is its
                    976: contents.
                    977: 
                    978: 
1.10      anton     979: @c --------------------------------------------------------------------
1.18      anton     980: @node Superinstructions, Store Optimization, Simple instructions, Input File Format
1.3       anton     981: @section Superinstructions
1.12      anton     982: @cindex superinstructions, defining
                    983: @cindex defining superinstructions
1.5       anton     984: 
1.8       anton     985: Note: don't invest too much work in (static) superinstructions; a future
1.11      anton     986: version of Vmgen will support dynamic superinstructions (see Ian
1.8       anton     987: Piumarta and Fabio Riccardi, @cite{Optimizing Direct Threaded Code by
                    988: Selective Inlining}, PLDI'98), and static superinstructions have much
1.12      anton     989: less benefit in that context (preliminary results indicate only a factor
                    990: 1.1 speedup).
1.8       anton     991: 
1.5       anton     992: Here is an example of a superinstruction definition:
                    993: 
                    994: @example
                    995: lit_sub = lit sub
                    996: @end example
                    997: 
                    998: @code{lit_sub} is the name of the superinstruction, and @code{lit} and
                    999: @code{sub} are its components.  This superinstruction performs the same
                   1000: action as the sequence @code{lit} and @code{sub}.  It is generated
                   1001: automatically by the VM code generation functions whenever that sequence
1.11      anton    1002: occurs, so if you want to use this superinstruction, you just need to
                   1003: add this definition (and even that can be partially automatized,
                   1004: @pxref{VM profiler}).
1.5       anton    1005: 
1.12      anton    1006: @cindex prefixes of superinstructions
1.5       anton    1007: Vmgen requires that the component instructions are simple instructions
1.11      anton    1008: defined before superinstructions using the components.  Currently, Vmgen
1.5       anton    1009: also requires that all the subsequences at the start of a
                   1010: superinstruction (prefixes) must be defined as superinstruction before
                   1011: the superinstruction.  I.e., if you want to define a superinstruction
                   1012: 
                   1013: @example
1.12      anton    1014: foo4 = load add sub mul
1.5       anton    1015: @end example
                   1016: 
1.12      anton    1017: you first have to define @code{load}, @code{add}, @code{sub} and
                   1018: @code{mul}, plus
1.5       anton    1019: 
                   1020: @example
1.12      anton    1021: foo2 = load add
                   1022: foo3 = load add sub
1.5       anton    1023: @end example
                   1024: 
                   1025: Here, @code{sumof4} is the longest prefix of @code{sumof5}, and @code{sumof3}
                   1026: is the longest prefix of @code{sumof4}.
                   1027: 
1.11      anton    1028: Note that Vmgen assumes that only the code it generates accesses stack
1.5       anton    1029: pointers, the instruction pointer, and various stack items, and it
                   1030: performs optimizations based on this assumption.  Therefore, VM
1.12      anton    1031: instructions where your C code changes the instruction pointer should
                   1032: only be used as last component; a VM instruction where your C code
                   1033: accesses a stack pointer should not be used as component at all.  Vmgen
                   1034: does not check these restrictions, they just result in bugs in your
                   1035: interpreter.
1.5       anton    1036: 
1.12      anton    1037: @c -------------------------------------------------------------------
1.18      anton    1038: @node  Store Optimization, Register Machines, Superinstructions, Input File Format
                   1039: @section Store Optimization
                   1040: @cindex store optimization
                   1041: @cindex optimization, stack stores
                   1042: @cindex stack stores, optimization
                   1043: @cindex eliminating stack stores
                   1044: 
                   1045: This minor optimization (0.6\%--0.8\% reduction in executed instructions
                   1046: for Gforth) puts additional requirements on the instruction descriptions
                   1047: and is therefore disabled by default.
                   1048: 
                   1049: What does it do?  Consider an instruction like
                   1050: 
                   1051: @example
                   1052: dup ( n -- n n )
                   1053: @end example
                   1054: 
                   1055: For simplicity, also assume that we are not caching the top-of-stack in
                   1056: a register.  Now, the C code for dup first loads @code{n} from the
                   1057: stack, and then stores it twice to the stack, one time to the address
                   1058: where it came from; that time is unnecessary, but gcc does not optimize
                   1059: it away, so vmgen can do it instead (if you turn on the store
                   1060: optimization).
                   1061: 
                   1062: Vmgen uses the stack item's name to determine if the stack item contains
                   1063: the same value as it did at the start.  Therefore, if you use the store
                   1064: optimization, you have to ensure that stack items that have the same
                   1065: name on input and output also have the same value, and are not changed
                   1066: in the C code you supply.  I.e., the following code could fail if you
                   1067: turn on the store optimization:
                   1068: 
                   1069: @example
                   1070: add1 ( n -- n )
                   1071: n++;
                   1072: @end example
                   1073: 
                   1074: Instead, you have to use different names, i.e.:
                   1075: 
                   1076: @example
                   1077: add1 ( n1 -- n1 )
                   1078: n2=n1+1;
                   1079: @end example
                   1080: 
                   1081: To turn on the store optimization, write
                   1082: 
                   1083: @example
                   1084: \E store-optimization on
                   1085: @end example
                   1086: 
                   1087: at the start of the file.  You can turn this optimization on or off
                   1088: between any two VM instruction descriptions.  For turning it off again,
                   1089: you can use
                   1090: 
                   1091: @example
                   1092: \E store-optimization off
                   1093: @end example
                   1094: 
                   1095: @c -------------------------------------------------------------------
                   1096: @node Register Machines,  , Store Optimization, Input File Format
1.11      anton    1097: @section Register Machines
1.12      anton    1098: @cindex Register VM
                   1099: @cindex Superinstructions for register VMs
                   1100: @cindex tracing of register VMs
1.11      anton    1101: 
                   1102: If you want to implement a register VM rather than a stack VM with
                   1103: Vmgen, there are two ways to do it: Directly and through
                   1104: superinstructions.
                   1105: 
                   1106: If you use the direct way, you define instructions that take the
                   1107: register numbers as immediate arguments, like this:
                   1108: 
                   1109: @example
                   1110: add3 ( #src1 #src2 #dest -- )
                   1111: reg[dest] = reg[src1]+reg[src2];
                   1112: @end example
                   1113: 
1.12      anton    1114: A disadvantage of this method is that during tracing you only see the
                   1115: register numbers, but not the register contents.  Actually, with an
                   1116: appropriate definition of @code{printarg_src} (@pxref{VM engine}), you
                   1117: can print the values of the source registers on entry, but you cannot
                   1118: print the value of the destination register on exit.
                   1119: 
1.11      anton    1120: If you use superinstructions to define a register VM, you define simple
                   1121: instructions that use a stack, and then define superinstructions that
                   1122: have no overall stack effect, like this:
                   1123: 
                   1124: @example
                   1125: loadreg ( #src -- n )
                   1126: n = reg[src];
                   1127: 
                   1128: storereg ( n #dest -- )
                   1129: reg[dest] = n;
                   1130: 
                   1131: adds ( n1 n2 -- n )
                   1132: n = n1+n2;
                   1133: 
                   1134: add3 = loadreg loadreg adds storereg
                   1135: @end example
                   1136: 
                   1137: An advantage of this method is that you see the values and not just the
1.12      anton    1138: register numbers in tracing.  A disadvantage of this method is that
1.11      anton    1139: currently you cannot generate superinstructions directly, but only
                   1140: through generating a sequence of simple instructions (we might change
                   1141: this in the future if there is demand).
                   1142: 
                   1143: Could the register VM support be improved, apart from the issues
                   1144: mentioned above?  It is hard to see how to do it in a general way,
                   1145: because there are a number of different designs that different people
                   1146: mean when they use the term @emph{register machine} in connection with
                   1147: VM interpreters.  However, if you have ideas or requests in that
                   1148: direction, please let me know (@pxref{Contact}).
                   1149: 
1.5       anton    1150: @c ********************************************************************
1.13      anton    1151: @node Error messages, Using the generated code, Input File Format, Top
                   1152: @chapter Error messages
                   1153: @cindex error messages
                   1154: 
                   1155: These error messages are created by Vmgen:
                   1156: 
                   1157: @table @code
                   1158: 
                   1159: @cindex @code{# can only be on the input side} error
                   1160: @item # can only be on the input side
                   1161: You have used an instruction-stream prefix (usually @samp{#}) after the
                   1162: @samp{--} (the output side); you can only use it before (the input
                   1163: side).
                   1164: 
                   1165: @cindex @code{prefix for this combination must be defined earlier} error
1.20      anton    1166: @item the prefix for this superinstruction must be defined earlier
1.13      anton    1167: You have defined a superinstruction (e.g. @code{abc = a b c}) without
                   1168: defining its direct prefix (e.g., @code{ab = a b}),
                   1169: @xref{Superinstructions}.
                   1170: 
                   1171: @cindex @code{sync line syntax} error
                   1172: @item sync line syntax
                   1173: If you are using a preprocessor (e.g., @command{m4}) to generate Vmgen
                   1174: input code, you may want to create @code{#line} directives (aka sync
                   1175: lines).  This error indicates that such a line is not in th syntax
1.16      anton    1176: expected by Vmgen (this should not happen; please report the offending
                   1177: line in a bug report).
1.13      anton    1178: 
                   1179: @cindex @code{syntax error, wrong char} error
                   1180: @cindex syntax error, wrong char
1.16      anton    1181: A syntax error.  If you do not see right away where the error is, it may
                   1182: be helpful to check the following: Did you put an empty line in a VM
                   1183: instruction where the C code is not delimited by braces (then the empty
                   1184: line ends the VM instruction)?  If you used brace-delimited C code, did
                   1185: you put the delimiting braces (and only those) at the start of the line,
                   1186: without preceding white space?  Did you forget a delimiting brace?
1.13      anton    1187: 
                   1188: @cindex @code{too many stacks} error
                   1189: @item too many stacks
1.16      anton    1190: Vmgen currently supports 3 stacks (plus the instruction stream); if you
                   1191: need more, let us know.
1.13      anton    1192: 
                   1193: @cindex @code{unknown prefix} error
                   1194: @item unknown prefix
                   1195: The stack item does not match any defined type prefix (after stripping
                   1196: away any stack prefix).  You should either declare the type prefix you
                   1197: want for that stack item, or use a different type prefix
                   1198: 
                   1199: @item @code{unknown primitive} error
                   1200: @item unknown primitive
                   1201: You have used the name of a simple VM instruction in a superinstruction
                   1202: definition without defining the simple VM instruction first.
                   1203: 
                   1204: @end table
                   1205: 
                   1206: In addition, the C compiler can produce errors due to code produced by
                   1207: Vmgen; e.g., you need to define type cast functions.
                   1208: 
                   1209: @c ********************************************************************
                   1210: @node Using the generated code, Hints, Error messages, Top
1.5       anton    1211: @chapter Using the generated code
1.12      anton    1212: @cindex generated code, usage
                   1213: @cindex Using vmgen-erated code
1.5       anton    1214: 
1.11      anton    1215: The easiest way to create a working VM interpreter with Vmgen is
1.12      anton    1216: probably to start with @file{vmgen-ex}, and modify it for your purposes.
1.13      anton    1217: This chapter explains what the various wrapper and generated files do.
                   1218: It also contains reference-manual style descriptions of the macros,
                   1219: variables etc. used by the generated code, and you can skip that on
                   1220: first reading.
1.5       anton    1221: 
1.10      anton    1222: @menu
                   1223: * VM engine::                   Executing VM code
                   1224: * VM instruction table::        
                   1225: * VM code generation::          Creating VM code (in the front-end)
                   1226: * Peephole optimization::       Creating VM superinstructions
                   1227: * VM disassembler::             for debugging the front end
                   1228: * VM profiler::                 for finding worthwhile superinstructions
                   1229: @end menu
1.6       anton    1230: 
1.10      anton    1231: @c --------------------------------------------------------------------
                   1232: @node VM engine, VM instruction table, Using the generated code, Using the generated code
1.5       anton    1233: @section VM engine
1.12      anton    1234: @cindex VM instruction execution
                   1235: @cindex engine
                   1236: @cindex executing VM code
                   1237: @cindex @file{engine.c}
                   1238: @cindex @file{-vm.i} output file
1.5       anton    1239: 
                   1240: The VM engine is the VM interpreter that executes the VM code.  It is
                   1241: essential for an interpretive system.
                   1242: 
1.6       anton    1243: Vmgen supports two methods of VM instruction dispatch: @emph{threaded
                   1244: code} (fast, but gcc-specific), and @emph{switch dispatch} (slow, but
                   1245: portable across C compilers); you can use conditional compilation
                   1246: (@samp{defined(__GNUC__)}) to choose between these methods, and our
                   1247: example does so.
                   1248: 
                   1249: For both methods, the VM engine is contained in a C-level function.
                   1250: Vmgen generates most of the contents of the function for you
                   1251: (@file{@var{name}-vm.i}), but you have to define this function, and
                   1252: macros and variables used in the engine, and initialize the variables.
                   1253: In our example the engine function also includes
                   1254: @file{@var{name}-labels.i} (@pxref{VM instruction table}).
                   1255: 
1.12      anton    1256: @cindex tracing VM code
1.13      anton    1257: @cindex superinstructions and tracing
1.12      anton    1258: In addition to executing the code, the VM engine can optionally also
                   1259: print out a trace of the executed instructions, their arguments and
                   1260: results.  For superinstructions it prints the trace as if only component
                   1261: instructions were executed; this allows to introduce new
                   1262: superinstructions while keeping the traces comparable to old ones
                   1263: (important for regression tests).
                   1264: 
                   1265: It costs significant performance to check in each instruction whether to
                   1266: print tracing code, so we recommend producing two copies of the engine:
                   1267: one for fast execution, and one for tracing.  See the rules for
                   1268: @file{engine.o} and @file{engine-debug.o} in @file{vmgen-ex/Makefile}
                   1269: for an example.
                   1270: 
1.6       anton    1271: The following macros and variables are used in @file{@var{name}-vm.i}:
1.5       anton    1272: 
                   1273: @table @code
                   1274: 
1.12      anton    1275: @findex LABEL
1.5       anton    1276: @item LABEL(@var{inst_name})
                   1277: This is used just before each VM instruction to provide a jump or
1.11      anton    1278: @code{switch} label (the @samp{:} is provided by Vmgen).  For switch
1.13      anton    1279: dispatch this should expand to @samp{case @var{label}:}; for
                   1280: threaded-code dispatch this should just expand to @samp{@var{label}:}.
1.12      anton    1281: In either case @var{label} is usually the @var{inst_name} with some
                   1282: prefix or suffix to avoid naming conflicts.
1.5       anton    1283: 
1.12      anton    1284: @findex LABEL2
1.9       anton    1285: @item LABEL2(@var{inst_name})
                   1286: This will be used for dynamic superinstructions; at the moment, this
                   1287: should expand to nothing.
                   1288: 
1.12      anton    1289: @findex NAME
1.5       anton    1290: @item NAME(@var{inst_name_string})
                   1291: Called on entering a VM instruction with a string containing the name of
1.13      anton    1292: the VM instruction as parameter.  In normal execution this should be
                   1293: expand to nothing, but for tracing this usually prints the name, and
                   1294: possibly other information (several VM registers in our example).
1.5       anton    1295: 
1.12      anton    1296: @findex DEF_CA
1.5       anton    1297: @item DEF_CA
                   1298: Usually empty.  Called just inside a new scope at the start of a VM
                   1299: instruction.  Can be used to define variables that should be visible
                   1300: during every VM instruction.  If you define this macro as non-empty, you
                   1301: have to provide the finishing @samp{;} in the macro.
                   1302: 
1.12      anton    1303: @findex NEXT_P0
                   1304: @findex NEXT_P1
                   1305: @findex NEXT_P2
1.5       anton    1306: @item NEXT_P0 NEXT_P1 NEXT_P2
                   1307: The three parts of instruction dispatch.  They can be defined in
                   1308: different ways for best performance on various processors (see
                   1309: @file{engine.c} in the example or @file{engine/threaded.h} in Gforth).
1.12      anton    1310: @samp{NEXT_P0} is invoked right at the start of the VM instruction (but
1.5       anton    1311: after @samp{DEF_CA}), @samp{NEXT_P1} right after the user-supplied C
                   1312: code, and @samp{NEXT_P2} at the end.  The actual jump has to be
1.13      anton    1313: performed by @samp{NEXT_P2} (if you would do it earlier, important parts
                   1314: of the VM instruction would not be executed).
1.5       anton    1315: 
                   1316: The simplest variant is if @samp{NEXT_P2} does everything and the other
                   1317: macros do nothing.  Then also related macros like @samp{IP},
                   1318: @samp{SET_IP}, @samp{IP}, @samp{INC_IP} and @samp{IPTOS} are very
                   1319: straightforward to define.  For switch dispatch this code consists just
1.12      anton    1320: of a jump to the dispatch code (@samp{goto next_inst;} in our example);
1.5       anton    1321: for direct threaded code it consists of something like
1.11      anton    1322: @samp{(@{cfa=*ip++; goto *cfa;@})}.
1.5       anton    1323: 
1.12      anton    1324: Pulling code (usually the @samp{cfa=*ip++;}) up into @samp{NEXT_P1}
1.5       anton    1325: usually does not cause problems, but pulling things up into
                   1326: @samp{NEXT_P0} usually requires changing the other macros (and, at least
                   1327: for Gforth on Alpha, it does not buy much, because the compiler often
                   1328: manages to schedule the relevant stuff up by itself).  An even more
                   1329: extreme variant is to pull code up even further, into, e.g., NEXT_P1 of
                   1330: the previous VM instruction (prefetching, useful on PowerPCs).
                   1331: 
1.12      anton    1332: @findex INC_IP
1.5       anton    1333: @item INC_IP(@var{n})
1.8       anton    1334: This increments @code{IP} by @var{n}.
                   1335: 
1.12      anton    1336: @findex SET_IP
1.8       anton    1337: @item SET_IP(@var{target})
                   1338: This sets @code{IP} to @var{target}.
1.5       anton    1339: 
1.12      anton    1340: @cindex type cast macro
                   1341: @findex vm_@var{A}2@var{B}
1.5       anton    1342: @item vm_@var{A}2@var{B}(a,b)
                   1343: Type casting macro that assigns @samp{a} (of type @var{A}) to @samp{b}
                   1344: (of type @var{B}).  This is mainly used for getting stack items into
                   1345: variables and back.  So you need to define macros for every combination
                   1346: of stack basic type (@code{Cell} in our example) and type-prefix types
                   1347: used with that stack (in both directions).  For the type-prefix type,
                   1348: you use the type-prefix (not the C type string) as type name (e.g.,
                   1349: @samp{vm_Cell2i}, not @samp{vm_Cell2Cell}).  In addition, you have to
1.12      anton    1350: define a vm_@var{X}2@var{X} macro for the stack's basic type @var{X}
                   1351: (used in superinstructions).
1.5       anton    1352: 
1.12      anton    1353: @cindex instruction stream, basic type
1.5       anton    1354: The stack basic type for the predefined @samp{inst-stream} is
                   1355: @samp{Cell}.  If you want a stack with the same item size, making its
                   1356: basic type @samp{Cell} usually reduces the number of macros you have to
                   1357: define.
                   1358: 
1.12      anton    1359: @cindex unions in type cast macros
                   1360: @cindex casts in type cast macros
                   1361: @cindex type casting between floats and integers
1.5       anton    1362: Here our examples differ a lot: @file{vmgen-ex} uses casts in these
                   1363: macros, whereas @file{vmgen-ex2} uses union-field selection (or
1.12      anton    1364: assignment to union fields).  Note that casting floats into integers and
                   1365: vice versa changes the bit pattern (and you do not want that).  In this
                   1366: case your options are to use a (temporary) union, or to take the address
                   1367: of the value, cast the pointer, and dereference that (not always
                   1368: possible, and sometimes expensive).
1.5       anton    1369: 
1.12      anton    1370: @findex vm_two@var{A}2@var{B}
                   1371: @findex vm_@var{B}2two@var{A}
1.5       anton    1372: @item vm_two@var{A}2@var{B}(a1,a2,b)
                   1373: @item vm_@var{B}2two@var{A}(b,a1,a2)
1.12      anton    1374: Type casting between two stack items (@code{a1}, @code{a2}) and a
1.5       anton    1375: variable @code{b} of a type that takes two stack items.  This does not
1.12      anton    1376: occur in our small examples, but you can look at Gforth for examples
                   1377: (see @code{vm_twoCell2d} in @file{engine/forth.h}).
1.5       anton    1378: 
1.12      anton    1379: @cindex stack pointer definition
                   1380: @cindex instruction pointer definition
1.5       anton    1381: @item @var{stackpointer}
                   1382: For each stack used, the stackpointer name given in the stack
                   1383: declaration is used.  For a regular stack this must be an l-expression;
                   1384: typically it is a variable declared as a pointer to the stack's basic
                   1385: type.  For @samp{inst-stream}, the name is @samp{IP}, and it can be a
                   1386: plain r-value; typically it is a macro that abstracts away the
1.12      anton    1387: differences between the various implementations of @code{NEXT_P*}.
1.5       anton    1388: 
1.12      anton    1389: @cindex top of stack caching
                   1390: @cindex stack caching
                   1391: @cindex TOS
                   1392: @findex IPTOS
1.5       anton    1393: @item @var{stackpointer}TOS
                   1394: The top-of-stack for the stack pointed to by @var{stackpointer}.  If you
                   1395: are using top-of-stack caching for that stack, this should be defined as
                   1396: variable; if you are not using top-of-stack caching for that stack, this
                   1397: should be a macro expanding to @samp{@var{stackpointer}[0]}.  The stack
                   1398: pointer for the predefined @samp{inst-stream} is called @samp{IP}, so
                   1399: the top-of-stack is called @samp{IPTOS}.
                   1400: 
1.12      anton    1401: @findex IF_@var{stackpointer}TOS
1.5       anton    1402: @item IF_@var{stackpointer}TOS(@var{expr})
                   1403: Macro for executing @var{expr}, if top-of-stack caching is used for the
                   1404: @var{stackpointer} stack.  I.e., this should do @var{expr} if there is
                   1405: top-of-stack caching for @var{stackpointer}; otherwise it should do
                   1406: nothing.
                   1407: 
1.12      anton    1408: @findex SUPER_END
1.8       anton    1409: @item SUPER_END
                   1410: This is used by the VM profiler (@pxref{VM profiler}); it should not do
                   1411: anything in normal operation, and call @code{vm_count_block(IP)} for
                   1412: profiling.
                   1413: 
1.12      anton    1414: @findex SUPER_CONTINUE
1.8       anton    1415: @item SUPER_CONTINUE
1.11      anton    1416: This is just a hint to Vmgen and does nothing at the C level.
1.8       anton    1417: 
1.12      anton    1418: @findex VM_DEBUG
1.5       anton    1419: @item VM_DEBUG
                   1420: If this is defined, the tracing code will be compiled in (slower
                   1421: interpretation, but better debugging).  Our example compiles two
                   1422: versions of the engine, a fast-running one that cannot trace, and one
                   1423: with potential tracing and profiling.
                   1424: 
1.12      anton    1425: @findex vm_debug
1.5       anton    1426: @item vm_debug
                   1427: Needed only if @samp{VM_DEBUG} is defined.  If this variable contains
                   1428: true, the VM instructions produce trace output.  It can be turned on or
                   1429: off at any time.
                   1430: 
1.12      anton    1431: @findex vm_out
1.5       anton    1432: @item vm_out
                   1433: Needed only if @samp{VM_DEBUG} is defined.  Specifies the file on which
                   1434: to print the trace output (type @samp{FILE *}).
                   1435: 
1.12      anton    1436: @findex printarg_@var{type}
1.5       anton    1437: @item printarg_@var{type}(@var{value})
                   1438: Needed only if @samp{VM_DEBUG} is defined.  Macro or function for
                   1439: printing @var{value} in a way appropriate for the @var{type}.  This is
                   1440: used for printing the values of stack items during tracing.  @var{Type}
                   1441: is normally the type prefix specified in a @code{type-prefix} definition
                   1442: (e.g., @samp{printarg_i}); in superinstructions it is currently the
                   1443: basic type of the stack.
                   1444: 
                   1445: @end table
                   1446: 
1.6       anton    1447: 
1.10      anton    1448: @c --------------------------------------------------------------------
                   1449: @node VM instruction table, VM code generation, VM engine, Using the generated code
                   1450: @section VM instruction table
1.12      anton    1451: @cindex instruction table
                   1452: @cindex opcode definition
                   1453: @cindex labels for threaded code
                   1454: @cindex @code{vm_prim}, definition
                   1455: @cindex @file{-labels.i} output file
1.6       anton    1456: 
                   1457: For threaded code we also need to produce a table containing the labels
                   1458: of all VM instructions.  This is needed for VM code generation
                   1459: (@pxref{VM code generation}), and it has to be done in the engine
                   1460: function, because the labels are not visible outside.  It then has to be
                   1461: passed outside the function (and assigned to @samp{vm_prim}), to be used
                   1462: by the VM code generation functions.
                   1463: 
                   1464: This means that the engine function has to be called first to produce
                   1465: the VM instruction table, and later, after generating VM code, it has to
                   1466: be called again to execute the generated VM code (yes, this is ugly).
                   1467: In our example program, these two modes of calling the engine function
                   1468: are differentiated by the value of the parameter ip0 (if it equals 0,
                   1469: then the table is passed out, otherwise the VM code is executed); in our
                   1470: example, we pass the table out by assigning it to @samp{vm_prim} and
                   1471: returning from @samp{engine}.
                   1472: 
1.12      anton    1473: In our example (@file{vmgen-ex/engine.c}), we also build such a table for
                   1474: switch dispatch; this is mainly done for uniformity.
1.6       anton    1475: 
                   1476: For switch dispatch, we also need to define the VM instruction opcodes
                   1477: used as case labels in an @code{enum}.
                   1478: 
                   1479: For both purposes (VM instruction table, and enum), the file
1.11      anton    1480: @file{@var{name}-labels.i} is generated by Vmgen.  You have to define
1.6       anton    1481: the following macro used in this file:
1.5       anton    1482: 
1.12      anton    1483: @table @code
1.5       anton    1484: 
1.12      anton    1485: @findex INST_ADDR
1.5       anton    1486: @item INST_ADDR(@var{inst_name})
                   1487: For switch dispatch, this is just the name of the switch label (the same
1.6       anton    1488: name as used in @samp{LABEL(@var{inst_name})}), for both uses of
                   1489: @file{@var{name}-labels.i}.  For threaded-code dispatch, this is the
                   1490: address of the label defined in @samp{LABEL(@var{inst_name})}); the
1.11      anton    1491: address is taken with @samp{&&} (@pxref{Labels as Values, , Labels as
                   1492: Values, gcc.info, GNU C Manual}).
1.5       anton    1493: 
                   1494: @end table
                   1495: 
                   1496: 
1.10      anton    1497: @c --------------------------------------------------------------------
                   1498: @node VM code generation, Peephole optimization, VM instruction table, Using the generated code
1.6       anton    1499: @section VM code generation
1.12      anton    1500: @cindex VM code generation
                   1501: @cindex code generation, VM
                   1502: @cindex @file{-gen.i} output file
1.6       anton    1503: 
                   1504: Vmgen generates VM code generation functions in @file{@var{name}-gen.i}
                   1505: that the front end can call to generate VM code.  This is essential for
                   1506: an interpretive system.
                   1507: 
1.12      anton    1508: @findex gen_@var{inst}
1.11      anton    1509: For a VM instruction @samp{x ( #a b #c -- d )}, Vmgen generates a
1.6       anton    1510: function with the prototype
                   1511: 
                   1512: @example
                   1513: void gen_x(Inst **ctp, a_type a, c_type c)
                   1514: @end example
                   1515: 
                   1516: The @code{ctp} argument points to a pointer to the next instruction.
                   1517: @code{*ctp} is increased by the generation functions; i.e., you should
                   1518: allocate memory for the code to be generated beforehand, and start with
                   1519: *ctp set at the start of this memory area.  Before running out of
                   1520: memory, allocate a new area, and generate a VM-level jump to the new
1.12      anton    1521: area (this overflow handling is not implemented in our examples).
1.6       anton    1522: 
1.12      anton    1523: @cindex immediate arguments, VM code generation
1.6       anton    1524: The other arguments correspond to the immediate arguments of the VM
                   1525: instruction (with their appropriate types as defined in the
                   1526: @code{type_prefix} declaration.
                   1527: 
                   1528: The following types, variables, and functions are used in
                   1529: @file{@var{name}-gen.i}:
                   1530: 
1.12      anton    1531: @table @code
1.6       anton    1532: 
1.12      anton    1533: @findex Inst
1.6       anton    1534: @item Inst
                   1535: The type of the VM instruction; if you use threaded code, this is
                   1536: @code{void *}; for switch dispatch this is an integer type.
                   1537: 
1.12      anton    1538: @cindex @code{vm_prim}, use
1.6       anton    1539: @item vm_prim
                   1540: The VM instruction table (type: @code{Inst *}, @pxref{VM instruction table}).
                   1541: 
1.12      anton    1542: @findex gen_inst
1.6       anton    1543: @item gen_inst(Inst **ctp, Inst i)
                   1544: This function compiles the instruction @code{i}.  Take a look at it in
                   1545: @file{vmgen-ex/peephole.c}.  It is trivial when you don't want to use
                   1546: superinstructions (just the last two lines of the example function), and
                   1547: slightly more complicated in the example due to its ability to use
                   1548: superinstructions (@pxref{Peephole optimization}).
                   1549: 
1.12      anton    1550: @findex genarg_@var{type_prefix}
1.6       anton    1551: @item genarg_@var{type_prefix}(Inst **ctp, @var{type} @var{type_prefix})
                   1552: This compiles an immediate argument of @var{type} (as defined in a
                   1553: @code{type-prefix} definition).  These functions are trivial to define
                   1554: (see @file{vmgen-ex/support.c}).  You need one of these functions for
                   1555: every type that you use as immediate argument.
                   1556: 
                   1557: @end table
                   1558: 
1.12      anton    1559: @findex BB_BOUNDARY
1.6       anton    1560: In addition to using these functions to generate code, you should call
                   1561: @code{BB_BOUNDARY} at every basic block entry point if you ever want to
                   1562: use superinstructions (or if you want to use the profiling supported by
1.12      anton    1563: Vmgen; but this support is also useful mainly for selecting
                   1564: superinstructions).  If you use @code{BB_BOUNDARY}, you should also
                   1565: define it (take a look at its definition in @file{vmgen-ex/mini.y}).
1.6       anton    1566: 
                   1567: You do not need to call @code{BB_BOUNDARY} after branches, because you
                   1568: will not define superinstructions that contain branches in the middle
                   1569: (and if you did, and it would work, there would be no reason to end the
                   1570: superinstruction at the branch), and because the branches announce
                   1571: themselves to the profiler.
                   1572: 
                   1573: 
1.10      anton    1574: @c --------------------------------------------------------------------
                   1575: @node Peephole optimization, VM disassembler, VM code generation, Using the generated code
1.6       anton    1576: @section Peephole optimization
1.12      anton    1577: @cindex peephole optimization
                   1578: @cindex superinstructions, generating
                   1579: @cindex @file{peephole.c}
                   1580: @cindex @file{-peephole.i} output file
1.6       anton    1581: 
                   1582: You need peephole optimization only if you want to use
                   1583: superinstructions.  But having the code for it does not hurt much if you
                   1584: do not use superinstructions.
                   1585: 
                   1586: A simple greedy peephole optimization algorithm is used for
                   1587: superinstruction selection: every time @code{gen_inst} compiles a VM
1.12      anton    1588: instruction, it checks if it can combine it with the last VM instruction
1.6       anton    1589: (which may also be a superinstruction resulting from a previous peephole
                   1590: optimization); if so, it changes the last instruction to the combined
                   1591: instruction instead of laying down @code{i} at the current @samp{*ctp}.
                   1592: 
                   1593: The code for peephole optimization is in @file{vmgen-ex/peephole.c}.
                   1594: You can use this file almost verbatim.  Vmgen generates
                   1595: @file{@var{file}-peephole.i} which contains data for the peephoile
                   1596: optimizer.
                   1597: 
1.12      anton    1598: @findex init_peeptable
1.6       anton    1599: You have to call @samp{init_peeptable()} after initializing
                   1600: @samp{vm_prim}, and before compiling any VM code to initialize data
                   1601: structures for peephole optimization.  After that, compiling with the VM
                   1602: code generation functions will automatically combine VM instructions
                   1603: into superinstructions.  Since you do not want to combine instructions
                   1604: across VM branch targets (otherwise there will not be a proper VM
                   1605: instruction to branch to), you have to call @code{BB_BOUNDARY}
                   1606: (@pxref{VM code generation}) at branch targets.
                   1607: 
                   1608: 
1.10      anton    1609: @c --------------------------------------------------------------------
                   1610: @node VM disassembler, VM profiler, Peephole optimization, Using the generated code
1.6       anton    1611: @section VM disassembler
1.12      anton    1612: @cindex VM disassembler
                   1613: @cindex disassembler, VM code
                   1614: @cindex @file{disasm.c}
                   1615: @cindex @file{-disasm.i} output file
1.6       anton    1616: 
                   1617: A VM code disassembler is optional for an interpretive system, but
                   1618: highly recommended during its development and maintenance, because it is
                   1619: very useful for detecting bugs in the front end (and for distinguishing
                   1620: them from VM interpreter bugs).
                   1621: 
                   1622: Vmgen supports VM code disassembling by generating
                   1623: @file{@var{file}-disasm.i}.  This code has to be wrapped into a
1.12      anton    1624: function, as is done in @file{vmgen-ex/disasm.c}.  You can use this file
1.6       anton    1625: almost verbatim.  In addition to @samp{vm_@var{A}2@var{B}(a,b)},
                   1626: @samp{vm_out}, @samp{printarg_@var{type}(@var{value})}, which are
                   1627: explained above, the following macros and variables are used in
                   1628: @file{@var{file}-disasm.i} (and you have to define them):
                   1629: 
1.12      anton    1630: @table @code
1.6       anton    1631: 
                   1632: @item ip
                   1633: This variable points to the opcode of the current VM instruction.
                   1634: 
1.12      anton    1635: @cindex @code{IP}, @code{IPTOS} in disassmbler
1.6       anton    1636: @item IP IPTOS
                   1637: @samp{IPTOS} is the first argument of the current VM instruction, and
                   1638: @samp{IP} points to it; this is just as in the engine, but here
                   1639: @samp{ip} points to the opcode of the VM instruction (in contrast to the
                   1640: engine, where @samp{ip} points to the next cell, or even one further).
                   1641: 
1.12      anton    1642: @findex VM_IS_INST
1.6       anton    1643: @item VM_IS_INST(Inst i, int n)
                   1644: Tests if the opcode @samp{i} is the same as the @samp{n}th entry in the
                   1645: VM instruction table.
                   1646: 
                   1647: @end table
                   1648: 
                   1649: 
1.10      anton    1650: @c --------------------------------------------------------------------
                   1651: @node VM profiler,  , VM disassembler, Using the generated code
1.7       anton    1652: @section VM profiler
1.12      anton    1653: @cindex VM profiler
                   1654: @cindex profiling for selecting superinstructions
                   1655: @cindex superinstructions and profiling
                   1656: @cindex @file{profile.c}
                   1657: @cindex @file{-profile.i} output file
1.7       anton    1658: 
                   1659: The VM profiler is designed for getting execution and occurence counts
                   1660: for VM instruction sequences, and these counts can then be used for
                   1661: selecting sequences as superinstructions.  The VM profiler is probably
1.8       anton    1662: not useful as profiling tool for the interpretive system.  I.e., the VM
1.7       anton    1663: profiler is useful for the developers, but not the users of the
1.8       anton    1664: interpretive system.
1.7       anton    1665: 
1.8       anton    1666: The output of the profiler is: for each basic block (executed at least
                   1667: once), it produces the dynamic execution count of that basic block and
                   1668: all its subsequences; e.g.,
1.7       anton    1669: 
1.8       anton    1670: @example
                   1671:        9227465  lit storelocal 
                   1672:        9227465  storelocal branch 
                   1673:        9227465  lit storelocal branch 
                   1674: @end example
1.7       anton    1675: 
1.8       anton    1676: I.e., a basic block consisting of @samp{lit storelocal branch} is
                   1677: executed 9227465 times.
1.6       anton    1678: 
1.12      anton    1679: @cindex @file{stat.awk}
                   1680: @cindex @file{seq2rule.awk}
1.8       anton    1681: This output can be combined in various ways.  E.g.,
1.12      anton    1682: @file{vmgen-ex/stat.awk} adds up the occurences of a given sequence wrt
1.8       anton    1683: dynamic execution, static occurence, and per-program occurence.  E.g.,
1.3       anton    1684: 
1.8       anton    1685: @example
                   1686:       2      16        36910041 loadlocal lit 
                   1687: @end example
1.2       anton    1688: 
1.12      anton    1689: @noindent
1.8       anton    1690: indicates that the sequence @samp{loadlocal lit} occurs in 2 programs,
                   1691: in 16 places, and has been executed 36910041 times.  Now you can select
                   1692: superinstructions in any way you like (note that compile time and space
                   1693: typically limit the number of superinstructions to 100--1000).  After
                   1694: you have done that, @file{vmgen/seq2rule.awk} turns lines of the form
1.11      anton    1695: above into rules for inclusion in a Vmgen input file.  Note that this
1.8       anton    1696: script does not ensure that all prefixes are defined, so you have to do
                   1697: that in other ways.  So, an overall script for turning profiles into
                   1698: superinstructions can look like this:
1.2       anton    1699: 
1.8       anton    1700: @example
                   1701: awk -f stat.awk fib.prof test.prof|
                   1702: awk '$3>=10000'|                #select sequences
                   1703: fgrep -v -f peephole-blacklist| #eliminate wrong instructions
                   1704: awk -f seq2rule.awk|            #turn into superinstructions
                   1705: sort -k 3 >mini-super.vmg       #sort sequences
                   1706: @end example
1.2       anton    1707: 
1.8       anton    1708: Here the dynamic count is used for selecting sequences (preliminary
                   1709: results indicate that the static count gives better results, though);
1.12      anton    1710: the third line eliminates sequences containing instructions that must not
1.8       anton    1711: occur in a superinstruction, because they access a stack directly.  The
                   1712: dynamic count selection ensures that all subsequences (including
                   1713: prefixes) of longer sequences occur (because subsequences have at least
                   1714: the same count as the longer sequences); the sort in the last line
                   1715: ensures that longer superinstructions occur after their prefixes.
                   1716: 
1.12      anton    1717: But before using this, you have to have the profiler.  Vmgen supports its
1.8       anton    1718: creation by generating @file{@var{file}-profile.i}; you also need the
                   1719: wrapper file @file{vmgen-ex/profile.c} that you can use almost verbatim.
                   1720: 
1.12      anton    1721: @cindex @code{SUPER_END} in profiling
                   1722: @cindex @code{BB_BOUNDARY} in profiling
1.8       anton    1723: The profiler works by recording the targets of all VM control flow
                   1724: changes (through @code{SUPER_END} during execution, and through
                   1725: @code{BB_BOUNDARY} in the front end), and counting (through
                   1726: @code{SUPER_END}) how often they were targeted.  After the program run,
                   1727: the numbers are corrected such that each VM basic block has the correct
1.12      anton    1728: count (entering a block without executing a branch does not increase the
                   1729: count, and the correction fixes that), then the subsequences of all
                   1730: basic blocks are printed.  To get all this, you just have to define
                   1731: @code{SUPER_END} (and @code{BB_BOUNDARY}) appropriately, and call
                   1732: @code{vm_print_profile(FILE *file)} when you want to output the profile
                   1733: on @code{file}.
1.8       anton    1734: 
1.12      anton    1735: @cindex @code{VM_IS_INST} in profiling
                   1736: The @file{@var{file}-profile.i} is similar to the disassembler file, and
1.8       anton    1737: it uses variables and functions defined in @file{vmgen-ex/profile.c},
                   1738: plus @code{VM_IS_INST} already defined for the VM disassembler
                   1739: (@pxref{VM disassembler}).
                   1740: 
1.13      anton    1741: @c **********************************************************
                   1742: @node Hints, The future, Using the generated code, Top
                   1743: @chapter Hints
                   1744: @cindex hints
                   1745: 
                   1746: @menu
                   1747: * Floating point::              and stacks
                   1748: @end menu
                   1749: 
                   1750: @c --------------------------------------------------------------------
                   1751: @node Floating point,  , Hints, Hints
                   1752: @section Floating point
                   1753: 
                   1754: How should you deal with floating point values?  Should you use the same
                   1755: stack as for integers/pointers, or a different one?  This section
                   1756: discusses this issue with a view on execution speed.
                   1757: 
                   1758: The simpler approach is to use a separate floating-point stack.  This
                   1759: allows you to choose FP value size without considering the size of the
                   1760: integers/pointers, and you avoid a number of performance problems.  The
                   1761: main downside is that this needs an FP stack pointer (and that may not
                   1762: fit in the register file on the 386 arhitecture, costing some
                   1763: performance, but comparatively little if you take the other option into
                   1764: account).  If you use a separate FP stack (with stack pointer @code{fp}),
                   1765: using an fpTOS is helpful on most machines, but some spill the fpTOS
                   1766: register into memory, and fpTOS should not be used there.
                   1767: 
                   1768: The other approach is to share one stack (pointed to by, say, @code{sp})
                   1769: between integer/pointer and floating-point values.  This is ok if you do
                   1770: not use @code{spTOS}.  If you do use @code{spTOS}, the compiler has to
                   1771: decide whether to put that variable into an integer or a floating point
                   1772: register, and the other type of operation becomes quite expensive on
                   1773: most machines (because moving values between integer and FP registers is
                   1774: quite expensive).  If a value of one type has to be synthesized out of
                   1775: two values of the other type (@code{double} types), things are even more
                   1776: interesting.
                   1777: 
                   1778: One way around this problem would be to not use the @code{spTOS}
                   1779: supported by Vmgen, but to use explicit top-of-stack variables (one for
                   1780: integers, one for FP values), and having a kind of accumulator+stack
                   1781: architecture (e.g., Ocaml bytecode uses this approach); however, this is
                   1782: a major change, and it's ramifications are not completely clear.
1.10      anton    1783: 
                   1784: @c **********************************************************
1.13      anton    1785: @node The future, Changes, Hints, Top
                   1786: @chapter The future
                   1787: @cindex future ideas
                   1788: 
1.21    ! anton    1789: We have a number of ideas for future versions of Vmgen.  However, there
1.13      anton    1790: are so many possible things to do that we would like some feedback from
                   1791: you.  What are you doing with Vmgen, what features are you missing, and
                   1792: why?
                   1793: 
                   1794: One idea we are thinking about is to generate just one @file{.c} file
                   1795: instead of letting you copy and adapt all the wrapper files (you would
                   1796: still have to define stuff like the type-specific macros, and stack
                   1797: pointers etc. somewhere).  The advantage would be that, if we change the
                   1798: wrapper files between versions, you would not need to integrate your
                   1799: changes and our changes to them; Vmgen would also be easier to use for
                   1800: beginners.  The main disadvantage of that is that it would reduce the
                   1801: flexibility of Vmgen a little (well, those who like flexibility could
                   1802: still patch the resulting @file{.c} file, like they are now doing for
                   1803: the wrapper files).  In any case, if you are doing things to the wrapper
                   1804: files that would cause problems in a generated-@file{.c}-file approach,
                   1805: please let us know.
                   1806: 
                   1807: @c **********************************************************
                   1808: @node Changes, Contact, The future, Top
1.8       anton    1809: @chapter Changes
1.12      anton    1810: @cindex Changes from old versions
1.8       anton    1811: 
1.19      anton    1812: User-visible changes between 0.5.9-20020822 and 0.5.9-20020901:
                   1813: 
                   1814: The store optimization is now disabled by default, but can be enabled by
                   1815: the user (@pxref{Store Optimization}).  Documentation for this
                   1816: optimization is also new.
                   1817: 
                   1818: User-visible changes between 0.5.9-20010501 and 0.5.9-20020822:
1.17      anton    1819: 
                   1820: There is now a manual (in info, HTML, Postscript, or plain text format).
                   1821: 
                   1822: There is the vmgen-ex2 variant of the vmgen-ex example; the new
                   1823: variant uses a union type instead of lots of casting.
                   1824: 
                   1825: Both variants of the example can now be compiled with an ANSI C compiler
                   1826: (using switch dispatch and losing quite a bit of performance); tested
                   1827: with @command{lcc}.
                   1828: 
1.11      anton    1829: Users of the gforth-0.5.9-20010501 version of Vmgen need to change
1.8       anton    1830: several things in their source code to use the current version.  I
                   1831: recommend keeping the gforth-0.5.9-20010501 version until you have
                   1832: completed the change (note that you can have several versions of Gforth
                   1833: installed at the same time).  I hope to avoid such incompatible changes
                   1834: in the future.
1.2       anton    1835: 
1.8       anton    1836: The required changes are:
                   1837: 
                   1838: @table @code
1.13      anton    1839: 
                   1840: @cindex @code{TAIL;}, changes
                   1841: @item TAIL;
                   1842: has been renamed into @code{INST_TAIL;} (less chance of an accidental
                   1843: match).
1.2       anton    1844: 
1.12      anton    1845: @cindex @code{vm_@var{A}2@var{B}}, changes
1.8       anton    1846: @item vm_@var{A}2@var{B}
                   1847: now takes two arguments.
                   1848: 
1.12      anton    1849: @cindex @code{vm_two@var{A}2@var{B}}, changes
1.8       anton    1850: @item vm_two@var{A}2@var{B}(b,a1,a2);
                   1851: changed to vm_two@var{A}2@var{B}(a1,a2,b) (note the absence of the @samp{;}).
                   1852: 
                   1853: @end table
1.2       anton    1854: 
1.8       anton    1855: Also some new macros have to be defined, e.g., @code{INST_ADDR}, and
                   1856: @code{LABEL}; some macros have to be defined in new contexts, e.g.,
                   1857: @code{VM_IS_INST} is now also needed in the disassembler.
1.4       anton    1858: 
1.12      anton    1859: @c *********************************************************
1.10      anton    1860: @node Contact, Copying This Manual, Changes, Top
1.8       anton    1861: @chapter Contact
1.17      anton    1862: 
                   1863: To report a bug, use
                   1864: @url{https://savannah.gnu.org/bugs/?func=addbug&group_id=2672}.
                   1865: 
                   1866: For discussion on Vmgen (e.g., how to use it), use the mailing list
                   1867: @email{bug-vmgen@@mail.freesoftware.fsf.org} (use
                   1868: @url{http://mail.gnu.org/mailman/listinfo/help-vmgen} to subscribe).
                   1869: 
                   1870: You can find vmgen information at
                   1871: @url{http://www.complang.tuwien.ac.at/anton/vmgen/}.
1.4       anton    1872: 
1.12      anton    1873: @c ***********************************************************
1.10      anton    1874: @node Copying This Manual, Index, Contact, Top
                   1875: @appendix Copying This Manual
                   1876: 
                   1877: @menu
                   1878: * GNU Free Documentation License::  License for copying this manual.
                   1879: @end menu
                   1880: 
                   1881: @include fdl.texi
                   1882: 
                   1883: 
                   1884: @node Index,  , Copying This Manual, Top
                   1885: @unnumbered Index
                   1886: 
                   1887: @printindex cp
                   1888: 
                   1889: @bye

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