13.6 Literal-based optimizations

Gforth delays the code generation for literals; instead, it pushes the literal on a literal stack, and the implementation of compile, for a word (see User-defined compile,) can inspect the literal stack and possibly generate better code. This optimization happens at the threaded-code level, so one can see its effect already with see; in some cases simple-see is necessary to see the effect.

Here’s an example that shows some of the optimizations based on the literal stack:

: foo 15 1 + * 2 pick 3 - ;

see foo \ output below
: foo  
  #4 lshift third #-3 + ; ok
  
simple-see foo \ output below
<foo>         lit    0->0 
<foo+$8>      #4 
<foo+$10>     lshift    0->0 
<foo+$18>     third    0->0 
<foo+$20>     lit+    0->0 
<foo+$28>     #-3 
<foo+$30>     ;s    0->0  ok

The optimizer for + sees and consumes two values on the literal stack and constant-folds them into the value 16 on the literal stack. The optimizer for * sees and consumes 16 on the literal stack, and generates 4 lshift instead of the more expensive #16 *. The optimizer for pick sees and consumes 2 from the literal stack and generates third. The optimizer for - sees only one value on the literal stack, and generates the lit+ primitive with the negated value as immediate argument; in the see output, the lit+ is decompied as a literal followed by +.

This optimization if performed at the Forth level and is not controlled by engine options.