File:  [gforth] / gforth / doc / vmgen.texi
Revision 1.17: download - view: text, annotated - select for diffs
Thu Aug 22 20:07:33 2002 UTC (20 years, 5 months ago) by anton
Branches: MAIN
CVS tags: HEAD
Getting ready for the Vmgen release
New snapshot dates, various documentation changes, Makefile and configure fixes

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

FreeBSD-CVSweb <>