Improve and clarify transformation format definition.
[matthijs/master-project/report.git] / Chapters / Normalization.tex
1 \chapter[chap:normalization]{Normalization}
2
3 % A helper to print a single example in the half the page width. The example
4 % text should be in a buffer whose name is given in an argument.
5 %
6 % The align=right option really does left-alignment, but without the program
7 % will end up on a single line. The strut=no option prevents a bunch of empty
8 % space at the start of the frame.
9 \define[1]\example{
10   \framed[offset=1mm,align=right,strut=no,background=box,frame=off]{
11     \setuptyping[option=LAM,style=sans,before=,after=]
12     \typebuffer[#1]
13     \setuptyping[option=none,style=\tttf]
14   }
15 }
16
17
18 % A transformation example
19 \definefloat[example][examples]
20 \setupcaption[example][location=top] % Put captions on top
21
22 \define[3]\transexample{
23   \placeexample[here]{#1}
24   \startcombination[2*1]
25     {\example{#2}}{Original program}
26     {\example{#3}}{Transformed program}
27   \stopcombination
28 }
29 %
30 %\define[3]\transexampleh{
31 %%  \placeexample[here]{#1}
32 %%  \startcombination[1*2]
33 %%    {\example{#2}}{Original program}
34 %%    {\example{#3}}{Transformed program}
35 %%  \stopcombination
36 %}
37
38 The first step in the core to \small{VHDL} translation process, is normalization. We
39 aim to bring the core description into a simpler form, which we can
40 subsequently translate into \small{VHDL} easily. This normal form is needed because
41 the full core language is more expressive than \small{VHDL} in some areas and because
42 core can describe expressions that do not have a direct hardware
43 interpretation.
44
45 TODO: Describe core properties not supported in \small{VHDL}, and describe how the
46 \small{VHDL} we want to generate should look like.
47
48 \section{Normal form}
49 The transformations described here have a well-defined goal: To bring the
50 program in a well-defined form that is directly translatable to hardware,
51 while fully preserving the semantics of the program. We refer to this form as
52 the \emph{normal form} of the program. The formal definition of this normal
53 form is quite simple:
54
55 \placedefinition{}{A program is in \emph{normal form} if none of the
56 transformations from this chapter apply.}
57
58 Of course, this is an \quote{easy} definition of the normal form, since our
59 program will end up in normal form automatically. The more interesting part is
60 to see if this normal form actually has the properties we would like it to
61 have.
62
63 But, before getting into more definitions and details about this normal form,
64 let's try to get a feeling for it first. The easiest way to do this is by
65 describing the things we want to not have in a normal form.
66
67 \startitemize
68   \item Any \emph{polymorphism} must be removed. When laying down hardware, we
69   can't generate any signals that can have multiple types. All types must be
70   completely known to generate hardware.
71   
72   \item Any \emph{higher order} constructions must be removed. We can't
73   generate a hardware signal that contains a function, so all values,
74   arguments and returns values used must be first order.
75
76   \item Any complex \emph{nested scopes} must be removed. In the \small{VHDL}
77   description, every signal is in a single scope. Also, full expressions are
78   not supported everywhere (in particular port maps can only map signal names,
79   not expressions). To make the \small{VHDL} generation easy, all values must be bound
80   on the \quote{top level}.
81 \stopitemize
82
83 TODO: Intermezzo: functions vs plain values
84
85 A very simple example of a program in normal form is given in
86 \in{example}[ex:MulSum]. As you can see, all arguments to the function (which
87 will become input ports in the final hardware) are at the top. This means that
88 the body of the final lambda abstraction is never a function, but always a
89 plain value.
90
91 After the lambda abstractions, we see a single let expression, that binds two
92 variables (\lam{mul} and \lam{sum}). These variables will be signals in the
93 final hardware, bound to the output port of the \lam{*} and \lam{+}
94 components.
95
96 The final line (the \quote{return value} of the function) selects the
97 \lam{sum} signal to be the output port of the function. This \quote{return
98 value} can always only be a variable reference, never a more complex
99 expression.
100
101 \startbuffer[MulSum]
102 alu :: Bit -> Word -> Word -> Word
103 alu = λa.λb.λc.
104     let
105       mul = (*) a b
106       sum = (+) mul c
107     in
108       sum
109 \stopbuffer
110
111 \startuseMPgraphic{MulSum}
112   save a, b, c, mul, add, sum;
113
114   % I/O ports
115   newCircle.a(btex $a$ etex) "framed(false)";
116   newCircle.b(btex $b$ etex) "framed(false)";
117   newCircle.c(btex $c$ etex) "framed(false)";
118   newCircle.sum(btex $res$ etex) "framed(false)";
119
120   % Components
121   newCircle.mul(btex - etex);
122   newCircle.add(btex + etex);
123
124   a.c      - b.c   = (0cm, 2cm);
125   b.c      - c.c   = (0cm, 2cm);
126   add.c            = c.c + (2cm, 0cm);
127   mul.c            = midpoint(a.c, b.c) + (2cm, 0cm);
128   sum.c            = add.c + (2cm, 0cm);
129   c.c              = origin;
130
131   % Draw objects and lines
132   drawObj(a, b, c, mul, add, sum);
133
134   ncarc(a)(mul) "arcangle(15)";
135   ncarc(b)(mul) "arcangle(-15)";
136   ncline(c)(add);
137   ncline(mul)(add);
138   ncline(add)(sum);
139 \stopuseMPgraphic
140
141 \placeexample[here][ex:MulSum]{Simple architecture consisting of an adder and a
142 subtractor.}
143   \startcombination[2*1]
144     {\typebufferlam{MulSum}}{Core description in normal form.}
145     {\boxedgraphic{MulSum}}{The architecture described by the normal form.}
146   \stopcombination
147
148 The previous example described composing an architecture by calling other
149 functions (operators), resulting in a simple architecture with component and
150 connection. There is of course also some mechanism for choice in the normal
151 form. In a normal Core program, the \emph{case} expression can be used in a
152 few different ways to describe choice. In normal form, this is limited to a
153 very specific form.
154
155 \in{Example}[ex:AddSubAlu] shows an example describing a
156 simple \small{ALU}, which chooses between two operations based on an opcode
157 bit. The main structure is the same as in \in{example}[ex:MulSum], but this
158 time the \lam{res} variable is bound to a case expression. This case
159 expression scrutinizes the variable \lam{opcode} (and scrutinizing more
160 complex expressions is not supported). The case expression can select a
161 different variable based on the constructor of \lam{opcode}.
162
163 \startbuffer[AddSubAlu]
164 alu :: Bit -> Word -> Word -> Word
165 alu = λopcode.λa.λb.
166     let
167       res1 = (+) a b
168       res2 = (-) a b
169       res = case opcode of
170         Low -> res1
171         High -> res2
172     in
173       res
174 \stopbuffer
175
176 \startuseMPgraphic{AddSubAlu}
177   save opcode, a, b, add, sub, mux, res;
178
179   % I/O ports
180   newCircle.opcode(btex $opcode$ etex) "framed(false)";
181   newCircle.a(btex $a$ etex) "framed(false)";
182   newCircle.b(btex $b$ etex) "framed(false)";
183   newCircle.res(btex $res$ etex) "framed(false)";
184   % Components
185   newCircle.add(btex + etex);
186   newCircle.sub(btex - etex);
187   newMux.mux;
188
189   opcode.c - a.c   = (0cm, 2cm);
190   add.c    - a.c   = (4cm, 0cm);
191   sub.c    - b.c   = (4cm, 0cm);
192   a.c      - b.c   = (0cm, 3cm);
193   mux.c            = midpoint(add.c, sub.c) + (1.5cm, 0cm);
194   res.c    - mux.c = (1.5cm, 0cm);
195   b.c              = origin;
196
197   % Draw objects and lines
198   drawObj(opcode, a, b, res, add, sub, mux);
199
200   ncline(a)(add) "posA(e)";
201   ncline(b)(sub) "posA(e)";
202   nccurve(a)(sub) "posA(e)", "angleA(0)";
203   nccurve(b)(add) "posA(e)", "angleA(0)";
204   nccurve(add)(mux) "posB(inpa)", "angleB(0)";
205   nccurve(sub)(mux) "posB(inpb)", "angleB(0)";
206   nccurve(opcode)(mux) "posB(n)", "angleA(0)", "angleB(-90)";
207   ncline(mux)(res) "posA(out)";
208 \stopuseMPgraphic
209
210 \placeexample[here][ex:AddSubAlu]{Simple \small{ALU} supporting two operations.}
211   \startcombination[2*1]
212     {\typebufferlam{AddSubAlu}}{Core description in normal form.}
213     {\boxedgraphic{AddSubAlu}}{The architecture described by the normal form.}
214   \stopcombination
215
216 As a more complete example, consider \in{example}[ex:NormalComplete]. This
217 example contains everything that is supported in normal form, with the
218 exception of builtin higher order functions. The graphical version of the
219 architecture contains a slightly simplified version, since the state tuple
220 packing and unpacking have been left out. Instead, two seperate registers are
221 drawn. Also note that most synthesis tools will further optimize this
222 architecture by removing the multiplexers at the register input and replace
223 them with some logic in the clock inputs, but we want to show the architecture
224 as close to the description as possible.
225
226 \startbuffer[NormalComplete]
227   regbank :: Bit 
228              -> Word 
229              -> State (Word, Word) 
230              -> (State (Word, Word), Word)
231
232   -- All arguments are an inital lambda
233   regbank = λa.λd.λsp.
234   -- There are nested let expressions at top level
235   let
236     -- Unpack the state by coercion (\eg, cast from
237     -- State (Word, Word) to (Word, Word))
238     s = sp :: (Word, Word)
239     -- Extract both registers from the state
240     r1 = case s of (fst, snd) -> fst
241     r2 = case s of (fst, snd) -> snd
242     -- Calling some other user-defined function.
243     d' = foo d
244     -- Conditional connections
245     out = case a of
246       High -> r1
247       Low -> r2
248     r1' = case a of
249       High -> d'
250       Low -> r1
251     r2' = case a of
252       High -> r2
253       Low -> d'
254     -- Packing a tuple
255     s' = (,) r1' r2'
256     -- pack the state by coercion (\eg, cast from
257     -- (Word, Word) to State (Word, Word))
258     sp' = s' :: State (Word, Word)
259     -- Pack our return value
260     res = (,) sp' out
261   in
262     -- The actual result
263     res
264 \stopbuffer
265
266 \startuseMPgraphic{NormalComplete}
267   save a, d, r, foo, muxr, muxout, out;
268
269   % I/O ports
270   newCircle.a(btex \lam{a} etex) "framed(false)";
271   newCircle.d(btex \lam{d} etex) "framed(false)";
272   newCircle.out(btex \lam{out} etex) "framed(false)";
273   % Components
274   %newCircle.add(btex + etex);
275   newBox.foo(btex \lam{foo} etex);
276   newReg.r1(btex $\lam{r1}$ etex) "dx(4mm)", "dy(6mm)";
277   newReg.r2(btex $\lam{r2}$ etex) "dx(4mm)", "dy(6mm)", "reflect(true)";
278   newMux.muxr1;
279   % Reflect over the vertical axis
280   reflectObj(muxr1)((0,0), (0,1));
281   newMux.muxr2;
282   newMux.muxout;
283   rotateObj(muxout)(-90);
284
285   d.c               = foo.c + (0cm, 1.5cm); 
286   a.c               = (xpart r2.c + 2cm, ypart d.c - 0.5cm);
287   foo.c             = midpoint(muxr1.c, muxr2.c) + (0cm, 2cm);
288   muxr1.c           = r1.c + (0cm, 2cm);
289   muxr2.c           = r2.c + (0cm, 2cm);
290   r2.c              = r1.c + (4cm, 0cm);
291   r1.c              = origin;
292   muxout.c          = midpoint(r1.c, r2.c) - (0cm, 2cm);
293   out.c             = muxout.c - (0cm, 1.5cm);
294
295 %  % Draw objects and lines
296   drawObj(a, d, foo, r1, r2, muxr1, muxr2, muxout, out);
297   
298   ncline(d)(foo);
299   nccurve(foo)(muxr1) "angleA(-90)", "posB(inpa)", "angleB(180)";
300   nccurve(foo)(muxr2) "angleA(-90)", "posB(inpb)", "angleB(0)";
301   nccurve(muxr1)(r1) "posA(out)", "angleA(180)", "posB(d)", "angleB(0)";
302   nccurve(r1)(muxr1) "posA(out)", "angleA(0)", "posB(inpb)", "angleB(180)";
303   nccurve(muxr2)(r2) "posA(out)", "angleA(0)", "posB(d)", "angleB(180)";
304   nccurve(r2)(muxr2) "posA(out)", "angleA(180)", "posB(inpa)", "angleB(0)";
305   nccurve(r1)(muxout) "posA(out)", "angleA(0)", "posB(inpb)", "angleB(-90)";
306   nccurve(r2)(muxout) "posA(out)", "angleA(180)", "posB(inpa)", "angleB(-90)";
307   % Connect port a
308   nccurve(a)(muxout) "angleA(-90)", "angleB(180)", "posB(sel)";
309   nccurve(a)(muxr1) "angleA(180)", "angleB(-90)", "posB(sel)";
310   nccurve(a)(muxr2) "angleA(180)", "angleB(-90)", "posB(sel)";
311   ncline(muxout)(out) "posA(out)";
312 \stopuseMPgraphic
313
314 \placeexample[here][ex:NormalComplete]{Simple architecture consisting of an adder and a
315 subtractor.}
316   \startcombination[2*1]
317     {\typebufferlam{NormalComplete}}{Core description in normal form.}
318     {\boxedgraphic{NormalComplete}}{The architecture described by the normal form.}
319   \stopcombination
320
321 \subsection{Normal form definition}
322 Now we have some intuition for the normal form, we can describe how we want
323 the normal form to look like in a slightly more formal manner. The following
324 EBNF-like description completely captures the intended structure (and
325 generates a subset of GHC's core format).
326
327 Some clauses have an expression listed in parentheses. These are conditions
328 that need to apply to the clause.
329
330 \startlambda
331 \italic{normal} = \italic{lambda}
332 \italic{lambda} = λvar.\italic{lambda} (representable(var))
333                 | \italic{toplet} 
334 \italic{toplet} = let \italic{binding} in \italic{toplet} 
335                 | letrec [\italic{binding}] in \italic{toplet}
336                 | var (representable(varvar))
337 \italic{binding} = var = \italic{rhs} (representable(rhs))
338                  -- State packing and unpacking by coercion
339                  | var0 = var1 :: State ty (lvar(var1))
340                  | var0 = var1 :: ty (var0 :: State ty) (lvar(var1))
341 \italic{rhs} = userapp
342              | builtinapp
343              -- Extractor case
344              | case var of C a0 ... an -> ai (lvar(var))
345              -- Selector case
346              | case var of (lvar(var))
347                 DEFAULT -> var0 (lvar(var0))
348                 C w0 ... wn -> resvar (\forall{}i, wi \neq resvar, lvar(resvar))
349 \italic{userapp} = \italic{userfunc}
350                  | \italic{userapp} {userarg}
351 \italic{userfunc} = var (gvar(var))
352 \italic{userarg} = var (lvar(var))
353 \italic{builtinapp} = \italic{builtinfunc}
354                     | \italic{builtinapp} \italic{builtinarg}
355 \italic{builtinfunc} = var (bvar(var))
356 \italic{builtinarg} = \italic{coreexpr}
357 \stoplambda
358
359 -- TODO: Limit builtinarg further
360
361 -- TODO: There can still be other casts around (which the code can handle,
362 e.g., ignore), which still need to be documented here.
363
364 -- TODO: Note about the selector case. It just supports Bit and Bool
365 currently, perhaps it should be generalized in the normal form?
366
367 When looking at such a program from a hardware perspective, the top level
368 lambda's define the input ports. The value produced by the let expression is
369 the output port. Most function applications bound by the let expression
370 define a component instantiation, where the input and output ports are mapped
371 to local signals or arguments. Some of the others use a builtin
372 construction (\eg the \lam{case} statement) or call a builtin function
373 (\eg \lam{add} or \lam{sub}). For these, a hardcoded \small{VHDL} translation is
374 available.
375
376 \subsection{Definitions}
377 In the following sections, we will be using a number of functions and
378 notations, which we will define here.
379
380 \subsubsection{Transformation notation}
381 To be able to concisely present transformations, we use a specific format to
382 them. It is a simple format, similar to one used in logic reasoning.
383
384 Such a transformation description looks like the following.
385
386 \starttrans
387 <context conditions>
388 ~
389 <original expression>
390 --------------------------          <expression conditions>
391 <transformed expresssion>
392 ~
393 <context additions>
394 \stoptrans
395
396 This format desribes a transformation that applies to \lam{original
397 expresssion} and transforms it into \lam{transformed expression}, assuming
398 that all conditions apply. In this format, there are a number of placeholders
399 in pointy brackets, most of which should be rather obvious in their meaning.
400 Nevertheless, we will more precisely specify their meaning below:
401
402   \startdesc{<original expression>} The expression pattern that will be matched
403   against (subexpressions of) the expression to be transformed. We call this a
404   pattern, because it can contain \emph{placeholders} (variables), which match
405   any expression or binder. Any such placeholder is said to be \emph{bound} to
406   the expression it matches. It is convention to use an uppercase latter (\eg
407   \lam{M} or \lam{E} to refer to any expression (including a simple variable
408   reference) and lowercase letters (\eg \lam{v} or \lam{b}) to refer to
409   (references to) binders.
410
411   For example, the pattern \lam{a + B} will match the expression 
412   \lam{v + (2 * w)} (and bind \lam{a} to \lam{v} and \lam{B} to 
413   \lam{(2 * 2)}), but not \lam{v + (2 * w)}.
414   \stopdesc
415
416   \startdesc{<expression conditions>}
417   These are extra conditions on the expression that is matched. These
418   conditions can be used to further limit the cases in which the
419   transformation applies, in particular to prevent a transformation from
420   causing a loop with itself or another transformation.
421
422   Only if these if these conditions are \emph{all} true, this transformation
423   applies.
424   \stopdesc
425
426   \startdesc{<context conditions>}
427   These are a number of extra conditions on the context of the function. In
428   particular, these conditions can require some other top level function to be
429   present, whose value matches the pattern given here. The format of each of
430   these conditions is: \lam{binder = <pattern>}.
431
432   Typically, the binder is some placeholder bound in the \lam{<original
433   expression>}, while the pattern contains some placeholders that are used in
434   the \lam{transformed expression}.
435   
436   Only if a top level binder exists that matches each binder and pattern, this
437   transformation applies.
438   \stopdesc
439
440   \startdesc{<transformed expression>}
441   This is the expression template that is the result of the transformation. If, looking
442   at the above three items, the transformation applies, the \lam{original
443   expression} is completely replaced with the \lam{<transformed expression>}.
444   We call this a template, because it can contain placeholders, referring to
445   any placeholder bound by the \lam{<original expression>} or the
446   \lam{<context conditions>}. The resulting expression will have those
447   placeholders replaced by the values bound to them.
448
449   Any binder (lowercase) placeholder that has no value bound to it yet will be
450   bound to (and replaced with) a fresh binder.
451   \stopdesc
452
453   \startdesc{<context additions>}
454   These are templates for new functions to add to the context. This is a way
455   to have a transformation create new top level functiosn.
456
457   Each addition has the form \lam{binder = template}. As above, any
458   placeholder in the addition is replaced with the value bound to it, and any
459   binder placeholder that has no value bound to it yet will be bound to (and
460   replaced with) a fresh binder.
461   \stopdesc
462
463   As an example, we'll look at η-abstraction:
464
465 \starttrans
466 E                 \lam{E :: a -> b}
467 --------------    \lam{E} does not occur on a function position in an application
468 λx.E x            \lam{E} is not a lambda abstraction.
469 \stoptrans
470
471   Consider the following function, which is a fairly obvious way to specify a
472   simple ALU (Note \at{example}[ex:AddSubAlu] is the normal form of this
473   function):
474
475 \startlambda 
476 alu :: Bit -> Word -> Word -> Word
477 alu = λopcode. case opcode of
478   Low -> (+)
479   High -> (-)
480 \stoplambda
481
482   There are a few subexpressions in this function to which we could possibly
483   apply the transformation. Since the pattern of the transformation is only
484   the placeholder \lam{E}, any expression will match that. Whether the
485   transformation applies to an expression is thus solely decided by the
486   conditions to the right of the transformation.
487
488   We will look at each expression in the function in a top down manner. The
489   first expression is the entire expression the function is bound to.
490
491 \startlambda
492 λopcode. case opcode of
493   Low -> (+)
494   High -> (-)
495 \stoplambda
496
497   As said, the expression pattern matches this. The type of this expression is
498   \lam{Bit -> Word -> Word -> Word}, which matches \lam{a -> b} (Note that in
499   this case \lam{a = Bit} and \lam{b = Word -> Word -> Word}).
500
501   Since this expression is at top level, it does not occur at a function
502   position of an application. However, The expression is a lambda abstraction,
503   so this transformation does not apply.
504
505   The next expression we could apply this transformation to, is the body of
506   the lambda abstraction:
507
508 \startlambda
509 case opcode of
510   Low -> (+)
511   High -> (-)
512 \stoplambda
513
514   The type of this expression is \lam{Word -> Word -> Word}, which again
515   matches \lam{a -> b}. The expression is the body of a lambda expression, so
516   it does not occur at a function position of an application. Finally, the
517   expression is not a lambda abstraction but a case expression, so all the
518   conditions match. There are no context conditions to match, so the
519   transformation applies.
520
521   By now, the placeholder \lam{E} is bound to the entire expression. The
522   placeholder \lam{x}, which occurs in the replacement template, is not bound
523   yet, so we need to generate a fresh binder for that. Let's use the binder
524   \lam{a}. This results in the following replacement expression:
525
526 \startlambda
527 λa.(case opcode of
528   Low -> (+)
529   High -> (-)) a
530 \stoplambda
531
532   Continuing with this expression, we see that the transformation does not
533   apply again (it is a lambda expression). Next we look at the body of this
534   labmda abstraction:
535
536 \startlambda
537 (case opcode of
538   Low -> (+)
539   High -> (-)) a
540 \stoplambda
541   
542   Here, the transformation does apply, binding \lam{E} to the entire
543   expression and \lam{x} to the fresh binder \lam{b}, resulting in the
544   replacement:
545
546 \startlambda
547 λb.(case opcode of
548   Low -> (+)
549   High -> (-)) a b
550 \stoplambda
551
552   Again, the transformation does not apply to this lambda abstraction, so we
553   look at its body. For brevity, we'll put the case statement on one line from
554   now on.
555
556 \startlambda
557 (case opcode of Low -> (+); High -> (-)) a b
558 \stoplambda
559
560   The type of this expression is \lam{Word}, so it does not match \lam{a -> b}
561   and the transformation does not apply. Next, we have two options for the
562   next expression to look at: The function position and argument position of
563   the application. The expression in the argument position is \lam{b}, which
564   has type \lam{Word}, so the transformation does not apply. The expression in
565   the function position is:
566
567 \startlambda
568 (case opcode of Low -> (+); High -> (-)) a
569 \stoplambda
570
571   Obviously, the transformation does not apply here, since it occurs in
572   function position. In the same way the transformation does not apply to both
573   components of this expression (\lam{case opcode of Low -> (+); High -> (-)}
574   and \lam{a}), so we'll skip to the components of the case expression: The
575   scrutinee and both alternatives. Since the opcode is not a function, it does
576   not apply here, and we'll leave both alternatives as an exercise to the
577   reader. The final function, after all these transformations becomes:
578
579 \startlambda 
580 alu :: Bit -> Word -> Word -> Word
581 alu = λopcode.λa.b. (case opcode of
582   Low -> λa1.λb1 (+) a1 b1
583   High -> λa2.λb2 (-) a2 b2) a b
584 \stoplambda
585
586   In this case, the transformation does not apply anymore, though this might
587   not always be the case (e.g., the application of a transformation on a
588   subexpression might open up possibilities to apply the transformation
589   further up in the expression).
590
591 \subsubsection{Transformation application}
592 In this chapter we define a number of transformations, but how will we apply
593 these? As stated before, our normal form is reached as soon as no
594 transformation applies anymore. This means our application strategy is to
595 simply apply any transformation that applies, and continuing to do that with
596 the result of each transformation.
597
598 In particular, we define no particular order of transformations. Since
599 transformation order should not influence the resulting normal form (see TODO
600 ref), this leaves the implementation free to choose any application order that
601 results in an efficient implementation.
602
603 When applying a single transformation, we try to apply it to every (sub)expression
604 in a function, not just the top level function. This allows us to keep the
605 transformation descriptions concise and powerful.
606
607 \subsubsection{Other concepts}
608 A \emph{global variable} is any variable that is bound at the
609 top level of a program, or an external module. A local variable is any other
610 variable (\eg, variables local to a function, which can be bound by lambda
611 abstractions, let expressions and case expressions).
612
613 A \emph{hardware representable} type is a type that we can generate
614 a signal for in hardware. For example, a bit, a vector of bits, a 32 bit
615 unsigned word, etc. Types that are not runtime representable notably
616 include (but are not limited to): Types, dictionaries, functions.
617
618 A \emph{builtin function} is a function for which a builtin
619 hardware translation is available, because its actual definition is not
620 translatable. A user-defined function is any other function.
621
622 \subsubsection{Functions}
623 Here, we define a number of functions that can be used below to concisely
624 specify conditions.
625
626 \emph{gvar(expr)} is true when \emph{expr} is a variable that references a
627 global variable. It is false when it references a local variable.
628
629 \emph{lvar(expr)} is the inverse of \emph{gvar}; it is true when \emph{expr}
630 references a local variable, false when it references a global variable.
631
632 \emph{representable(expr)} or \emph{representable(var)} is true when
633 \emph{expr} or \emph{var} has a type that is representable at runtime.
634
635 \section{Transform passes}
636 In this section we describe the actual transforms. Here we're using
637 the core language in a notation that resembles lambda calculus.
638
639 Each of these transforms is meant to be applied to every (sub)expression
640 in a program, for as long as it applies. Only when none of the
641 transformations can be applied anymore, the program is in normal form (by
642 definition). We hope to be able to prove that this form will obey all of the
643 constraints defined above, but this has yet to happen (though it seems likely
644 that it will).
645
646 Each of the transforms will be described informally first, explaining
647 the need for and goal of the transform. Then, a formal definition is
648 given, using a familiar syntax from the world of logic. Each transform
649 is specified as a number of conditions (above the horizontal line) and a
650 number of conclusions (below the horizontal line). The details of using
651 this notation are still a bit fuzzy, so comments are welcom.
652
653 TODO: Formally describe the "apply to every (sub)expression" in terms of
654 rules with full transformations in the conditions.
655
656 \subsection{Binder uniqueness}
657 A common problem in transformation systems, is binder uniqueness. When not
658 considering this problem, it is easy to create transformations that mix up
659 bindings and cause name collisions. Take for example, the following core
660 expression:
661
662 \startlambda
663 (λa.λb.λc. a * b * c) x c
664 \stoplambda
665
666 By applying β-reduction (see below) once, we can simplify this expression to:
667
668 \startlambda
669 (λb.λc. x * b * c) c
670 \stoplambda
671
672 Now, we have replaced the \lam{a} binder with a reference to the \lam{x}
673 binder. No harm done here. But note that we see multiple occurences of the
674 \lam{c} binder. The first is a binding occurence, to which the second refers.
675 The last, however refers to \emph{another} instance of \lam{c}, which is
676 bound somewhere outside of this expression. Now, if we would apply beta
677 reduction without taking heed of binder uniqueness, we would get:
678
679 \startlambda
680 λc. x * c * c
681 \stoplambda
682
683 This is obviously not what was supposed to happen! The root of this problem is
684 the reuse of binders: Identical binders can be bound in different scopes, such
685 that only the inner one is \quote{visible} in the inner expression. In the example
686 above, the \lam{c} binder was bound outside of the expression and in the inner
687 lambda expression. Inside that lambda expression, only the inner \lam{c} is
688 visible.
689
690 There are a number of ways to solve this. \small{GHC} has isolated this
691 problem to their binder substitution code, which performs \emph{deshadowing}
692 during its expression traversal. This means that any binding that shadows
693 another binding on a higher level is replaced by a new binder that does not
694 shadow any other binding. This non-shadowing invariant is enough to prevent
695 binder uniqueness problems in \small{GHC}.
696
697 In our transformation system, maintaining this non-shadowing invariant is
698 a bit harder to do (mostly due to implementation issues, the prototype doesn't
699 use \small{GHC}'s subsitution code). Also, we can observe the following
700 points.
701
702 \startitemize
703 \item Deshadowing does not guarantee overall uniqueness. For example, the
704 following (slightly contrived) expression shows the identifier \lam{x} bound in
705 two seperate places (and to different values), even though no shadowing
706 occurs.
707
708 \startlambda
709 (let x = 1 in x) + (let x = 2 in x)
710 \stoplambda
711
712 \item In our normal form (and the resulting \small{VHDL}), all binders
713 (signals) will end up in the same scope. To allow this, all binders within the
714 same function should be unique.
715
716 \item When we know that all binders in an expression are unique, moving around
717 or removing a subexpression will never cause any binder conflicts. If we have
718 some way to generate fresh binders, introducing new subexpressions will not
719 cause any problems either. The only way to cause conflicts is thus to
720 duplicate an existing subexpression.
721 \stopitemize
722
723 Given the above, our prototype maintains a unique binder invariant. This
724 meanst that in any given moment during normalization, all binders \emph{within
725 a single function} must be unique. To achieve this, we apply the following
726 technique.
727
728 TODO: Define fresh binders and unique supplies
729
730 \startitemize
731 \item Before starting normalization, all binders in the function are made
732 unique. This is done by generating a fresh binder for every binder used. This
733 also replaces binders that did not pose any conflict, but it does ensure that
734 all binders within the function are generated by the same unique supply. See
735 (TODO: ref fresh binder).
736 \item Whenever a new binder must be generated, we generate a fresh binder that
737 is guaranteed to be different from \emph{all binders generated so far}. This
738 can thus never introduce duplication and will maintain the invariant.
739 \item Whenever (part of) an expression is duplicated (for example when
740 inlining), all binders in the expression are replaced with fresh binders
741 (using the same method as at the start of normalization). These fresh binders
742 can never introduce duplication, so this will maintain the invariant.
743 \item Whenever we move part of an expression around within the function, there
744 is no need to do anything special. There is obviously no way to introduce
745 duplication by moving expressions around. Since we know that each of the
746 binders is already unique, there is no way to introduce (incorrect) shadowing
747 either.
748 \stopitemize
749
750 \subsection{η-abstraction}
751 This transformation makes sure that all arguments of a function-typed
752 expression are named, by introducing lambda expressions. When combined with
753 β-reduction and function inlining below, all function-typed expressions should
754 be lambda abstractions or global identifiers.
755
756 \starttrans
757 E                 \lam{E :: a -> b}
758 --------------    \lam{E} is not the first argument of an application.
759 λx.E x            \lam{E} is not a lambda abstraction.
760                   \lam{x} is a variable that does not occur free in \lam{E}.
761 \stoptrans
762
763 \startbuffer[from]
764 foo = λa.case a of 
765   True -> λb.mul b b
766   False -> id
767 \stopbuffer
768
769 \startbuffer[to]
770 foo = λa.λx.(case a of 
771     True -> λb.mul b b
772     False -> λy.id y) x
773 \stopbuffer
774
775 \transexample{η-abstraction}{from}{to}
776
777 \subsection{Extended β-reduction}
778 This transformation is meant to propagate application expressions downwards
779 into expressions as far as possible. In lambda calculus, this reduction
780 is known as β-reduction, but it is of course only defined for
781 applications of lambda abstractions. We extend this reduction to also
782 work for the rest of core (case and let expressions).
783
784 For let expressions:
785 \starttrans
786 let binds in E) M
787 -----------------
788 let binds in E M
789 \stoptrans
790
791 For case statements:
792 \starttrans
793 (case x of
794   p1 -> E1
795   \vdots
796   pn -> En) M
797 -----------------
798 case x of
799   p1 -> E1 M
800   \vdots
801   pn -> En M
802 \stoptrans
803
804 For lambda expressions:
805 \starttrans
806 (λx.E) M
807 -----------------
808 E[M/x]
809 \stoptrans
810
811 % And an example
812 \startbuffer[from]
813 ( let a = (case x of 
814             True -> id
815             False -> neg
816           ) 1
817       b = (let y = 3 in add y) 2
818   in
819     (λz.add 1 z)
820 ) 3
821 \stopbuffer
822
823 \startbuffer[to]
824 let a = case x of 
825            True -> id 1
826            False -> neg 1
827     b = let y = 3 in add y 2
828 in
829   add 1 3
830 \stopbuffer
831
832 \transexample{Extended β-reduction}{from}{to}
833
834 \subsection{Let derecursification}
835 This transformation is meant to make lets non-recursive whenever possible.
836 This might allow other optimizations to do their work better. TODO: Why is
837 this needed exactly?
838
839 \subsection{Let flattening}
840 This transformation puts nested lets in the same scope, by lifting the
841 binding(s) of the inner let into a new let around the outer let. Eventually,
842 this will cause all let bindings to appear in the same scope (they will all be
843 in scope for the function return value).
844
845 Note that this transformation does not try to be smart when faced with
846 recursive lets, it will just leave the lets recursive (possibly joining a
847 recursive and non-recursive let into a single recursive let). The let
848 rederursification transformation will do this instead.
849
850 \starttrans
851 letnonrec x = (let bindings in M) in N
852 ------------------------------------------
853 let bindings in (letnonrec x = M) in N
854 \stoptrans
855
856 \starttrans
857 letrec 
858   \vdots
859   x = (let bindings in M)
860   \vdots
861 in
862   N
863 ------------------------------------------
864 letrec
865   \vdots
866   bindings
867   x = M
868   \vdots
869 in
870   N
871 \stoptrans
872
873 \startbuffer[from]
874 let
875   a = letrec
876     x = 1
877     y = 2
878   in
879     x + y
880 in
881   letrec
882     b = let c = 3 in a + c
883     d = 4
884   in
885     d + b
886 \stopbuffer
887 \startbuffer[to]
888 letrec
889   x = 1
890   y = 2
891 in
892   let
893     a = x + y
894   in
895     letrec
896       c = 3
897       b = a + c
898       d = 4
899     in
900       d + b
901 \stopbuffer
902
903 \transexample{Let flattening}{from}{to}
904
905 \subsection{Empty let removal}
906 This transformation is simple: It removes recursive lets that have no bindings
907 (which usually occurs when let derecursification removes the last binding from
908 it).
909
910 \starttrans
911 letrec in M
912 --------------
913 M
914 \stoptrans
915
916 \subsection{Simple let binding removal}
917 This transformation inlines simple let bindings (\eg a = b).
918
919 This transformation is not needed to get into normal form, but makes the
920 resulting \small{VHDL} a lot shorter.
921
922 \starttrans
923 letnonrec
924   a = b
925 in
926   M
927 -----------------
928 M[b/a]
929 \stoptrans
930
931 \starttrans
932 letrec
933   \vdots
934   a = b
935   \vdots
936 in
937   M
938 -----------------
939 let
940   \vdots [b/a]
941   \vdots [b/a]
942 in
943   M[b/a]
944 \stoptrans
945
946 \subsection{Unused let binding removal}
947 This transformation removes let bindings that are never used. Usually,
948 the desugarer introduces some unused let bindings.
949
950 This normalization pass should really be unneeded to get into normal form
951 (since ununsed bindings are not forbidden by the normal form), but in practice
952 the desugarer or simplifier emits some unused bindings that cannot be
953 normalized (e.g., calls to a \type{PatError} (TODO: Check this name)). Also,
954 this transformation makes the resulting \small{VHDL} a lot shorter.
955
956 \starttrans
957 let a = E in M
958 ----------------------------    \lam{a} does not occur free in \lam{M}
959 M
960 \stoptrans
961
962 \starttrans
963 letrec
964   \vdots
965   a = E
966   \vdots
967 in
968   M
969 ----------------------------    \lam{a} does not occur free in \lam{M}
970 letrec
971   \vdots
972   \vdots
973 in
974   M
975 \stoptrans
976
977 \subsection{Non-representable binding inlining}
978 This transform inlines let bindings that have a non-representable type. Since
979 we can never generate a signal assignment for these bindings (we cannot
980 declare a signal assignment with a non-representable type, for obvious
981 reasons), we have no choice but to inline the binding to remove it.
982
983 If the binding is non-representable because it is a lambda abstraction, it is
984 likely that it will inlined into an application and β-reduction will remove
985 the lambda abstraction and turn it into a representable expression at the
986 inline site. The same holds for partial applications, which can be turned into
987 full applications by inlining.
988
989 Other cases of non-representable bindings we see in practice are primitive
990 Haskell types. In most cases, these will not result in a valid normalized
991 output, but then the input would have been invalid to start with. There is one
992 exception to this: When a builtin function is applied to a non-representable
993 expression, things might work out in some cases. For example, when you write a
994 literal \hs{SizedInt} in Haskell, like \hs{1 :: SizedInt D8}, this results in
995 the following core: \lam{fromInteger (smallInteger 10)}, where for example
996 \lam{10 :: GHC.Prim.Int\#} and \lam{smallInteger 10 :: Integer} have
997 non-representable types. TODO: This/these paragraph(s) should probably become a
998 separate discussion somewhere else.
999
1000 \starttrans
1001 letnonrec a = E in M
1002 --------------------------    \lam{E} has a non-representable type.
1003 M[E/a]
1004 \stoptrans
1005
1006 \starttrans
1007 letrec 
1008   \vdots
1009   a = E
1010   \vdots
1011 in
1012   M
1013 --------------------------    \lam{E} has a non-representable type.
1014 letrec
1015   \vdots [E/a]
1016   \vdots [E/a]
1017 in
1018   M[E/a]
1019 \stoptrans
1020
1021 \startbuffer[from]
1022 letrec
1023   a = smallInteger 10
1024   inc = λa -> add a 1
1025   inc' = add 1
1026   x = fromInteger a 
1027 in
1028   inc (inc' x)
1029 \stopbuffer
1030
1031 \startbuffer[to]
1032 letrec
1033   x = fromInteger (smallInteger 10)
1034 in
1035   (λa -> add a 1) (add 1 x)
1036 \stopbuffer
1037
1038 \transexample{Let flattening}{from}{to}
1039
1040 \subsection{Compiler generated top level binding inlining}
1041 TODO
1042
1043 \subsection{Scrutinee simplification}
1044 This transform ensures that the scrutinee of a case expression is always
1045 a simple variable reference.
1046
1047 \starttrans
1048 case E of
1049   alts
1050 -----------------        \lam{E} is not a local variable reference
1051 let x = E in 
1052   case E of
1053     alts
1054 \stoptrans
1055
1056 \startbuffer[from]
1057 case (foo a) of
1058   True -> a
1059   False -> b
1060 \stopbuffer
1061
1062 \startbuffer[to]
1063 let x = foo a in
1064   case x of
1065     True -> a
1066     False -> b
1067 \stopbuffer
1068
1069 \transexample{Let flattening}{from}{to}
1070
1071
1072 \subsection{Case simplification}
1073 This transformation ensures that all case expressions become normal form. This
1074 means they will become one of:
1075 \startitemize
1076 \item An extractor case with a single alternative that picks a single field
1077 from a datatype, \eg \lam{case x of (a, b) -> a}.
1078 \item A selector case with multiple alternatives and only wild binders, that
1079 makes a choice between expressions based on the constructor of another
1080 expression, \eg \lam{case x of Low -> a; High -> b}.
1081 \stopitemize
1082
1083 \starttrans
1084 case E of
1085   C0 v0,0 ... v0,m -> E0
1086   \vdots
1087   Cn vn,0 ... vn,m -> En
1088 --------------------------------------------------- \forall i \forall j, 0 <= i <= n, 0 <= i < m (\lam{wi,j} is a wild (unused) binder)
1089 letnonrec
1090   v0,0 = case x of C0 v0,0 .. v0,m -> v0,0
1091   \vdots
1092   v0,m = case x of C0 v0,0 .. v0,m -> v0,m
1093   x0 = E0
1094   \dots
1095   vn,m = case x of Cn vn,0 .. vn,m -> vn,m
1096   xn = En
1097 in
1098   case E of
1099     C0 w0,0 ... w0,m -> x0
1100     \vdots
1101     Cn wn,0 ... wn,m -> xn
1102 \stoptrans
1103
1104 TODO: This transformation specified like this is complicated and misses
1105 conditions to prevent looping with itself. Perhaps we should split it here for
1106 discussion?
1107
1108 \startbuffer[from]
1109 case a of
1110   True -> add b 1
1111   False -> add b 2
1112 \stopbuffer
1113
1114 \startbuffer[to]
1115 letnonrec
1116   x0 = add b 1
1117   x1 = add b 2
1118 in
1119   case a of
1120     True -> x0
1121     False -> x1
1122 \stopbuffer
1123
1124 \transexample{Selector case simplification}{from}{to}
1125
1126 \startbuffer[from]
1127 case a of
1128   (,) b c -> add b c
1129 \stopbuffer
1130 \startbuffer[to]
1131 letnonrec
1132   b = case a of (,) b c -> b
1133   c = case a of (,) b c -> c
1134   x0 = add b c
1135 in
1136   case a of
1137     (,) w0 w1 -> x0
1138 \stopbuffer
1139
1140 \transexample{Extractor case simplification}{from}{to}
1141
1142 \subsection{Case removal}
1143 This transform removes any case statements with a single alternative and
1144 only wild binders.
1145
1146 These "useless" case statements are usually leftovers from case simplification
1147 on extractor case (see the previous example).
1148
1149 \starttrans
1150 case x of
1151   C v0 ... vm -> E
1152 ----------------------     \lam{\forall i, 0 <= i <= m} (\lam{vi} does not occur free in E)
1153 E
1154 \stoptrans
1155
1156 \startbuffer[from]
1157 case a of
1158   (,) w0 w1 -> x0
1159 \stopbuffer
1160
1161 \startbuffer[to]
1162 x0
1163 \stopbuffer
1164
1165 \transexample{Case removal}{from}{to}
1166
1167 \subsection{Argument simplification}
1168 The transforms in this section deal with simplifying application
1169 arguments into normal form. The goal here is to:
1170
1171 \startitemize
1172  \item Make all arguments of user-defined functions (\eg, of which
1173  we have a function body) simple variable references of a runtime
1174  representable type. This is needed, since these applications will be turned
1175  into component instantiations.
1176  \item Make all arguments of builtin functions one of:
1177    \startitemize
1178     \item A type argument.
1179     \item A dictionary argument.
1180     \item A type level expression.
1181     \item A variable reference of a runtime representable type.
1182     \item A variable reference or partial application of a function type.
1183    \stopitemize
1184 \stopitemize
1185
1186 When looking at the arguments of a user-defined function, we can
1187 divide them into two categories:
1188 \startitemize
1189   \item Arguments of a runtime representable type (\eg bits or vectors).
1190
1191         These arguments can be preserved in the program, since they can
1192         be translated to input ports later on.  However, since we can
1193         only connect signals to input ports, these arguments must be
1194         reduced to simple variables (for which signals will be
1195         produced). This is taken care of by the argument extraction
1196         transform.
1197   \item Non-runtime representable typed arguments.
1198         
1199         These arguments cannot be preserved in the program, since we
1200         cannot represent them as input or output ports in the resulting
1201         \small{VHDL}. To remove them, we create a specialized version of the
1202         called function with these arguments filled in. This is done by
1203         the argument propagation transform.
1204
1205         Typically, these arguments are type and dictionary arguments that are
1206         used to make functions polymorphic. By propagating these arguments, we
1207         are essentially doing the same which GHC does when it specializes
1208         functions: Creating multiple variants of the same function, one for
1209         each type for which it is used. Other common non-representable
1210         arguments are functions, e.g. when calling a higher order function
1211         with another function or a lambda abstraction as an argument.
1212
1213         The reason for doing this is similar to the reasoning provided for
1214         the inlining of non-representable let bindings above. In fact, this
1215         argument propagation could be viewed as a form of cross-function
1216         inlining.
1217 \stopitemize
1218
1219 TODO: Check the following itemization.
1220
1221 When looking at the arguments of a builtin function, we can divide them
1222 into categories: 
1223
1224 \startitemize
1225   \item Arguments of a runtime representable type.
1226         
1227         As we have seen with user-defined functions, these arguments can
1228         always be reduced to a simple variable reference, by the
1229         argument extraction transform. Performing this transform for
1230         builtin functions as well, means that the translation of builtin
1231         functions can be limited to signal references, instead of
1232         needing to support all possible expressions.
1233
1234   \item Arguments of a function type.
1235         
1236         These arguments are functions passed to higher order builtins,
1237         like \lam{map} and \lam{foldl}. Since implementing these
1238         functions for arbitrary function-typed expressions (\eg, lambda
1239         expressions) is rather comlex, we reduce these arguments to
1240         (partial applications of) global functions.
1241         
1242         We can still support arbitrary expressions from the user code,
1243         by creating a new global function containing that expression.
1244         This way, we can simply replace the argument with a reference to
1245         that new function. However, since the expression can contain any
1246         number of free variables we also have to include partial
1247         applications in our normal form.
1248
1249         This category of arguments is handled by the function extraction
1250         transform.
1251   \item Other unrepresentable arguments.
1252         
1253         These arguments can take a few different forms:
1254         \startdesc{Type arguments}
1255           In the core language, type arguments can only take a single
1256           form: A type wrapped in the Type constructor. Also, there is
1257           nothing that can be done with type expressions, except for
1258           applying functions to them, so we can simply leave type
1259           arguments as they are.
1260         \stopdesc
1261         \startdesc{Dictionary arguments}
1262           In the core language, dictionary arguments are used to find
1263           operations operating on one of the type arguments (mostly for
1264           finding class methods). Since we will not actually evaluatie
1265           the function body for builtin functions and can generate
1266           code for builtin functions by just looking at the type
1267           arguments, these arguments can be ignored and left as they
1268           are.
1269         \stopdesc
1270         \startdesc{Type level arguments}
1271           Sometimes, we want to pass a value to a builtin function, but
1272           we need to know the value at compile time. Additionally, the
1273           value has an impact on the type of the function. This is
1274           encoded using type-level values, where the actual value of the
1275           argument is not important, but the type encodes some integer,
1276           for example. Since the value is not important, the actual form
1277           of the expression does not matter either and we can leave
1278           these arguments as they are.
1279         \stopdesc
1280         \startdesc{Other arguments}
1281           Technically, there is still a wide array of arguments that can
1282           be passed, but does not fall into any of the above categories.
1283           However, none of the supported builtin functions requires such
1284           an argument. This leaves use with passing unsupported types to
1285           a function, such as calling \lam{head} on a list of functions.
1286
1287           In these cases, it would be impossible to generate hardware
1288           for such a function call anyway, so we can ignore these
1289           arguments.
1290
1291           The only way to generate hardware for builtin functions with
1292           arguments like these, is to expand the function call into an
1293           equivalent core expression (\eg, expand map into a series of
1294           function applications). But for now, we choose to simply not
1295           support expressions like these.
1296         \stopdesc
1297
1298         From the above, we can conclude that we can simply ignore these
1299         other unrepresentable arguments and focus on the first two
1300         categories instead.
1301 \stopitemize
1302
1303 \subsubsection{Argument simplification}
1304 This transform deals with arguments to functions that
1305 are of a runtime representable type. It ensures that they will all become
1306 references to global variables, or local signals in the resulting \small{VHDL}. 
1307
1308 TODO: It seems we can map an expression to a port, not only a signal.
1309 Perhaps this makes this transformation not needed?
1310 TODO: Say something about dataconstructors (without arguments, like True
1311 or False), which are variable references of a runtime representable
1312 type, but do not result in a signal.
1313
1314 To reduce a complex expression to a simple variable reference, we create
1315 a new let expression around the application, which binds the complex
1316 expression to a new variable. The original function is then applied to
1317 this variable.
1318
1319 \starttrans
1320 M N
1321 --------------------    \lam{N} is of a representable type
1322 let x = N in M x        \lam{N} is not a local variable reference
1323 \stoptrans
1324
1325 \startbuffer[from]
1326 add (add a 1) 1
1327 \stopbuffer
1328
1329 \startbuffer[to]
1330 let x = add a 1 in add x 1
1331 \stopbuffer
1332
1333 \transexample{Argument extraction}{from}{to}
1334
1335 \subsubsection{Function extraction}
1336 This transform deals with function-typed arguments to builtin functions.
1337 Since these arguments cannot be propagated, we choose to extract them
1338 into a new global function instead.
1339
1340 Any free variables occuring in the extracted arguments will become
1341 parameters to the new global function. The original argument is replaced
1342 with a reference to the new function, applied to any free variables from
1343 the original argument.
1344
1345 This transformation is useful when applying higher order builtin functions
1346 like \hs{map} to a lambda abstraction, for example. In this case, the code
1347 that generates \small{VHDL} for \hs{map} only needs to handle top level functions and
1348 partial applications, not any other expression (such as lambda abstractions or
1349 even more complicated expressions).
1350
1351 \starttrans
1352 M N                     \lam{M} is a (partial aplication of a) builtin function.
1353 ---------------------   \lam{f0 ... fn} = free local variables of \lam{N}
1354 M x f0 ... fn           \lam{N :: a -> b}
1355 ~                       \lam{N} is not a (partial application of) a top level function
1356 x = λf0 ... λfn.N
1357 \stoptrans
1358
1359 \startbuffer[from]
1360 map (λa . add a b) xs
1361
1362 map (add b) ys
1363 \stopbuffer
1364
1365 \startbuffer[to]
1366 x0 = λb.λa.add a b
1367 ~
1368 map x0 xs
1369
1370 x1 = λb.add b
1371 map x1 ys
1372 \stopbuffer
1373
1374 \transexample{Function extraction}{from}{to}
1375
1376 \subsubsection{Argument propagation}
1377 This transform deals with arguments to user-defined functions that are
1378 not representable at runtime. This means these arguments cannot be
1379 preserved in the final form and most be {\em propagated}.
1380
1381 Propagation means to create a specialized version of the called
1382 function, with the propagated argument already filled in. As a simple
1383 example, in the following program:
1384
1385 \startlambda
1386 f = λa.λb.a + b
1387 inc = λa.f a 1
1388 \stoplambda
1389
1390 we could {\em propagate} the constant argument 1, with the following
1391 result:
1392
1393 \startlambda
1394 f' = λa.a + 1
1395 inc = λa.f' a
1396 \stoplambda
1397
1398 Special care must be taken when the to-be-propagated expression has any
1399 free variables. If this is the case, the original argument should not be
1400 removed alltogether, but replaced by all the free variables of the
1401 expression. In this way, the original expression can still be evaluated
1402 inside the new function. Also, this brings us closer to our goal: All
1403 these free variables will be simple variable references.
1404
1405 To prevent us from propagating the same argument over and over, a simple
1406 local variable reference is not propagated (since is has exactly one
1407 free variable, itself, we would only replace that argument with itself).
1408
1409 This shows that any free local variables that are not runtime representable
1410 cannot be brought into normal form by this transform. We rely on an
1411 inlining transformation to replace such a variable with an expression we
1412 can propagate again.
1413
1414 \starttrans
1415 x = E
1416 ~
1417 x Y0 ... Yi ... Yn                               \lam{Yi} is not of a runtime representable type
1418 ---------------------------------------------    \lam{Yi} is not a local variable reference
1419 x' y0 ... yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} = free local vars of \lam{Yi}
1420 ~
1421 x' = λy0 ... yi-1 f0 ... fm yi+1 ... yn .       
1422       E y0 ... yi-1 Yi yi+1 ... yn   
1423
1424 \stoptrans
1425
1426 TODO: Example
1427
1428 \subsection{Cast propagation / simplification}
1429 This transform pushes casts down into the expression as far as possible. Since
1430 its exact role and need is not clear yet, this transformation is not yet
1431 specified.
1432
1433 \subsection{Return value simplification}
1434 This transformation ensures that the return value of a function is always a
1435 simple local variable reference.
1436
1437 Currently implemented using lambda simplification, let simplification, and
1438 top simplification. Should change into something like the following, which
1439 works only on the result of a function instead of any subexpression. This is
1440 achieved by the contexts, like \lam{x = E}, though this is strictly not
1441 correct (you could read this as "if there is any function \lam{x} that binds
1442 \lam{E}, any \lam{E} can be transformed, while we only mean the \lam{E} that
1443 is bound by \lam{x}. This might need some extra notes or something).
1444
1445 \starttrans
1446 x = E                            \lam{E} is representable
1447 ~                                \lam{E} is not a lambda abstraction
1448 E                                \lam{E} is not a let expression
1449 ---------------------------      \lam{E} is not a local variable reference
1450 let x = E in x
1451 \stoptrans
1452
1453 \starttrans
1454 x = λv0 ... λvn.E
1455 ~                                \lam{E} is representable
1456 E                                \lam{E} is not a let expression
1457 ---------------------------      \lam{E} is not a local variable reference
1458 let x = E in x
1459 \stoptrans
1460
1461 \starttrans
1462 x = λv0 ... λvn.let ... in E
1463 ~                                \lam{E} is representable
1464 E                                \lam{E} is not a local variable reference
1465 ---------------------------
1466 let x = E in x
1467 \stoptrans
1468
1469 \startbuffer[from]
1470 x = add 1 2
1471 \stopbuffer
1472
1473 \startbuffer[to]
1474 x = let x = add 1 2 in x
1475 \stopbuffer
1476
1477 \transexample{Return value simplification}{from}{to}