Enable interaction (clickable links) in the table of contents.
[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 \section{Transformation notation}
377 To be able to concisely present transformations, we use a specific format to
378 them. It is a simple format, similar to one used in logic reasoning.
379
380 Such a transformation description looks like the following.
381
382 \starttrans
383 <context conditions>
384 ~
385 <original expression>
386 --------------------------          <expression conditions>
387 <transformed expresssion>
388 ~
389 <context additions>
390 \stoptrans
391
392 This format desribes a transformation that applies to \lam{original
393 expresssion} and transforms it into \lam{transformed expression}, assuming
394 that all conditions apply. In this format, there are a number of placeholders
395 in pointy brackets, most of which should be rather obvious in their meaning.
396 Nevertheless, we will more precisely specify their meaning below:
397
398   \startdesc{<original expression>} The expression pattern that will be matched
399   against (subexpressions of) the expression to be transformed. We call this a
400   pattern, because it can contain \emph{placeholders} (variables), which match
401   any expression or binder. Any such placeholder is said to be \emph{bound} to
402   the expression it matches. It is convention to use an uppercase latter (\eg
403   \lam{M} or \lam{E} to refer to any expression (including a simple variable
404   reference) and lowercase letters (\eg \lam{v} or \lam{b}) to refer to
405   (references to) binders.
406
407   For example, the pattern \lam{a + B} will match the expression 
408   \lam{v + (2 * w)} (and bind \lam{a} to \lam{v} and \lam{B} to 
409   \lam{(2 * 2)}), but not \lam{v + (2 * w)}.
410   \stopdesc
411
412   \startdesc{<expression conditions>}
413   These are extra conditions on the expression that is matched. These
414   conditions can be used to further limit the cases in which the
415   transformation applies, in particular to prevent a transformation from
416   causing a loop with itself or another transformation.
417
418   Only if these if these conditions are \emph{all} true, this transformation
419   applies.
420   \stopdesc
421
422   \startdesc{<context conditions>}
423   These are a number of extra conditions on the context of the function. In
424   particular, these conditions can require some other top level function to be
425   present, whose value matches the pattern given here. The format of each of
426   these conditions is: \lam{binder = <pattern>}.
427
428   Typically, the binder is some placeholder bound in the \lam{<original
429   expression>}, while the pattern contains some placeholders that are used in
430   the \lam{transformed expression}.
431   
432   Only if a top level binder exists that matches each binder and pattern, this
433   transformation applies.
434   \stopdesc
435
436   \startdesc{<transformed expression>}
437   This is the expression template that is the result of the transformation. If, looking
438   at the above three items, the transformation applies, the \lam{original
439   expression} is completely replaced with the \lam{<transformed expression>}.
440   We call this a template, because it can contain placeholders, referring to
441   any placeholder bound by the \lam{<original expression>} or the
442   \lam{<context conditions>}. The resulting expression will have those
443   placeholders replaced by the values bound to them.
444
445   Any binder (lowercase) placeholder that has no value bound to it yet will be
446   bound to (and replaced with) a fresh binder.
447   \stopdesc
448
449   \startdesc{<context additions>}
450   These are templates for new functions to add to the context. This is a way
451   to have a transformation create new top level functiosn.
452
453   Each addition has the form \lam{binder = template}. As above, any
454   placeholder in the addition is replaced with the value bound to it, and any
455   binder placeholder that has no value bound to it yet will be bound to (and
456   replaced with) a fresh binder.
457   \stopdesc
458
459   As an example, we'll look at η-abstraction:
460
461 \starttrans
462 E                 \lam{E :: a -> b}
463 --------------    \lam{E} does not occur on a function position in an application
464 λx.E x            \lam{E} is not a lambda abstraction.
465 \stoptrans
466
467   Consider the following function, which is a fairly obvious way to specify a
468   simple ALU (Note \at{example}[ex:AddSubAlu] is the normal form of this
469   function):
470
471 \startlambda 
472 alu :: Bit -> Word -> Word -> Word
473 alu = λopcode. case opcode of
474   Low -> (+)
475   High -> (-)
476 \stoplambda
477
478   There are a few subexpressions in this function to which we could possibly
479   apply the transformation. Since the pattern of the transformation is only
480   the placeholder \lam{E}, any expression will match that. Whether the
481   transformation applies to an expression is thus solely decided by the
482   conditions to the right of the transformation.
483
484   We will look at each expression in the function in a top down manner. The
485   first expression is the entire expression the function is bound to.
486
487 \startlambda
488 λopcode. case opcode of
489   Low -> (+)
490   High -> (-)
491 \stoplambda
492
493   As said, the expression pattern matches this. The type of this expression is
494   \lam{Bit -> Word -> Word -> Word}, which matches \lam{a -> b} (Note that in
495   this case \lam{a = Bit} and \lam{b = Word -> Word -> Word}).
496
497   Since this expression is at top level, it does not occur at a function
498   position of an application. However, The expression is a lambda abstraction,
499   so this transformation does not apply.
500
501   The next expression we could apply this transformation to, is the body of
502   the lambda abstraction:
503
504 \startlambda
505 case opcode of
506   Low -> (+)
507   High -> (-)
508 \stoplambda
509
510   The type of this expression is \lam{Word -> Word -> Word}, which again
511   matches \lam{a -> b}. The expression is the body of a lambda expression, so
512   it does not occur at a function position of an application. Finally, the
513   expression is not a lambda abstraction but a case expression, so all the
514   conditions match. There are no context conditions to match, so the
515   transformation applies.
516
517   By now, the placeholder \lam{E} is bound to the entire expression. The
518   placeholder \lam{x}, which occurs in the replacement template, is not bound
519   yet, so we need to generate a fresh binder for that. Let's use the binder
520   \lam{a}. This results in the following replacement expression:
521
522 \startlambda
523 λa.(case opcode of
524   Low -> (+)
525   High -> (-)) a
526 \stoplambda
527
528   Continuing with this expression, we see that the transformation does not
529   apply again (it is a lambda expression). Next we look at the body of this
530   labmda abstraction:
531
532 \startlambda
533 (case opcode of
534   Low -> (+)
535   High -> (-)) a
536 \stoplambda
537   
538   Here, the transformation does apply, binding \lam{E} to the entire
539   expression and \lam{x} to the fresh binder \lam{b}, resulting in the
540   replacement:
541
542 \startlambda
543 λb.(case opcode of
544   Low -> (+)
545   High -> (-)) a b
546 \stoplambda
547
548   Again, the transformation does not apply to this lambda abstraction, so we
549   look at its body. For brevity, we'll put the case statement on one line from
550   now on.
551
552 \startlambda
553 (case opcode of Low -> (+); High -> (-)) a b
554 \stoplambda
555
556   The type of this expression is \lam{Word}, so it does not match \lam{a -> b}
557   and the transformation does not apply. Next, we have two options for the
558   next expression to look at: The function position and argument position of
559   the application. The expression in the argument position is \lam{b}, which
560   has type \lam{Word}, so the transformation does not apply. The expression in
561   the function position is:
562
563 \startlambda
564 (case opcode of Low -> (+); High -> (-)) a
565 \stoplambda
566
567   Obviously, the transformation does not apply here, since it occurs in
568   function position. In the same way the transformation does not apply to both
569   components of this expression (\lam{case opcode of Low -> (+); High -> (-)}
570   and \lam{a}), so we'll skip to the components of the case expression: The
571   scrutinee and both alternatives. Since the opcode is not a function, it does
572   not apply here, and we'll leave both alternatives as an exercise to the
573   reader. The final function, after all these transformations becomes:
574
575 \startlambda 
576 alu :: Bit -> Word -> Word -> Word
577 alu = λopcode.λa.b. (case opcode of
578   Low -> λa1.λb1 (+) a1 b1
579   High -> λa2.λb2 (-) a2 b2) a b
580 \stoplambda
581
582   In this case, the transformation does not apply anymore, though this might
583   not always be the case (e.g., the application of a transformation on a
584   subexpression might open up possibilities to apply the transformation
585   further up in the expression).
586
587 \subsection{Transformation application}
588 In this chapter we define a number of transformations, but how will we apply
589 these? As stated before, our normal form is reached as soon as no
590 transformation applies anymore. This means our application strategy is to
591 simply apply any transformation that applies, and continuing to do that with
592 the result of each transformation.
593
594 In particular, we define no particular order of transformations. Since
595 transformation order should not influence the resulting normal form (see TODO
596 ref), this leaves the implementation free to choose any application order that
597 results in an efficient implementation.
598
599 When applying a single transformation, we try to apply it to every (sub)expression
600 in a function, not just the top level function. This allows us to keep the
601 transformation descriptions concise and powerful.
602
603 \subsection{Definitions}
604 In the following sections, we will be using a number of functions and
605 notations, which we will define here.
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 \emph{local variable} is any
610 other variable (\eg, variables local to a function, which can be bound by
611 lambda abstractions, let expressions and pattern matches of case
612 alternatives).  Note that this is a slightly different notion of global versus
613 local than what \small{GHC} uses internally.
614 \defref{global variable} \defref{local variable}
615
616 A \emph{hardware representable} (or just \emph{representable}) type or value
617 is (a value of) a type that we can generate a signal for in hardware. For
618 example, a bit, a vector of bits, a 32 bit unsigned word, etc. Types that are
619 not runtime representable notably include (but are not limited to): Types,
620 dictionaries, functions.
621 \defref{representable}
622
623 A \emph{builtin function} is a function supplied by the Cλash framework, whose
624 implementation is not valid Cλash. The implementation is of course valid
625 Haskell, for simulation, but it is not expressable in Cλash.
626 \defref{builtin function} \defref{user-defined function}
627
628 For these functions, Cλash has a \emph{builtin hardware translation}, so calls
629 to these functions can still be translated. These are functions like
630 \lam{map}, \lam{hwor} and \lam{length}.
631
632 A \emph{user-defined} function is a function for which we do have a Cλash
633 implementation available.
634
635 \subsubsection{Functions}
636 Here, we define a number of functions that can be used below to concisely
637 specify conditions.
638
639 \refdef{global variable}\emph{gvar(expr)} is true when \emph{expr} is a variable that references a
640 global variable. It is false when it references a local variable.
641
642 \refdef{local variable}\emph{lvar(expr)} is the complement of \emph{gvar}; it is true when \emph{expr}
643 references a local variable, false when it references a global variable.
644
645 \refdef{representable}\emph{representable(expr)} or \emph{representable(var)} is true when
646 \emph{expr} or \emph{var} is \emph{representable}.
647
648 \subsection{Binder uniqueness}
649 A common problem in transformation systems, is binder uniqueness. When not
650 considering this problem, it is easy to create transformations that mix up
651 bindings and cause name collisions. Take for example, the following core
652 expression:
653
654 \startlambda
655 (λa.λb.λc. a * b * c) x c
656 \stoplambda
657
658 By applying β-reduction (see below) once, we can simplify this expression to:
659
660 \startlambda
661 (λb.λc. x * b * c) c
662 \stoplambda
663
664 Now, we have replaced the \lam{a} binder with a reference to the \lam{x}
665 binder. No harm done here. But note that we see multiple occurences of the
666 \lam{c} binder. The first is a binding occurence, to which the second refers.
667 The last, however refers to \emph{another} instance of \lam{c}, which is
668 bound somewhere outside of this expression. Now, if we would apply beta
669 reduction without taking heed of binder uniqueness, we would get:
670
671 \startlambda
672 λc. x * c * c
673 \stoplambda
674
675 This is obviously not what was supposed to happen! The root of this problem is
676 the reuse of binders: Identical binders can be bound in different scopes, such
677 that only the inner one is \quote{visible} in the inner expression. In the example
678 above, the \lam{c} binder was bound outside of the expression and in the inner
679 lambda expression. Inside that lambda expression, only the inner \lam{c} is
680 visible.
681
682 There are a number of ways to solve this. \small{GHC} has isolated this
683 problem to their binder substitution code, which performs \emph{deshadowing}
684 during its expression traversal. This means that any binding that shadows
685 another binding on a higher level is replaced by a new binder that does not
686 shadow any other binding. This non-shadowing invariant is enough to prevent
687 binder uniqueness problems in \small{GHC}.
688
689 In our transformation system, maintaining this non-shadowing invariant is
690 a bit harder to do (mostly due to implementation issues, the prototype doesn't
691 use \small{GHC}'s subsitution code). Also, we can observe the following
692 points.
693
694 \startitemize
695 \item Deshadowing does not guarantee overall uniqueness. For example, the
696 following (slightly contrived) expression shows the identifier \lam{x} bound in
697 two seperate places (and to different values), even though no shadowing
698 occurs.
699
700 \startlambda
701 (let x = 1 in x) + (let x = 2 in x)
702 \stoplambda
703
704 \item In our normal form (and the resulting \small{VHDL}), all binders
705 (signals) will end up in the same scope. To allow this, all binders within the
706 same function should be unique.
707
708 \item When we know that all binders in an expression are unique, moving around
709 or removing a subexpression will never cause any binder conflicts. If we have
710 some way to generate fresh binders, introducing new subexpressions will not
711 cause any problems either. The only way to cause conflicts is thus to
712 duplicate an existing subexpression.
713 \stopitemize
714
715 Given the above, our prototype maintains a unique binder invariant. This
716 meanst that in any given moment during normalization, all binders \emph{within
717 a single function} must be unique. To achieve this, we apply the following
718 technique.
719
720 TODO: Define fresh binders and unique supplies
721
722 \startitemize
723 \item Before starting normalization, all binders in the function are made
724 unique. This is done by generating a fresh binder for every binder used. This
725 also replaces binders that did not pose any conflict, but it does ensure that
726 all binders within the function are generated by the same unique supply. See
727 (TODO: ref fresh binder).
728 \item Whenever a new binder must be generated, we generate a fresh binder that
729 is guaranteed to be different from \emph{all binders generated so far}. This
730 can thus never introduce duplication and will maintain the invariant.
731 \item Whenever (part of) an expression is duplicated (for example when
732 inlining), all binders in the expression are replaced with fresh binders
733 (using the same method as at the start of normalization). These fresh binders
734 can never introduce duplication, so this will maintain the invariant.
735 \item Whenever we move part of an expression around within the function, there
736 is no need to do anything special. There is obviously no way to introduce
737 duplication by moving expressions around. Since we know that each of the
738 binders is already unique, there is no way to introduce (incorrect) shadowing
739 either.
740 \stopitemize
741
742 \section{Transform passes}
743 In this section we describe the actual transforms. Here we're using
744 the core language in a notation that resembles lambda calculus.
745
746 Each of these transforms is meant to be applied to every (sub)expression
747 in a program, for as long as it applies. Only when none of the
748 transformations can be applied anymore, the program is in normal form (by
749 definition). We hope to be able to prove that this form will obey all of the
750 constraints defined above, but this has yet to happen (though it seems likely
751 that it will).
752
753 Each of the transforms will be described informally first, explaining
754 the need for and goal of the transform. Then, a formal definition is
755 given, using a familiar syntax from the world of logic. Each transform
756 is specified as a number of conditions (above the horizontal line) and a
757 number of conclusions (below the horizontal line). The details of using
758 this notation are still a bit fuzzy, so comments are welcom.
759
760 \subsection{η-abstraction}
761 This transformation makes sure that all arguments of a function-typed
762 expression are named, by introducing lambda expressions. When combined with
763 β-reduction and function inlining below, all function-typed expressions should
764 be lambda abstractions or global identifiers.
765
766 \starttrans
767 E                 \lam{E :: a -> b}
768 --------------    \lam{E} is not the first argument of an application.
769 λx.E x            \lam{E} is not a lambda abstraction.
770                   \lam{x} is a variable that does not occur free in \lam{E}.
771 \stoptrans
772
773 \startbuffer[from]
774 foo = λa.case a of 
775   True -> λb.mul b b
776   False -> id
777 \stopbuffer
778
779 \startbuffer[to]
780 foo = λa.λx.(case a of 
781     True -> λb.mul b b
782     False -> λy.id y) x
783 \stopbuffer
784
785 \transexample{η-abstraction}{from}{to}
786
787 \subsection{Extended β-reduction}
788 This transformation is meant to propagate application expressions downwards
789 into expressions as far as possible. In lambda calculus, this reduction
790 is known as β-reduction, but it is of course only defined for
791 applications of lambda abstractions. We extend this reduction to also
792 work for the rest of core (case and let expressions).
793
794 For let expressions:
795 \starttrans
796 let binds in E) M
797 -----------------
798 let binds in E M
799 \stoptrans
800
801 For case statements:
802 \starttrans
803 (case x of
804   p1 -> E1
805   \vdots
806   pn -> En) M
807 -----------------
808 case x of
809   p1 -> E1 M
810   \vdots
811   pn -> En M
812 \stoptrans
813
814 For lambda expressions:
815 \starttrans
816 (λx.E) M
817 -----------------
818 E[M/x]
819 \stoptrans
820
821 % And an example
822 \startbuffer[from]
823 ( let a = (case x of 
824             True -> id
825             False -> neg
826           ) 1
827       b = (let y = 3 in add y) 2
828   in
829     (λz.add 1 z)
830 ) 3
831 \stopbuffer
832
833 \startbuffer[to]
834 let a = case x of 
835            True -> id 1
836            False -> neg 1
837     b = let y = 3 in add y 2
838 in
839   add 1 3
840 \stopbuffer
841
842 \transexample{Extended β-reduction}{from}{to}
843
844 \subsection{Let derecursification}
845 This transformation is meant to make lets non-recursive whenever possible.
846 This might allow other optimizations to do their work better. TODO: Why is
847 this needed exactly?
848
849 \subsection{Let flattening}
850 This transformation puts nested lets in the same scope, by lifting the
851 binding(s) of the inner let into a new let around the outer let. Eventually,
852 this will cause all let bindings to appear in the same scope (they will all be
853 in scope for the function return value).
854
855 Note that this transformation does not try to be smart when faced with
856 recursive lets, it will just leave the lets recursive (possibly joining a
857 recursive and non-recursive let into a single recursive let). The let
858 rederursification transformation will do this instead.
859
860 \starttrans
861 letnonrec x = (let bindings in M) in N
862 ------------------------------------------
863 let bindings in (letnonrec x = M) in N
864 \stoptrans
865
866 \starttrans
867 letrec 
868   \vdots
869   x = (let bindings in M)
870   \vdots
871 in
872   N
873 ------------------------------------------
874 letrec
875   \vdots
876   bindings
877   x = M
878   \vdots
879 in
880   N
881 \stoptrans
882
883 \startbuffer[from]
884 let
885   a = letrec
886     x = 1
887     y = 2
888   in
889     x + y
890 in
891   letrec
892     b = let c = 3 in a + c
893     d = 4
894   in
895     d + b
896 \stopbuffer
897 \startbuffer[to]
898 letrec
899   x = 1
900   y = 2
901 in
902   let
903     a = x + y
904   in
905     letrec
906       c = 3
907       b = a + c
908       d = 4
909     in
910       d + b
911 \stopbuffer
912
913 \transexample{Let flattening}{from}{to}
914
915 \subsection{Empty let removal}
916 This transformation is simple: It removes recursive lets that have no bindings
917 (which usually occurs when let derecursification removes the last binding from
918 it).
919
920 \starttrans
921 letrec in M
922 --------------
923 M
924 \stoptrans
925
926 \subsection{Simple let binding removal}
927 This transformation inlines simple let bindings (\eg a = b).
928
929 This transformation is not needed to get into normal form, but makes the
930 resulting \small{VHDL} a lot shorter.
931
932 \starttrans
933 letnonrec
934   a = b
935 in
936   M
937 -----------------
938 M[b/a]
939 \stoptrans
940
941 \starttrans
942 letrec
943   \vdots
944   a = b
945   \vdots
946 in
947   M
948 -----------------
949 let
950   \vdots [b/a]
951   \vdots [b/a]
952 in
953   M[b/a]
954 \stoptrans
955
956 \subsection{Unused let binding removal}
957 This transformation removes let bindings that are never used. Usually,
958 the desugarer introduces some unused let bindings.
959
960 This normalization pass should really be unneeded to get into normal form
961 (since ununsed bindings are not forbidden by the normal form), but in practice
962 the desugarer or simplifier emits some unused bindings that cannot be
963 normalized (e.g., calls to a \type{PatError} (TODO: Check this name)). Also,
964 this transformation makes the resulting \small{VHDL} a lot shorter.
965
966 \starttrans
967 let a = E in M
968 ----------------------------    \lam{a} does not occur free in \lam{M}
969 M
970 \stoptrans
971
972 \starttrans
973 letrec
974   \vdots
975   a = E
976   \vdots
977 in
978   M
979 ----------------------------    \lam{a} does not occur free in \lam{M}
980 letrec
981   \vdots
982   \vdots
983 in
984   M
985 \stoptrans
986
987 \subsection{Non-representable binding inlining}
988 This transform inlines let bindings that have a non-representable type. Since
989 we can never generate a signal assignment for these bindings (we cannot
990 declare a signal assignment with a non-representable type, for obvious
991 reasons), we have no choice but to inline the binding to remove it.
992
993 If the binding is non-representable because it is a lambda abstraction, it is
994 likely that it will inlined into an application and β-reduction will remove
995 the lambda abstraction and turn it into a representable expression at the
996 inline site. The same holds for partial applications, which can be turned into
997 full applications by inlining.
998
999 Other cases of non-representable bindings we see in practice are primitive
1000 Haskell types. In most cases, these will not result in a valid normalized
1001 output, but then the input would have been invalid to start with. There is one
1002 exception to this: When a builtin function is applied to a non-representable
1003 expression, things might work out in some cases. For example, when you write a
1004 literal \hs{SizedInt} in Haskell, like \hs{1 :: SizedInt D8}, this results in
1005 the following core: \lam{fromInteger (smallInteger 10)}, where for example
1006 \lam{10 :: GHC.Prim.Int\#} and \lam{smallInteger 10 :: Integer} have
1007 non-representable types. TODO: This/these paragraph(s) should probably become a
1008 separate discussion somewhere else.
1009
1010 \starttrans
1011 letnonrec a = E in M
1012 --------------------------    \lam{E} has a non-representable type.
1013 M[E/a]
1014 \stoptrans
1015
1016 \starttrans
1017 letrec 
1018   \vdots
1019   a = E
1020   \vdots
1021 in
1022   M
1023 --------------------------    \lam{E} has a non-representable type.
1024 letrec
1025   \vdots [E/a]
1026   \vdots [E/a]
1027 in
1028   M[E/a]
1029 \stoptrans
1030
1031 \startbuffer[from]
1032 letrec
1033   a = smallInteger 10
1034   inc = λa -> add a 1
1035   inc' = add 1
1036   x = fromInteger a 
1037 in
1038   inc (inc' x)
1039 \stopbuffer
1040
1041 \startbuffer[to]
1042 letrec
1043   x = fromInteger (smallInteger 10)
1044 in
1045   (λa -> add a 1) (add 1 x)
1046 \stopbuffer
1047
1048 \transexample{Let flattening}{from}{to}
1049
1050 \subsection{Compiler generated top level binding inlining}
1051 TODO
1052
1053 \subsection{Scrutinee simplification}
1054 This transform ensures that the scrutinee of a case expression is always
1055 a simple variable reference.
1056
1057 \starttrans
1058 case E of
1059   alts
1060 -----------------        \lam{E} is not a local variable reference
1061 let x = E in 
1062   case E of
1063     alts
1064 \stoptrans
1065
1066 \startbuffer[from]
1067 case (foo a) of
1068   True -> a
1069   False -> b
1070 \stopbuffer
1071
1072 \startbuffer[to]
1073 let x = foo a in
1074   case x of
1075     True -> a
1076     False -> b
1077 \stopbuffer
1078
1079 \transexample{Let flattening}{from}{to}
1080
1081
1082 \subsection{Case simplification}
1083 This transformation ensures that all case expressions become normal form. This
1084 means they will become one of:
1085 \startitemize
1086 \item An extractor case with a single alternative that picks a single field
1087 from a datatype, \eg \lam{case x of (a, b) -> a}.
1088 \item A selector case with multiple alternatives and only wild binders, that
1089 makes a choice between expressions based on the constructor of another
1090 expression, \eg \lam{case x of Low -> a; High -> b}.
1091 \stopitemize
1092
1093 \starttrans
1094 case E of
1095   C0 v0,0 ... v0,m -> E0
1096   \vdots
1097   Cn vn,0 ... vn,m -> En
1098 --------------------------------------------------- \forall i \forall j, 0 <= i <= n, 0 <= i < m (\lam{wi,j} is a wild (unused) binder)
1099 letnonrec
1100   v0,0 = case x of C0 v0,0 .. v0,m -> v0,0
1101   \vdots
1102   v0,m = case x of C0 v0,0 .. v0,m -> v0,m
1103   x0 = E0
1104   \dots
1105   vn,m = case x of Cn vn,0 .. vn,m -> vn,m
1106   xn = En
1107 in
1108   case E of
1109     C0 w0,0 ... w0,m -> x0
1110     \vdots
1111     Cn wn,0 ... wn,m -> xn
1112 \stoptrans
1113
1114 TODO: This transformation specified like this is complicated and misses
1115 conditions to prevent looping with itself. Perhaps we should split it here for
1116 discussion?
1117
1118 \startbuffer[from]
1119 case a of
1120   True -> add b 1
1121   False -> add b 2
1122 \stopbuffer
1123
1124 \startbuffer[to]
1125 letnonrec
1126   x0 = add b 1
1127   x1 = add b 2
1128 in
1129   case a of
1130     True -> x0
1131     False -> x1
1132 \stopbuffer
1133
1134 \transexample{Selector case simplification}{from}{to}
1135
1136 \startbuffer[from]
1137 case a of
1138   (,) b c -> add b c
1139 \stopbuffer
1140 \startbuffer[to]
1141 letnonrec
1142   b = case a of (,) b c -> b
1143   c = case a of (,) b c -> c
1144   x0 = add b c
1145 in
1146   case a of
1147     (,) w0 w1 -> x0
1148 \stopbuffer
1149
1150 \transexample{Extractor case simplification}{from}{to}
1151
1152 \subsection{Case removal}
1153 This transform removes any case statements with a single alternative and
1154 only wild binders.
1155
1156 These "useless" case statements are usually leftovers from case simplification
1157 on extractor case (see the previous example).
1158
1159 \starttrans
1160 case x of
1161   C v0 ... vm -> E
1162 ----------------------     \lam{\forall i, 0 <= i <= m} (\lam{vi} does not occur free in E)
1163 E
1164 \stoptrans
1165
1166 \startbuffer[from]
1167 case a of
1168   (,) w0 w1 -> x0
1169 \stopbuffer
1170
1171 \startbuffer[to]
1172 x0
1173 \stopbuffer
1174
1175 \transexample{Case removal}{from}{to}
1176
1177 \subsection{Argument simplification}
1178 The transforms in this section deal with simplifying application
1179 arguments into normal form. The goal here is to:
1180
1181 \startitemize
1182  \item Make all arguments of user-defined functions (\eg, of which
1183  we have a function body) simple variable references of a runtime
1184  representable type. This is needed, since these applications will be turned
1185  into component instantiations.
1186  \item Make all arguments of builtin functions one of:
1187    \startitemize
1188     \item A type argument.
1189     \item A dictionary argument.
1190     \item A type level expression.
1191     \item A variable reference of a runtime representable type.
1192     \item A variable reference or partial application of a function type.
1193    \stopitemize
1194 \stopitemize
1195
1196 When looking at the arguments of a user-defined function, we can
1197 divide them into two categories:
1198 \startitemize
1199   \item Arguments of a runtime representable type (\eg bits or vectors).
1200
1201         These arguments can be preserved in the program, since they can
1202         be translated to input ports later on.  However, since we can
1203         only connect signals to input ports, these arguments must be
1204         reduced to simple variables (for which signals will be
1205         produced). This is taken care of by the argument extraction
1206         transform.
1207   \item Non-runtime representable typed arguments.
1208         
1209         These arguments cannot be preserved in the program, since we
1210         cannot represent them as input or output ports in the resulting
1211         \small{VHDL}. To remove them, we create a specialized version of the
1212         called function with these arguments filled in. This is done by
1213         the argument propagation transform.
1214
1215         Typically, these arguments are type and dictionary arguments that are
1216         used to make functions polymorphic. By propagating these arguments, we
1217         are essentially doing the same which GHC does when it specializes
1218         functions: Creating multiple variants of the same function, one for
1219         each type for which it is used. Other common non-representable
1220         arguments are functions, e.g. when calling a higher order function
1221         with another function or a lambda abstraction as an argument.
1222
1223         The reason for doing this is similar to the reasoning provided for
1224         the inlining of non-representable let bindings above. In fact, this
1225         argument propagation could be viewed as a form of cross-function
1226         inlining.
1227 \stopitemize
1228
1229 TODO: Check the following itemization.
1230
1231 When looking at the arguments of a builtin function, we can divide them
1232 into categories: 
1233
1234 \startitemize
1235   \item Arguments of a runtime representable type.
1236         
1237         As we have seen with user-defined functions, these arguments can
1238         always be reduced to a simple variable reference, by the
1239         argument extraction transform. Performing this transform for
1240         builtin functions as well, means that the translation of builtin
1241         functions can be limited to signal references, instead of
1242         needing to support all possible expressions.
1243
1244   \item Arguments of a function type.
1245         
1246         These arguments are functions passed to higher order builtins,
1247         like \lam{map} and \lam{foldl}. Since implementing these
1248         functions for arbitrary function-typed expressions (\eg, lambda
1249         expressions) is rather comlex, we reduce these arguments to
1250         (partial applications of) global functions.
1251         
1252         We can still support arbitrary expressions from the user code,
1253         by creating a new global function containing that expression.
1254         This way, we can simply replace the argument with a reference to
1255         that new function. However, since the expression can contain any
1256         number of free variables we also have to include partial
1257         applications in our normal form.
1258
1259         This category of arguments is handled by the function extraction
1260         transform.
1261   \item Other unrepresentable arguments.
1262         
1263         These arguments can take a few different forms:
1264         \startdesc{Type arguments}
1265           In the core language, type arguments can only take a single
1266           form: A type wrapped in the Type constructor. Also, there is
1267           nothing that can be done with type expressions, except for
1268           applying functions to them, so we can simply leave type
1269           arguments as they are.
1270         \stopdesc
1271         \startdesc{Dictionary arguments}
1272           In the core language, dictionary arguments are used to find
1273           operations operating on one of the type arguments (mostly for
1274           finding class methods). Since we will not actually evaluatie
1275           the function body for builtin functions and can generate
1276           code for builtin functions by just looking at the type
1277           arguments, these arguments can be ignored and left as they
1278           are.
1279         \stopdesc
1280         \startdesc{Type level arguments}
1281           Sometimes, we want to pass a value to a builtin function, but
1282           we need to know the value at compile time. Additionally, the
1283           value has an impact on the type of the function. This is
1284           encoded using type-level values, where the actual value of the
1285           argument is not important, but the type encodes some integer,
1286           for example. Since the value is not important, the actual form
1287           of the expression does not matter either and we can leave
1288           these arguments as they are.
1289         \stopdesc
1290         \startdesc{Other arguments}
1291           Technically, there is still a wide array of arguments that can
1292           be passed, but does not fall into any of the above categories.
1293           However, none of the supported builtin functions requires such
1294           an argument. This leaves use with passing unsupported types to
1295           a function, such as calling \lam{head} on a list of functions.
1296
1297           In these cases, it would be impossible to generate hardware
1298           for such a function call anyway, so we can ignore these
1299           arguments.
1300
1301           The only way to generate hardware for builtin functions with
1302           arguments like these, is to expand the function call into an
1303           equivalent core expression (\eg, expand map into a series of
1304           function applications). But for now, we choose to simply not
1305           support expressions like these.
1306         \stopdesc
1307
1308         From the above, we can conclude that we can simply ignore these
1309         other unrepresentable arguments and focus on the first two
1310         categories instead.
1311 \stopitemize
1312
1313 \subsubsection{Argument simplification}
1314 This transform deals with arguments to functions that
1315 are of a runtime representable type. It ensures that they will all become
1316 references to global variables, or local signals in the resulting \small{VHDL}. 
1317
1318 TODO: It seems we can map an expression to a port, not only a signal.
1319 Perhaps this makes this transformation not needed?
1320 TODO: Say something about dataconstructors (without arguments, like True
1321 or False), which are variable references of a runtime representable
1322 type, but do not result in a signal.
1323
1324 To reduce a complex expression to a simple variable reference, we create
1325 a new let expression around the application, which binds the complex
1326 expression to a new variable. The original function is then applied to
1327 this variable.
1328
1329 \starttrans
1330 M N
1331 --------------------    \lam{N} is of a representable type
1332 let x = N in M x        \lam{N} is not a local variable reference
1333 \stoptrans
1334
1335 \startbuffer[from]
1336 add (add a 1) 1
1337 \stopbuffer
1338
1339 \startbuffer[to]
1340 let x = add a 1 in add x 1
1341 \stopbuffer
1342
1343 \transexample{Argument extraction}{from}{to}
1344
1345 \subsubsection{Function extraction}
1346 This transform deals with function-typed arguments to builtin functions.
1347 Since these arguments cannot be propagated, we choose to extract them
1348 into a new global function instead.
1349
1350 Any free variables occuring in the extracted arguments will become
1351 parameters to the new global function. The original argument is replaced
1352 with a reference to the new function, applied to any free variables from
1353 the original argument.
1354
1355 This transformation is useful when applying higher order builtin functions
1356 like \hs{map} to a lambda abstraction, for example. In this case, the code
1357 that generates \small{VHDL} for \hs{map} only needs to handle top level functions and
1358 partial applications, not any other expression (such as lambda abstractions or
1359 even more complicated expressions).
1360
1361 \starttrans
1362 M N                     \lam{M} is a (partial aplication of a) builtin function.
1363 ---------------------   \lam{f0 ... fn} = free local variables of \lam{N}
1364 M x f0 ... fn           \lam{N :: a -> b}
1365 ~                       \lam{N} is not a (partial application of) a top level function
1366 x = λf0 ... λfn.N
1367 \stoptrans
1368
1369 \startbuffer[from]
1370 map (λa . add a b) xs
1371
1372 map (add b) ys
1373 \stopbuffer
1374
1375 \startbuffer[to]
1376 x0 = λb.λa.add a b
1377 ~
1378 map x0 xs
1379
1380 x1 = λb.add b
1381 map x1 ys
1382 \stopbuffer
1383
1384 \transexample{Function extraction}{from}{to}
1385
1386 \subsubsection{Argument propagation}
1387 This transform deals with arguments to user-defined functions that are
1388 not representable at runtime. This means these arguments cannot be
1389 preserved in the final form and most be {\em propagated}.
1390
1391 Propagation means to create a specialized version of the called
1392 function, with the propagated argument already filled in. As a simple
1393 example, in the following program:
1394
1395 \startlambda
1396 f = λa.λb.a + b
1397 inc = λa.f a 1
1398 \stoplambda
1399
1400 we could {\em propagate} the constant argument 1, with the following
1401 result:
1402
1403 \startlambda
1404 f' = λa.a + 1
1405 inc = λa.f' a
1406 \stoplambda
1407
1408 Special care must be taken when the to-be-propagated expression has any
1409 free variables. If this is the case, the original argument should not be
1410 removed alltogether, but replaced by all the free variables of the
1411 expression. In this way, the original expression can still be evaluated
1412 inside the new function. Also, this brings us closer to our goal: All
1413 these free variables will be simple variable references.
1414
1415 To prevent us from propagating the same argument over and over, a simple
1416 local variable reference is not propagated (since is has exactly one
1417 free variable, itself, we would only replace that argument with itself).
1418
1419 This shows that any free local variables that are not runtime representable
1420 cannot be brought into normal form by this transform. We rely on an
1421 inlining transformation to replace such a variable with an expression we
1422 can propagate again.
1423
1424 \starttrans
1425 x = E
1426 ~
1427 x Y0 ... Yi ... Yn                               \lam{Yi} is not of a runtime representable type
1428 ---------------------------------------------    \lam{Yi} is not a local variable reference
1429 x' y0 ... yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} = free local vars of \lam{Yi}
1430 ~
1431 x' = λy0 ... yi-1 f0 ... fm yi+1 ... yn .       
1432       E y0 ... yi-1 Yi yi+1 ... yn   
1433
1434 \stoptrans
1435
1436 TODO: Example
1437
1438 \subsection{Cast propagation / simplification}
1439 This transform pushes casts down into the expression as far as possible. Since
1440 its exact role and need is not clear yet, this transformation is not yet
1441 specified.
1442
1443 \subsection{Return value simplification}
1444 This transformation ensures that the return value of a function is always a
1445 simple local variable reference.
1446
1447 Currently implemented using lambda simplification, let simplification, and
1448 top simplification. Should change into something like the following, which
1449 works only on the result of a function instead of any subexpression. This is
1450 achieved by the contexts, like \lam{x = E}, though this is strictly not
1451 correct (you could read this as "if there is any function \lam{x} that binds
1452 \lam{E}, any \lam{E} can be transformed, while we only mean the \lam{E} that
1453 is bound by \lam{x}. This might need some extra notes or something).
1454
1455 \starttrans
1456 x = E                            \lam{E} is representable
1457 ~                                \lam{E} is not a lambda abstraction
1458 E                                \lam{E} is not a let expression
1459 ---------------------------      \lam{E} is not a local variable reference
1460 let x = E in x
1461 \stoptrans
1462
1463 \starttrans
1464 x = λv0 ... λvn.E
1465 ~                                \lam{E} is representable
1466 E                                \lam{E} is not a let expression
1467 ---------------------------      \lam{E} is not a local variable reference
1468 let x = E in x
1469 \stoptrans
1470
1471 \starttrans
1472 x = λv0 ... λvn.let ... in E
1473 ~                                \lam{E} is representable
1474 E                                \lam{E} is not a local variable reference
1475 ---------------------------
1476 let x = E in x
1477 \stoptrans
1478
1479 \startbuffer[from]
1480 x = add 1 2
1481 \stopbuffer
1482
1483 \startbuffer[to]
1484 x = let x = add 1 2 in x
1485 \stopbuffer
1486
1487 \transexample{Return value simplification}{from}{to}