Fix reference.
[matthijs/master-project/report.git] / Chapters / Normalization.tex
1 \chapter[chap:normalization]{Normalization}
2   % A helper to print a single example in the half the page width. The example
3   % text should be in a buffer whose name is given in an argument.
4   %
5   % The align=right option really does left-alignment, but without the program
6   % will end up on a single line. The strut=no option prevents a bunch of empty
7   % space at the start of the frame.
8   \define[1]\example{
9     \framed[offset=1mm,align=right,strut=no,background=box,frame=off]{
10       \setuptyping[option=LAM,style=sans,before=,after=,strip=auto]
11       \typebuffer[#1]
12       \setuptyping[option=none,style=\tttf,strip=auto]
13     }
14   }
15
16   \define[4]\transexample{
17     \placeexample[here][ex:trans:#1]{#2}
18     \startcombination[2*1]
19       {\example{#3}}{Original program}
20       {\example{#4}}{Transformed program}
21     \stopcombination
22   }
23
24   The first step in the core to \small{VHDL} translation process, is normalization. We
25   aim to bring the core description into a simpler form, which we can
26   subsequently translate into \small{VHDL} easily. This normal form is needed because
27   the full core language is more expressive than \small{VHDL} in some areas and because
28   core can describe expressions that do not have a direct hardware
29   interpretation.
30
31   \todo{Describe core properties not supported in \VHDL, and describe how the
32   \VHDL we want to generate should look like.}
33
34   \section{Normal form}
35     \todo{Refresh or refer to distinct hardware per application principle}
36     The transformations described here have a well-defined goal: To bring the
37     program in a well-defined form that is directly translatable to hardware,
38     while fully preserving the semantics of the program. We refer to this form as
39     the \emph{normal form} of the program. The formal definition of this normal
40     form is quite simple:
41
42     \placedefinition{}{A program is in \emph{normal form} if none of the
43     transformations from this chapter apply.}
44
45     Of course, this is an \quote{easy} definition of the normal form, since our
46     program will end up in normal form automatically. The more interesting part is
47     to see if this normal form actually has the properties we would like it to
48     have.
49
50     But, before getting into more definitions and details about this normal form,
51     let's try to get a feeling for it first. The easiest way to do this is by
52     describing the things we want to not have in a normal form.
53
54     \startitemize
55       \item Any \emph{polymorphism} must be removed. When laying down hardware, we
56       can't generate any signals that can have multiple types. All types must be
57       completely known to generate hardware.
58       
59       \item Any \emph{higher order} constructions must be removed. We can't
60       generate a hardware signal that contains a function, so all values,
61       arguments and returns values used must be first order.
62
63       \item Any complex \emph{nested scopes} must be removed. In the \small{VHDL}
64       description, every signal is in a single scope. Also, full expressions are
65       not supported everywhere (in particular port maps can only map signal
66       names and constants, not complete expressions). To make the \small{VHDL}
67       generation easy, a separate binder must be bound to ever application or
68       other expression.
69     \stopitemize
70
71     \todo{Intermezzo: functions vs plain values}
72
73     A very simple example of a program in normal form is given in
74     \in{example}[ex:MulSum]. As you can see, all arguments to the function (which
75     will become input ports in the final hardware) are at the outer level.
76     This means that the body of the inner lambda abstraction is never a
77     function, but always a plain value.
78
79     As the body of the inner lambda abstraction, we see a single (recursive)
80     let expression, that binds two variables (\lam{mul} and \lam{sum}). These
81     variables will be signals in the final hardware, bound to the output port
82     of the \lam{*} and \lam{+} components.
83
84     The final line (the \quote{return value} of the function) selects the
85     \lam{sum} signal to be the output port of the function. This \quote{return
86     value} can always only be a variable reference, never a more complex
87     expression.
88
89     \todo{Add generated VHDL}
90
91     \startbuffer[MulSum]
92     alu :: Bit -> Word -> Word -> Word
93     alu = λa.λb.λc.
94         let
95           mul = (*) a b
96           sum = (+) mul c
97         in
98           sum
99     \stopbuffer
100
101     \startuseMPgraphic{MulSum}
102       save a, b, c, mul, add, sum;
103
104       % I/O ports
105       newCircle.a(btex $a$ etex) "framed(false)";
106       newCircle.b(btex $b$ etex) "framed(false)";
107       newCircle.c(btex $c$ etex) "framed(false)";
108       newCircle.sum(btex $res$ etex) "framed(false)";
109
110       % Components
111       newCircle.mul(btex * etex);
112       newCircle.add(btex + etex);
113
114       a.c      - b.c   = (0cm, 2cm);
115       b.c      - c.c   = (0cm, 2cm);
116       add.c            = c.c + (2cm, 0cm);
117       mul.c            = midpoint(a.c, b.c) + (2cm, 0cm);
118       sum.c            = add.c + (2cm, 0cm);
119       c.c              = origin;
120
121       % Draw objects and lines
122       drawObj(a, b, c, mul, add, sum);
123
124       ncarc(a)(mul) "arcangle(15)";
125       ncarc(b)(mul) "arcangle(-15)";
126       ncline(c)(add);
127       ncline(mul)(add);
128       ncline(add)(sum);
129     \stopuseMPgraphic
130
131     \placeexample[here][ex:MulSum]{Simple architecture consisting of a
132     multiplier and a subtractor.}
133       \startcombination[2*1]
134         {\typebufferlam{MulSum}}{Core description in normal form.}
135         {\boxedgraphic{MulSum}}{The architecture described by the normal form.}
136       \stopcombination
137
138     The previous example described composing an architecture by calling other
139     functions (operators), resulting in a simple architecture with components and
140     connections. There is of course also some mechanism for choice in the normal
141     form. In a normal Core program, the \emph{case} expression can be used in a
142     few different ways to describe choice. In normal form, this is limited to a
143     very specific form.
144
145     \in{Example}[ex:AddSubAlu] shows an example describing a
146     simple \small{ALU}, which chooses between two operations based on an opcode
147     bit. The main structure is similar to \in{example}[ex:MulSum], but this
148     time the \lam{res} variable is bound to a case expression. This case
149     expression scrutinizes the variable \lam{opcode} (and scrutinizing more
150     complex expressions is not supported). The case expression can select a
151     different variable based on the constructor of \lam{opcode}.
152
153     \startbuffer[AddSubAlu]
154     alu :: Bit -> Word -> Word -> Word
155     alu = λopcode.λa.λb.
156         let
157           res1 = (+) a b
158           res2 = (-) a b
159           res = case opcode of
160             Low -> res1
161             High -> res2
162         in
163           res
164     \stopbuffer
165
166     \startuseMPgraphic{AddSubAlu}
167       save opcode, a, b, add, sub, mux, res;
168
169       % I/O ports
170       newCircle.opcode(btex $opcode$ etex) "framed(false)";
171       newCircle.a(btex $a$ etex) "framed(false)";
172       newCircle.b(btex $b$ etex) "framed(false)";
173       newCircle.res(btex $res$ etex) "framed(false)";
174       % Components
175       newCircle.add(btex + etex);
176       newCircle.sub(btex - etex);
177       newMux.mux;
178
179       opcode.c - a.c   = (0cm, 2cm);
180       add.c    - a.c   = (4cm, 0cm);
181       sub.c    - b.c   = (4cm, 0cm);
182       a.c      - b.c   = (0cm, 3cm);
183       mux.c            = midpoint(add.c, sub.c) + (1.5cm, 0cm);
184       res.c    - mux.c = (1.5cm, 0cm);
185       b.c              = origin;
186
187       % Draw objects and lines
188       drawObj(opcode, a, b, res, add, sub, mux);
189
190       ncline(a)(add) "posA(e)";
191       ncline(b)(sub) "posA(e)";
192       nccurve(a)(sub) "posA(e)", "angleA(0)";
193       nccurve(b)(add) "posA(e)", "angleA(0)";
194       nccurve(add)(mux) "posB(inpa)", "angleB(0)";
195       nccurve(sub)(mux) "posB(inpb)", "angleB(0)";
196       nccurve(opcode)(mux) "posB(n)", "angleA(0)", "angleB(-90)";
197       ncline(mux)(res) "posA(out)";
198     \stopuseMPgraphic
199
200     \placeexample[here][ex:AddSubAlu]{Simple \small{ALU} supporting two operations.}
201       \startcombination[2*1]
202         {\typebufferlam{AddSubAlu}}{Core description in normal form.}
203         {\boxedgraphic{AddSubAlu}}{The architecture described by the normal form.}
204       \stopcombination
205
206     As a more complete example, consider \in{example}[ex:NormalComplete]. This
207     example contains everything that is supported in normal form, with the
208     exception of builtin higher order functions. The graphical version of the
209     architecture contains a slightly simplified version, since the state tuple
210     packing and unpacking have been left out. Instead, two seperate registers are
211     drawn. Also note that most synthesis tools will further optimize this
212     architecture by removing the multiplexers at the register input and
213     instead put some gates in front of the register's clock input, but we want
214     to show the architecture as close to the description as possible.
215
216     As you can see from the previous examples, the generation of the final
217     architecture from the normal form is straightforward. In each of the
218     examples, there is a direct match between the normal form structure,
219     the generated VHDL and the architecture shown in the images.
220
221     \startbuffer[NormalComplete]
222       regbank :: Bit 
223                  -> Word 
224                  -> State (Word, Word) 
225                  -> (State (Word, Word), Word)
226
227       -- All arguments are an inital lambda (address, data, packed state)
228       regbank = λa.λd.λsp.
229       -- There are nested let expressions at top level
230       let
231         -- Unpack the state by coercion (\eg, cast from
232         -- State (Word, Word) to (Word, Word))
233         s = sp ▶ (Word, Word)
234         -- Extract both registers from the state
235         r1 = case s of (a, b) -> a
236         r2 = case s of (a, b) -> b
237         -- Calling some other user-defined function.
238         d' = foo d
239         -- Conditional connections
240         out = case a of
241           High -> r1
242           Low -> r2
243         r1' = case a of
244           High -> d'
245           Low -> r1
246         r2' = case a of
247           High -> r2
248           Low -> d'
249         -- Packing a tuple
250         s' = (,) r1' r2'
251         -- pack the state by coercion (\eg, cast from
252         -- (Word, Word) to State (Word, Word))
253         sp' = s' ▶ State (Word, Word)
254         -- Pack our return value
255         res = (,) sp' out
256       in
257         -- The actual result
258         res
259     \stopbuffer
260
261     \startuseMPgraphic{NormalComplete}
262       save a, d, r, foo, muxr, muxout, out;
263
264       % I/O ports
265       newCircle.a(btex \lam{a} etex) "framed(false)";
266       newCircle.d(btex \lam{d} etex) "framed(false)";
267       newCircle.out(btex \lam{out} etex) "framed(false)";
268       % Components
269       %newCircle.add(btex + etex);
270       newBox.foo(btex \lam{foo} etex);
271       newReg.r1(btex $\lam{r1}$ etex) "dx(4mm)", "dy(6mm)";
272       newReg.r2(btex $\lam{r2}$ etex) "dx(4mm)", "dy(6mm)", "reflect(true)";
273       newMux.muxr1;
274       % Reflect over the vertical axis
275       reflectObj(muxr1)((0,0), (0,1));
276       newMux.muxr2;
277       newMux.muxout;
278       rotateObj(muxout)(-90);
279
280       d.c               = foo.c + (0cm, 1.5cm); 
281       a.c               = (xpart r2.c + 2cm, ypart d.c - 0.5cm);
282       foo.c             = midpoint(muxr1.c, muxr2.c) + (0cm, 2cm);
283       muxr1.c           = r1.c + (0cm, 2cm);
284       muxr2.c           = r2.c + (0cm, 2cm);
285       r2.c              = r1.c + (4cm, 0cm);
286       r1.c              = origin;
287       muxout.c          = midpoint(r1.c, r2.c) - (0cm, 2cm);
288       out.c             = muxout.c - (0cm, 1.5cm);
289
290     %  % Draw objects and lines
291       drawObj(a, d, foo, r1, r2, muxr1, muxr2, muxout, out);
292       
293       ncline(d)(foo);
294       nccurve(foo)(muxr1) "angleA(-90)", "posB(inpa)", "angleB(180)";
295       nccurve(foo)(muxr2) "angleA(-90)", "posB(inpb)", "angleB(0)";
296       nccurve(muxr1)(r1) "posA(out)", "angleA(180)", "posB(d)", "angleB(0)";
297       nccurve(r1)(muxr1) "posA(out)", "angleA(0)", "posB(inpb)", "angleB(180)";
298       nccurve(muxr2)(r2) "posA(out)", "angleA(0)", "posB(d)", "angleB(180)";
299       nccurve(r2)(muxr2) "posA(out)", "angleA(180)", "posB(inpa)", "angleB(0)";
300       nccurve(r1)(muxout) "posA(out)", "angleA(0)", "posB(inpb)", "angleB(-90)";
301       nccurve(r2)(muxout) "posA(out)", "angleA(180)", "posB(inpa)", "angleB(-90)";
302       % Connect port a
303       nccurve(a)(muxout) "angleA(-90)", "angleB(180)", "posB(sel)";
304       nccurve(a)(muxr1) "angleA(180)", "angleB(-90)", "posB(sel)";
305       nccurve(a)(muxr2) "angleA(180)", "angleB(-90)", "posB(sel)";
306       ncline(muxout)(out) "posA(out)";
307     \stopuseMPgraphic
308
309     \todo{Don't split registers in this image?}
310     \placeexample[here][ex:NormalComplete]{Simple architecture consisting of an adder and a
311     subtractor.}
312       \startcombination[2*1]
313         {\typebufferlam{NormalComplete}}{Core description in normal form.}
314         {\boxedgraphic{NormalComplete}}{The architecture described by the normal form.}
315       \stopcombination
316     
317
318
319     \subsection[sec:normalization:intendednormalform]{Intended normal form definition}
320       Now we have some intuition for the normal form, we can describe how we want
321       the normal form to look like in a slightly more formal manner. The following
322       EBNF-like description completely captures the intended structure (and
323       generates a subset of GHC's core format).
324
325       Some clauses have an expression listed in parentheses. These are conditions
326       that need to apply to the clause.
327
328       \defref{intended normal form definition}
329       \todo{Fix indentation}
330       \startlambda
331       \italic{normal} := \italic{lambda}
332       \italic{lambda} := λvar.\italic{lambda} (representable(var))
333                       | \italic{toplet} 
334       \italic{toplet} := letrec [\italic{binding}...] in var (representable(var))
335       \italic{binding} := var = \italic{rhs} (representable(rhs))
336                        -- State packing and unpacking by coercion
337                        | var0 = var1 ▶ State ty (lvar(var1))
338                        | var0 = var1 ▶ ty (var1 :: State ty ∧ lvar(var1))
339       \italic{rhs} := userapp
340                    | builtinapp
341                    -- Extractor case
342                    | case var of C a0 ... an -> ai (lvar(var))
343                    -- Selector case
344                    | case var of (lvar(var))
345                       [ DEFAULT -> var ]  (lvar(var))
346                       C0 w0,0 ... w0,n -> var0
347                       \vdots
348                       Cm wm,0 ... wm,n -> varm       (\forall{}i \forall{}j, wi,j \neq vari, lvar(vari))
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} := var (representable(var) ∧ lvar(var))
357                           | \italic{partapp} (partapp :: a -> b)
358                           | \italic{coreexpr} (¬representable(coreexpr) ∧ ¬(coreexpr :: a -> b))
359       \italic{partapp} := \italic{userapp} | \italic{builtinapp}
360       \stoplambda
361
362       \todo{There can still be other casts around (which the code can handle,
363       e.g., ignore), which still need to be documented here}
364
365       When looking at such a program from a hardware perspective, the top level
366       lambda's define the input ports. The variable reference in the body of
367       the recursive let expression is the output port. Most function
368       applications bound by the let expression define a component
369       instantiation, where the input and output ports are mapped to local
370       signals or arguments. Some of the others use a builtin construction (\eg
371       the \lam{case} expression) or call a builtin function (\eg \lam{+} or
372       \lam{map}). For these, a hardcoded \small{VHDL} translation is
373       available.
374
375   \section[sec:normalization:transformation]{Transformation notation}
376     To be able to concisely present transformations, we use a specific format
377     for them. It is a simple format, similar to one used in logic reasoning.
378
379     Such a transformation description looks like the following.
380
381     \starttrans
382     <context conditions>
383     ~
384     <original expression>
385     --------------------------          <expression conditions>
386     <transformed expresssion>
387     ~
388     <context additions>
389     \stoptrans
390
391     This format desribes a transformation that applies to \lam{<original
392     expresssion>} and transforms it into \lam{<transformed expression>}, assuming
393     that all conditions apply. In this format, there are a number of placeholders
394     in pointy brackets, most of which should be rather obvious in their meaning.
395     Nevertheless, we will more precisely specify their meaning below:
396
397       \startdesc{<original expression>} The expression pattern that will be matched
398       against (subexpressions of) the expression to be transformed. We call this a
399       pattern, because it can contain \emph{placeholders} (variables), which match
400       any expression or binder. Any such placeholder is said to be \emph{bound} to
401       the expression it matches. It is convention to use an uppercase letter (\eg
402       \lam{M} or \lam{E}) to refer to any expression (including a simple variable
403       reference) and lowercase letters (\eg \lam{v} or \lam{b}) to refer to
404       (references to) binders.
405
406       For example, the pattern \lam{a + B} will match the expression 
407       \lam{v + (2 * w)} (binding \lam{a} to \lam{v} and \lam{B} to 
408       \lam{(2 * w)}), but not \lam{(2 * w) + v}.
409       \stopdesc
410
411       \startdesc{<expression conditions>}
412       These are extra conditions on the expression that is matched. These
413       conditions can be used to further limit the cases in which the
414       transformation applies, commonly to prevent a transformation from
415       causing a loop with itself or another transformation.
416
417       Only if these conditions are \emph{all} true, the transformation
418       applies.
419       \stopdesc
420
421       \startdesc{<context conditions>}
422       These are a number of extra conditions on the context of the function. In
423       particular, these conditions can require some (other) top level function to be
424       present, whose value matches the pattern given here. The format of each of
425       these conditions is: \lam{binder = <pattern>}.
426
427       Typically, the binder is some placeholder bound in the \lam{<original
428       expression>}, while the pattern contains some placeholders that are used in
429       the \lam{transformed expression}.
430       
431       Only if a top level binder exists that matches each binder and pattern,
432       the transformation applies.
433       \stopdesc
434
435       \startdesc{<transformed expression>}
436       This is the expression template that is the result of the transformation. If, looking
437       at the above three items, the transformation applies, the \lam{<original
438       expression>} is completely replaced with the \lam{<transformed expression>}.
439       We call this a template, because it can contain placeholders, referring to
440       any placeholder bound by the \lam{<original expression>} or the
441       \lam{<context conditions>}. The resulting expression will have those
442       placeholders replaced by the values bound to them.
443
444       Any binder (lowercase) placeholder that has no value bound to it yet will be
445       bound to (and replaced with) a fresh binder.
446       \stopdesc
447
448       \startdesc{<context additions>}
449       These are templates for new functions to add to the context. This is a way
450       to have a transformation create new top level functions.
451
452       Each addition has the form \lam{binder = template}. As above, any
453       placeholder in the addition is replaced with the value bound to it, and any
454       binder placeholder that has no value bound to it yet will be bound to (and
455       replaced with) a fresh binder.
456       \stopdesc
457
458     As an example, we'll look at η-abstraction:
459
460     \starttrans
461     E                 \lam{E :: a -> b}
462     --------------    \lam{E} does not occur on a function position in an application
463     λx.E x            \lam{E} is not a lambda abstraction.
464     \stoptrans
465
466     η-abstraction is a well known transformation from lambda calculus. What
467     this transformation does, is take any expression that has a function type
468     and turn it into a lambda expression (giving an explicit name to the
469     argument). There are some extra conditions that ensure that this
470     transformation does not apply infinitely (which are not necessarily part
471     of the conventional definition of η-abstraction).
472
473     Consider the following function, which is a fairly obvious way to specify a
474     simple ALU (Note that \in{example}[ex:AddSubAlu] shows the normal form of this
475     function). The parentheses around the \lam{+} and \lam{-} operators are
476     commonly used in Haskell to show that the operators are used as normal
477     functions, instead of \emph{infix} operators (\eg, the operators appear
478     before their arguments, instead of in between).
479
480     \startlambda 
481     alu :: Bit -> Word -> Word -> Word
482     alu = λopcode. case opcode of
483       Low -> (+)
484       High -> (-)
485     \stoplambda
486
487     There are a few subexpressions in this function to which we could possibly
488     apply the transformation. Since the pattern of the transformation is only
489     the placeholder \lam{E}, any expression will match that. Whether the
490     transformation applies to an expression is thus solely decided by the
491     conditions to the right of the transformation.
492
493     We will look at each expression in the function in a top down manner. The
494     first expression is the entire expression the function is bound to.
495
496     \startlambda
497     λopcode. case opcode of
498       Low -> (+)
499       High -> (-)
500     \stoplambda
501
502     As said, the expression pattern matches this. The type of this expression is
503     \lam{Bit -> Word -> Word -> Word}, which matches \lam{a -> b} (Note that in
504     this case \lam{a = Bit} and \lam{b = Word -> Word -> Word}).
505
506     Since this expression is at top level, it does not occur at a function
507     position of an application. However, The expression is a lambda abstraction,
508     so this transformation does not apply.
509
510     The next expression we could apply this transformation to, is the body of
511     the lambda abstraction:
512
513     \startlambda
514     case opcode of
515       Low -> (+)
516       High -> (-)
517     \stoplambda
518
519     The type of this expression is \lam{Word -> Word -> Word}, which again
520     matches \lam{a -> b}. The expression is the body of a lambda expression, so
521     it does not occur at a function position of an application. Finally, the
522     expression is not a lambda abstraction but a case expression, so all the
523     conditions match. There are no context conditions to match, so the
524     transformation applies.
525
526     By now, the placeholder \lam{E} is bound to the entire expression. The
527     placeholder \lam{x}, which occurs in the replacement template, is not bound
528     yet, so we need to generate a fresh binder for that. Let's use the binder
529     \lam{a}. This results in the following replacement expression:
530
531     \startlambda
532     λa.(case opcode of
533       Low -> (+)
534       High -> (-)) a
535     \stoplambda
536
537     Continuing with this expression, we see that the transformation does not
538     apply again (it is a lambda expression). Next we look at the body of this
539     lambda abstraction:
540
541     \startlambda
542     (case opcode of
543       Low -> (+)
544       High -> (-)) a
545     \stoplambda
546     
547     Here, the transformation does apply, binding \lam{E} to the entire
548     expression and \lam{x} to the fresh binder \lam{b}, resulting in the
549     replacement:
550
551     \startlambda
552     λb.(case opcode of
553       Low -> (+)
554       High -> (-)) a b
555     \stoplambda
556
557     Again, the transformation does not apply to this lambda abstraction, so we
558     look at its body. For brevity, we'll put the case statement on one line from
559     now on.
560
561     \startlambda
562     (case opcode of Low -> (+); High -> (-)) a b
563     \stoplambda
564
565     The type of this expression is \lam{Word}, so it does not match \lam{a -> b}
566     and the transformation does not apply. Next, we have two options for the
567     next expression to look at: The function position and argument position of
568     the application. The expression in the argument position is \lam{b}, which
569     has type \lam{Word}, so the transformation does not apply. The expression in
570     the function position is:
571
572     \startlambda
573     (case opcode of Low -> (+); High -> (-)) a
574     \stoplambda
575
576     Obviously, the transformation does not apply here, since it occurs in
577     function position (which makes the second condition false). In the same
578     way the transformation does not apply to both components of this
579     expression (\lam{case opcode of Low -> (+); High -> (-)} and \lam{a}), so
580     we'll skip to the components of the case expression: The scrutinee and
581     both alternatives. Since the opcode is not a function, it does not apply
582     here.
583
584     The first alternative is \lam{(+)}. This expression has a function type
585     (the operator still needs two arguments). It does not occur in function
586     position of an application and it is not a lambda expression, so the
587     transformation applies.
588
589     We look at the \lam{<original expression>} pattern, which is \lam{E}.
590     This means we bind \lam{E} to \lam{(+)}. We then replace the expression
591     with the \lam{<transformed expression>}, replacing all occurences of
592     \lam{E} with \lam{(+)}. In the \lam{<transformed expression>}, the This gives us the replacement expression:
593     \lam{λx.(+) x} (A lambda expression binding \lam{x}, with a body that
594     applies the addition operator to \lam{x}).
595
596     The complete function then becomes:
597     \startlambda
598     (case opcode of Low -> λa1.(+) a1; High -> (-)) a
599     \stoplambda
600
601     Now the transformation no longer applies to the complete first alternative
602     (since it is a lambda expression). It does not apply to the addition
603     operator again, since it is now in function position in an application. It
604     does, however, apply to the application of the addition operator, since
605     that is neither a lambda expression nor does it occur in function
606     position. This means after one more application of the transformation, the
607     function becomes:
608
609     \startlambda
610     (case opcode of Low -> λa1.λb1.(+) a1 b1; High -> (-)) a
611     \stoplambda
612
613     The other alternative is left as an exercise to the reader. The final
614     function, after applying η-abstraction until it does no longer apply is:
615
616     \startlambda 
617     alu :: Bit -> Word -> Word -> Word
618     alu = λopcode.λa.b. (case opcode of
619       Low -> λa1.λb1 (+) a1 b1
620       High -> λa2.λb2 (-) a2 b2) a b
621     \stoplambda
622
623     \subsection{Transformation application}
624       In this chapter we define a number of transformations, but how will we apply
625       these? As stated before, our normal form is reached as soon as no
626       transformation applies anymore. This means our application strategy is to
627       simply apply any transformation that applies, and continuing to do that with
628       the result of each transformation.
629
630       In particular, we define no particular order of transformations. Since
631       transformation order should not influence the resulting normal form,
632       \todo{This is not really true, but would like it to be...} this leaves
633       the implementation free to choose any application order that results in
634       an efficient implementation.
635
636       When applying a single transformation, we try to apply it to every (sub)expression
637       in a function, not just the top level function body. This allows us to
638       keep the transformation descriptions concise and powerful.
639
640     \subsection{Definitions}
641       In the following sections, we will be using a number of functions and
642       notations, which we will define here.
643
644       \todo{Define substitution (notation)}
645
646       \subsubsection{Concepts}
647         A \emph{global variable} is any variable (binder) that is bound at the
648         top level of a program, or an external module. A \emph{local variable} is any
649         other variable (\eg, variables local to a function, which can be bound by
650         lambda abstractions, let expressions and pattern matches of case
651         alternatives).  Note that this is a slightly different notion of global versus
652         local than what \small{GHC} uses internally.
653         \defref{global variable} \defref{local variable}
654
655         A \emph{hardware representable} (or just \emph{representable}) type or value
656         is (a value of) a type that we can generate a signal for in hardware. For
657         example, a bit, a vector of bits, a 32 bit unsigned word, etc. Values that are
658         not runtime representable notably include (but are not limited to): Types,
659         dictionaries, functions.
660         \defref{representable}
661
662         A \emph{builtin function} is a function supplied by the Cλash framework, whose
663         implementation is not valid Cλash. The implementation is of course valid
664         Haskell, for simulation, but it is not expressable in Cλash.
665         \defref{builtin function} \defref{user-defined function}
666
667       For these functions, Cλash has a \emph{builtin hardware translation}, so calls
668       to these functions can still be translated. These are functions like
669       \lam{map}, \lam{hwor} and \lam{length}.
670
671       A \emph{user-defined} function is a function for which we do have a Cλash
672       implementation available.
673
674       \subsubsection{Predicates}
675         Here, we define a number of predicates that can be used below to concisely
676         specify conditions.\refdef{global variable}
677
678         \emph{gvar(expr)} is true when \emph{expr} is a variable that references a
679         global variable. It is false when it references a local variable.
680
681         \refdef{local variable}\emph{lvar(expr)} is the complement of \emph{gvar}; it is true when \emph{expr}
682         references a local variable, false when it references a global variable.
683
684         \refdef{representable}\emph{representable(expr)} or \emph{representable(var)} is true when
685         \emph{expr} or \emph{var} is \emph{representable}.
686
687     \subsection[sec:normalization:uniq]{Binder uniqueness}
688       A common problem in transformation systems, is binder uniqueness. When not
689       considering this problem, it is easy to create transformations that mix up
690       bindings and cause name collisions. Take for example, the following core
691       expression:
692
693       \startlambda
694       (λa.λb.λc. a * b * c) x c
695       \stoplambda
696
697       By applying β-reduction (see \in{section}[sec:normalization:beta]) once,
698       we can simplify this expression to:
699
700       \startlambda
701       (λb.λc. x * b * c) c
702       \stoplambda
703
704       Now, we have replaced the \lam{a} binder with a reference to the \lam{x}
705       binder. No harm done here. But note that we see multiple occurences of the
706       \lam{c} binder. The first is a binding occurence, to which the second refers.
707       The last, however refers to \emph{another} instance of \lam{c}, which is
708       bound somewhere outside of this expression. Now, if we would apply beta
709       reduction without taking heed of binder uniqueness, we would get:
710
711       \startlambda
712       λc. x * c * c
713       \stoplambda
714
715       This is obviously not what was supposed to happen! The root of this problem is
716       the reuse of binders: Identical binders can be bound in different scopes, such
717       that only the inner one is \quote{visible} in the inner expression. In the example
718       above, the \lam{c} binder was bound outside of the expression and in the inner
719       lambda expression. Inside that lambda expression, only the inner \lam{c} is
720       visible.
721
722       There are a number of ways to solve this. \small{GHC} has isolated this
723       problem to their binder substitution code, which performs \emph{deshadowing}
724       during its expression traversal. This means that any binding that shadows
725       another binding on a higher level is replaced by a new binder that does not
726       shadow any other binding. This non-shadowing invariant is enough to prevent
727       binder uniqueness problems in \small{GHC}.
728
729       In our transformation system, maintaining this non-shadowing invariant is
730       a bit harder to do (mostly due to implementation issues, the prototype doesn't
731       use \small{GHC}'s subsitution code). Also, the following points can be
732       observed.
733
734       \startitemize
735       \item Deshadowing does not guarantee overall uniqueness. For example, the
736       following (slightly contrived) expression shows the identifier \lam{x} bound in
737       two seperate places (and to different values), even though no shadowing
738       occurs.
739
740       \startlambda
741       (let x = 1 in x) + (let x = 2 in x)
742       \stoplambda
743
744       \item In our normal form (and the resulting \small{VHDL}), all binders
745       (signals) within the same function (entity) will end up in the same
746       scope. To allow this, all binders within the same function should be
747       unique.
748
749       \item When we know that all binders in an expression are unique, moving around
750       or removing a subexpression will never cause any binder conflicts. If we have
751       some way to generate fresh binders, introducing new subexpressions will not
752       cause any problems either. The only way to cause conflicts is thus to
753       duplicate an existing subexpression.
754       \stopitemize
755
756       Given the above, our prototype maintains a unique binder invariant. This
757       means that in any given moment during normalization, all binders \emph{within
758       a single function} must be unique. To achieve this, we apply the following
759       technique.
760
761       \todo{Define fresh binders and unique supplies}
762
763       \startitemize
764       \item Before starting normalization, all binders in the function are made
765       unique. This is done by generating a fresh binder for every binder used. This
766       also replaces binders that did not cause any conflict, but it does ensure that
767       all binders within the function are generated by the same unique supply.
768       \refdef{fresh binder}
769       \item Whenever a new binder must be generated, we generate a fresh binder that
770       is guaranteed to be different from \emph{all binders generated so far}. This
771       can thus never introduce duplication and will maintain the invariant.
772       \item Whenever (a part of) an expression is duplicated (for example when
773       inlining), all binders in the expression are replaced with fresh binders
774       (using the same method as at the start of normalization). These fresh binders
775       can never introduce duplication, so this will maintain the invariant.
776       \item Whenever we move part of an expression around within the function, there
777       is no need to do anything special. There is obviously no way to introduce
778       duplication by moving expressions around. Since we know that each of the
779       binders is already unique, there is no way to introduce (incorrect) shadowing
780       either.
781       \stopitemize
782
783   \section{Transform passes}
784     In this section we describe the actual transforms.
785
786     Each transformation will be described informally first, explaining
787     the need for and goal of the transformation. Then, we will formally define
788     the transformation using the syntax introduced in
789     \in{section}[sec:normalization:transformation].
790
791     \subsection{General cleanup}
792       These transformations are general cleanup transformations, that aim to
793       make expressions simpler. These transformations usually clean up the
794        mess left behind by other transformations or clean up expressions to
795        expose new transformation opportunities for other transformations.
796
797        Most of these transformations are standard optimizations in other
798        compilers as well. However, in our compiler, most of these are not just
799        optimizations, but they are required to get our program into intended
800        normal form.
801
802       \subsubsection[sec:normalization:beta]{β-reduction}
803         \defref{beta-reduction}
804         β-reduction is a well known transformation from lambda calculus, where it is
805         the main reduction step. It reduces applications of lambda abstractions,
806         removing both the lambda abstraction and the application.
807
808         In our transformation system, this step helps to remove unwanted lambda
809         abstractions (basically all but the ones at the top level). Other
810         transformations (application propagation, non-representable inlining) make
811         sure that most lambda abstractions will eventually be reducable by
812         β-reduction.
813
814         Note that β-reduction also works on type lambda abstractions and type
815         applications as well. This means the substitution below also works on
816         type variables, in the case that the binder is a type variable and teh
817         expression applied to is a type.
818
819         \starttrans
820         (λx.E) M
821         -----------------
822         E[x=>M]
823         \stoptrans
824
825         % And an example
826         \startbuffer[from]
827         (λa. 2 * a) (2 * b)
828         \stopbuffer
829
830         \startbuffer[to]
831         2 * (2 * b)
832         \stopbuffer
833
834         \transexample{beta}{β-reduction}{from}{to}
835
836         \startbuffer[from]
837         (λt.λa::t. a) @Int
838         \stopbuffer
839
840         \startbuffer[to]
841         (λa::Int. a)
842         \stopbuffer
843
844         \transexample{beta-type}{β-reduction for type abstractions}{from}{to}
845        
846       \subsubsection{Empty let removal}
847         This transformation is simple: It removes recursive lets that have no bindings
848         (which usually occurs when unused let binding removal removes the last
849         binding from it).
850
851         Note that there is no need to define this transformation for
852         non-recursive lets, since they always contain exactly one binding.
853
854         \starttrans
855         letrec in M
856         --------------
857         M
858         \stoptrans
859
860         \todo{Example}
861
862       \subsubsection[sec:normalization:simplelet]{Simple let binding removal}
863         This transformation inlines simple let bindings, that bind some
864         binder to some other binder instead of a more complex expression (\ie
865         a = b).
866
867         This transformation is not needed to get an expression into intended
868         normal form (since these bindings are part of the intended normal
869         form), but makes the resulting \small{VHDL} a lot shorter.
870         
871         \starttrans
872         letrec
873           a0 = E0
874           \vdots
875           ai = b
876           \vdots
877           an = En
878         in
879           M
880         -----------------------------  \lam{b} is a variable reference
881         letrec                         \lam{ai} ≠ \lam{b}
882           a0 = E0 [ai=>b]
883           \vdots
884           ai-1 = Ei-1 [ai=>b]
885           ai+1 = Ei+1 [ai=>b]
886           \vdots
887           an = En [ai=>b]
888         in
889           M[ai=>b]
890         \stoptrans
891
892         \todo{example}
893
894       \subsubsection{Unused let binding removal}
895         This transformation removes let bindings that are never used.
896         Occasionally, \GHC's desugarer introduces some unused let bindings.
897
898         This normalization pass should really be unneeded to get into intended normal form
899         (since unused bindings are not forbidden by the normal form), but in practice
900         the desugarer or simplifier emits some unused bindings that cannot be
901         normalized (e.g., calls to a \type{PatError}\todo{Check this name}). Also,
902         this transformation makes the resulting \small{VHDL} a lot shorter.
903
904         \todo{Don't use old-style numerals in transformations}
905         \starttrans
906         letrec
907           a0 = E0
908           \vdots
909           ai = Ei
910           \vdots
911           an = En
912         in
913           M                             \lam{ai} does not occur free in \lam{M}
914         ----------------------------    \forall j, 0 ≤ j ≤ n, j ≠ i (\lam{ai} does not occur free in \lam{Ej})
915         letrec
916           a0 = E0
917           \vdots
918           ai-1 = Ei-1
919           ai+1 = Ei+1
920           \vdots
921           an = En
922         in
923           M
924         \stoptrans
925
926         \todo{Example}
927
928       \subsubsection{Cast propagation / simplification}
929         This transform pushes casts down into the expression as far as possible.
930         Since its exact role and need is not clear yet, this transformation is
931         not yet specified.
932
933         \todo{Cast propagation}
934
935       \subsubsection{Top level binding inlining}
936         This transform takes simple top level bindings generated by the
937         \small{GHC} compiler. \small{GHC} sometimes generates very simple
938         \quote{wrapper} bindings, which are bound to just a variable
939         reference, or a partial application to constants or other variable
940         references.
941
942         Note that this transformation is completely optional. It is not
943         required to get any function into intended normal form, but it does help making
944         the resulting VHDL output easier to read (since it removes a bunch of
945         components that are really boring).
946
947         This transform takes any top level binding generated by the compiler,
948         whose normalized form contains only a single let binding.
949
950         \starttrans
951         x = λa0 ... λan.let y = E in y
952         ~
953         x
954         --------------------------------------         \lam{x} is generated by the compiler
955         λa0 ... λan.let y = E in y
956         \stoptrans
957
958         \startbuffer[from]
959         (+) :: Word -> Word -> Word
960         (+) = GHC.Num.(+) @Word \$dNum
961         ~
962         (+) a b
963         \stopbuffer
964         \startbuffer[to]
965         GHC.Num.(+) @ Alu.Word \$dNum a b
966         \stopbuffer
967
968         \transexample{toplevelinline}{Top level binding inlining}{from}{to}
969        
970         \in{Example}[ex:trans:toplevelinline] shows a typical application of
971         the addition operator generated by \GHC. The type and dictionary
972         arguments used here are described in
973         \in{Section}[section:prototype:polymorphism].
974
975         Without this transformation, there would be a \lam{(+)} entity
976         in the \VHDL which would just add its inputs. This generates a
977         lot of overhead in the \VHDL, which is particularly annoying
978         when browsing the generated RTL schematic (especially since most
979         non-alphanumerics, like all characters in \lam{(+)}, are not
980         allowed in \VHDL architecture names\footnote{Technically, it is
981         allowed to use non-alphanumerics when using extended
982         identifiers, but it seems that none of the tooling likes
983         extended identifiers in filenames, so it effectively doesn't
984         work.}, so the entity would be called \quote{w7aA7f} or
985         something similarly unreadable and autogenerated).
986
987     \subsection{Program structure}
988       These transformations are aimed at normalizing the overall structure
989       into the intended form. This means ensuring there is a lambda abstraction
990       at the top for every argument (input port or current state), putting all
991       of the other value definitions in let bindings and making the final
992       return value a simple variable reference.
993
994       \subsubsection[sec:normalization:eta]{η-abstraction}
995         This transformation makes sure that all arguments of a function-typed
996         expression are named, by introducing lambda expressions. When combined with
997         β-reduction and non-representable binding inlining, all function-typed
998         expressions should be lambda abstractions or global identifiers.
999
1000         \starttrans
1001         E                 \lam{E :: a -> b}
1002         --------------    \lam{E} is not the first argument of an application.
1003         λx.E x            \lam{E} is not a lambda abstraction.
1004                           \lam{x} is a variable that does not occur free in \lam{E}.
1005         \stoptrans
1006
1007         \startbuffer[from]
1008         foo = λa.case a of 
1009           True -> λb.mul b b
1010           False -> id
1011         \stopbuffer
1012
1013         \startbuffer[to]
1014         foo = λa.λx.(case a of 
1015             True -> λb.mul b b
1016             False -> λy.id y) x
1017         \stopbuffer
1018
1019         \transexample{eta}{η-abstraction}{from}{to}
1020
1021       \subsubsection[sec:normalization:appprop]{Application propagation}
1022         This transformation is meant to propagate application expressions downwards
1023         into expressions as far as possible. This allows partial applications inside
1024         expressions to become fully applied and exposes new transformation
1025         opportunities for other transformations (like β-reduction and
1026         specialization).
1027
1028         Since all binders in our expression are unique (see
1029         \in{section}[sec:normalization:uniq]), there is no risk that we will
1030         introduce unintended shadowing by moving an expression into a lower
1031         scope. Also, since only move expression into smaller scopes (down into
1032         our expression), there is no risk of moving a variable reference out
1033         of the scope in which it is defined.
1034
1035         \starttrans
1036         (letrec binds in E) M
1037         ------------------------
1038         letrec binds in E M
1039         \stoptrans
1040
1041         % And an example
1042         \startbuffer[from]
1043         ( letrec
1044             val = 1
1045           in 
1046             add val
1047         ) 3
1048         \stopbuffer
1049
1050         \startbuffer[to]
1051         letrec
1052           val = 1
1053         in 
1054           add val 3
1055         \stopbuffer
1056
1057         \transexample{appproplet}{Application propagation for a let expression}{from}{to}
1058
1059         \starttrans
1060         (case x of
1061           p1 -> E1
1062           \vdots
1063           pn -> En) M
1064         -----------------
1065         case x of
1066           p1 -> E1 M
1067           \vdots
1068           pn -> En M
1069         \stoptrans
1070
1071         % And an example
1072         \startbuffer[from]
1073         ( case x of 
1074             True -> id
1075             False -> neg
1076         ) 1
1077         \stopbuffer
1078
1079         \startbuffer[to]
1080         case x of 
1081           True -> id 1
1082           False -> neg 1
1083         \stopbuffer
1084
1085         \transexample{apppropcase}{Application propagation for a case expression}{from}{to}
1086
1087       \subsubsection[sec:normalization:letrecurse]{Let recursification}
1088         This transformation makes all non-recursive lets recursive. In the
1089         end, we want a single recursive let in our normalized program, so all
1090         non-recursive lets can be converted. This also makes other
1091         transformations simpler: They can simply assume all lets are
1092         recursive.
1093
1094         \starttrans
1095         let
1096           a = E
1097         in
1098           M
1099         ------------------------------------------
1100         letrec
1101           a = E
1102         in
1103           M
1104         \stoptrans
1105
1106       \subsubsection{Let flattening}
1107         This transformation puts nested lets in the same scope, by lifting the
1108         binding(s) of the inner let into the outer let. Eventually, this will
1109         cause all let bindings to appear in the same scope.
1110
1111         This transformation only applies to recursive lets, since all
1112         non-recursive lets will be made recursive (see
1113         \in{section}[sec:normalization:letrecurse]).
1114
1115         Since we are joining two scopes together, there is no risk of moving a
1116         variable reference out of the scope where it is defined.
1117
1118         \starttrans
1119         letrec 
1120           a0 = E0
1121           \vdots
1122           ai = (letrec bindings in M)
1123           \vdots
1124           an = En
1125         in
1126           N
1127         ------------------------------------------
1128         letrec
1129           a0 = E0
1130           \vdots
1131           ai = M
1132           \vdots
1133           an = En
1134           bindings
1135         in
1136           N
1137         \stoptrans
1138
1139         \startbuffer[from]
1140         letrec
1141           a = 1
1142           b = letrec
1143             x = a
1144             y = c
1145           in
1146             x + y
1147           c = 2
1148         in
1149           b
1150         \stopbuffer
1151         \startbuffer[to]
1152         letrec
1153           a = 1
1154           b = x + y
1155           c = 2
1156           x = a
1157           y = c
1158         in
1159           b
1160         \stopbuffer
1161
1162         \transexample{letflat}{Let flattening}{from}{to}
1163
1164       \subsubsection{Return value simplification}
1165         This transformation ensures that the return value of a function is always a
1166         simple local variable reference.
1167
1168         Currently implemented using lambda simplification, let simplification, and
1169         top simplification. Should change into something like the following, which
1170         works only on the result of a function instead of any subexpression. This is
1171         achieved by the contexts, like \lam{x = E}, though this is strictly not
1172         correct (you could read this as "if there is any function \lam{x} that binds
1173         \lam{E}, any \lam{E} can be transformed, while we only mean the \lam{E} that
1174         is bound by \lam{x}. This might need some extra notes or something).
1175
1176         Note that the return value is not simplified if its not representable.
1177         Otherwise, this would cause a direct loop with the inlining of
1178         unrepresentable bindings. If the return value is not
1179         representable because it has a function type, η-abstraction should
1180         make sure that this transformation will eventually apply. If the value
1181         is not representable for other reasons, the function result itself is
1182         not representable, meaning this function is not translatable anyway.
1183
1184         \starttrans
1185         x = E                            \lam{E} is representable
1186         ~                                \lam{E} is not a lambda abstraction
1187         E                                \lam{E} is not a let expression
1188         ---------------------------      \lam{E} is not a local variable reference
1189         letrec x = E in x
1190         \stoptrans
1191
1192         \starttrans
1193         x = λv0 ... λvn.E
1194         ~                                \lam{E} is representable
1195         E                                \lam{E} is not a let expression
1196         ---------------------------      \lam{E} is not a local variable reference
1197         letrec x = E in x
1198         \stoptrans
1199
1200         \starttrans
1201         x = λv0 ... λvn.let ... in E
1202         ~                                \lam{E} is representable
1203         E                                \lam{E} is not a local variable reference
1204         -----------------------------
1205         letrec x = E in x
1206         \stoptrans
1207
1208         \startbuffer[from]
1209         x = add 1 2
1210         \stopbuffer
1211
1212         \startbuffer[to]
1213         x = letrec x = add 1 2 in x
1214         \stopbuffer
1215
1216         \transexample{retvalsimpl}{Return value simplification}{from}{to}
1217         
1218         \todo{More examples}
1219
1220     \subsection[sec:normalization:argsimpl]{Representable arguments simplification}
1221       This section contains just a single transformation that deals with
1222       representable arguments in applications. Non-representable arguments are
1223       handled by the transformations in
1224       \in{section}[sec:normalization:nonrep]. 
1225       
1226       This transformation ensures that all representable arguments will become
1227       references to local variables. This ensures they will become references
1228       to local signals in the resulting \small{VHDL}, which is required due to
1229       limitations in the component instantiation code in \VHDL (one can only
1230       assign a signal or constant to an input port). By ensuring that all
1231       arguments are always simple variable references, we always have a signal
1232       available to map to the input ports.
1233
1234       To reduce a complex expression to a simple variable reference, we create
1235       a new let expression around the application, which binds the complex
1236       expression to a new variable. The original function is then applied to
1237       this variable.
1238
1239       \refdef{global variable}
1240       Note that references to \emph{global variables} (like a top level
1241       function without arguments, but also an argumentless dataconstructors
1242       like \lam{True}) are also simplified. Only local variables generate
1243       signals in the resulting architecture. Even though argumentless
1244       dataconstructors generate constants in generated \VHDL code and could be
1245       mapped to an input port directly, they are still simplified to make the
1246       normal form more regular.
1247
1248       \refdef{representable}
1249       \starttrans
1250       M N
1251       --------------------    \lam{N} is representable
1252       letrec x = N in M x     \lam{N} is not a local variable reference
1253       \stoptrans
1254       \refdef{local variable}
1255
1256       \startbuffer[from]
1257       add (add a 1) 1
1258       \stopbuffer
1259
1260       \startbuffer[to]
1261       letrec x = add a 1 in add x 1
1262       \stopbuffer
1263
1264       \transexample{argsimpl}{Argument simplification}{from}{to}
1265
1266     \subsection[sec:normalization:builtins]{Builtin functions}
1267       This section deals with (arguments to) builtin functions.  In the
1268       intended normal form definition\refdef{intended normal form definition}
1269       we can see that there are three sorts of arguments a builtin function
1270       can receive.
1271       
1272       \startitemize[KR]
1273         \item A representable local variable reference. This is the most
1274         common argument to any function. The argument simplification
1275         transformation described in \in{section}[sec:normalization:argsimpl]
1276         makes sure that \emph{any} representable argument to \emph{any}
1277         function (including builtin functions) is turned into a local variable
1278         reference.
1279         \item (A partial application of) a top level function (either builtin on
1280         user-defined). The function extraction transformation described in
1281         this section takes care of turning every functiontyped argument into
1282         (a partial application of) a top level function.
1283         \item Any expression that is not representable and does not have a
1284         function type. Since these can be any expression, there is no
1285         transformation needed. Note that this category is exactly all
1286         expressions that are not transformed by the transformations for the
1287         previous two categories. This means that \emph{any} core expression
1288         that is used as an argument to a builtin function will be either
1289         transformed into one of the above categories, or end up in this
1290         categorie. In any case, the result is in normal form.
1291       \stopitemize
1292
1293       As noted, the argument simplification will handle any representable
1294       arguments to a builtin function. The following transformation is needed
1295       to handle non-representable arguments with a function type, all other
1296       non-representable arguments don't need any special handling.
1297
1298       \subsubsection[sec:normalization:funextract]{Function extraction}
1299         This transform deals with function-typed arguments to builtin
1300         functions. 
1301         Since builtin functions cannot be specialized (see
1302         \in{section}[sec:normalization:specialize]) to remove the arguments,
1303         these arguments are extracted into a new global function instead. In
1304         other words, we create a new top level function that has exactly the
1305         extracted argument as its body. This greatly simplifies the
1306         translation rules needed for builtin functions, since they only need
1307         to handle (partial applications of) top level functions.
1308
1309         Any free variables occuring in the extracted arguments will become
1310         parameters to the new global function. The original argument is replaced
1311         with a reference to the new function, applied to any free variables from
1312         the original argument.
1313
1314         This transformation is useful when applying higher order builtin functions
1315         like \hs{map} to a lambda abstraction, for example. In this case, the code
1316         that generates \small{VHDL} for \hs{map} only needs to handle top level functions and
1317         partial applications, not any other expression (such as lambda abstractions or
1318         even more complicated expressions).
1319
1320         \starttrans
1321         M N                     \lam{M} is (a partial aplication of) a builtin function.
1322         ---------------------   \lam{f0 ... fn} are all free local variables of \lam{N}
1323         M (x f0 ... fn)         \lam{N :: a -> b}
1324         ~                       \lam{N} is not a (partial application of) a top level function
1325         x = λf0 ... λfn.N
1326         \stoptrans
1327
1328         \startbuffer[from]
1329         addList = λb.λxs.map (λa . add a b) xs
1330         \stopbuffer
1331
1332         \startbuffer[to]
1333         addList = λb.λxs.map (f b) xs
1334         ~
1335         f = λb.λa.add a b
1336         \stopbuffer
1337
1338         \transexample{funextract}{Function extraction}{from}{to}
1339
1340         Note that the function \lam{f} will still need normalization after
1341         this.
1342
1343     \subsection{Case normalisation}
1344       \subsubsection{Scrutinee simplification}
1345         This transform ensures that the scrutinee of a case expression is always
1346         a simple variable reference.
1347
1348         \starttrans
1349         case E of
1350           alts
1351         -----------------        \lam{E} is not a local variable reference
1352         letrec x = E in 
1353           case E of
1354             alts
1355         \stoptrans
1356
1357         \startbuffer[from]
1358         case (foo a) of
1359           True -> a
1360           False -> b
1361         \stopbuffer
1362
1363         \startbuffer[to]
1364         letrec x = foo a in
1365           case x of
1366             True -> a
1367             False -> b
1368         \stopbuffer
1369
1370         \transexample{letflat}{Case normalisation}{from}{to}
1371
1372
1373       \subsubsection{Case simplification}
1374         This transformation ensures that all case expressions become normal form. This
1375         means they will become one of:
1376         \startitemize
1377         \item An extractor case with a single alternative that picks a single field
1378         from a datatype, \eg \lam{case x of (a, b) -> a}.
1379         \item A selector case with multiple alternatives and only wild binders, that
1380         makes a choice between expressions based on the constructor of another
1381         expression, \eg \lam{case x of Low -> a; High -> b}.
1382         \stopitemize
1383         
1384         \defref{wild binder}
1385         \starttrans
1386         case E of
1387           C0 v0,0 ... v0,m -> E0
1388           \vdots
1389           Cn vn,0 ... vn,m -> En
1390         --------------------------------------------------- \forall i \forall j, 0 ≤ i ≤ n, 0 ≤ i < m (\lam{wi,j} is a wild (unused) binder)
1391         letrec
1392           v0,0 = case E of C0 v0,0 .. v0,m -> v0,0
1393           \vdots
1394           v0,m = case E of C0 v0,0 .. v0,m -> v0,m
1395           \vdots
1396           vn,m = case E of Cn vn,0 .. vn,m -> vn,m
1397           x0 = E0
1398           \vdots
1399           xn = En
1400         in
1401           case E of
1402             C0 w0,0 ... w0,m -> x0
1403             \vdots
1404             Cn wn,0 ... wn,m -> xn
1405         \stoptrans
1406         \todo{Check the subscripts of this transformation}
1407
1408         Note that this transformation applies to case statements with any
1409         scrutinee. If the scrutinee is a complex expression, this might result
1410         in duplicate hardware. An extra condition to only apply this
1411         transformation when the scrutinee is already simple (effectively
1412         causing this transformation to be only applied after the scrutinee
1413         simplification transformation) might be in order. 
1414
1415         \fxnote{This transformation specified like this is complicated and misses
1416         conditions to prevent looping with itself. Perhaps it should be split here for
1417         discussion?}
1418
1419         \startbuffer[from]
1420         case a of
1421           True -> add b 1
1422           False -> add b 2
1423         \stopbuffer
1424
1425         \startbuffer[to]
1426         letnonrec
1427           x0 = add b 1
1428           x1 = add b 2
1429         in
1430           case a of
1431             True -> x0
1432             False -> x1
1433         \stopbuffer
1434
1435         \transexample{selcasesimpl}{Selector case simplification}{from}{to}
1436
1437         \startbuffer[from]
1438         case a of
1439           (,) b c -> add b c
1440         \stopbuffer
1441         \startbuffer[to]
1442         letrec
1443           b = case a of (,) b c -> b
1444           c = case a of (,) b c -> c
1445           x0 = add b c
1446         in
1447           case a of
1448             (,) w0 w1 -> x0
1449         \stopbuffer
1450
1451         \transexample{excasesimpl}{Extractor case simplification}{from}{to}
1452
1453         \refdef{selector case}
1454         In \in{example}[ex:trans:excasesimpl] the case expression is expanded
1455         into multiple case expressions, including a pretty useless expression
1456         (that is neither a selector or extractor case). This case can be
1457         removed by the Case removal transformation in
1458         \in{section}[sec:transformation:caseremoval].
1459
1460       \subsubsection[sec:transformation:caseremoval]{Case removal}
1461         This transform removes any case statements with a single alternative and
1462         only wild binders.
1463
1464         These "useless" case statements are usually leftovers from case simplification
1465         on extractor case (see the previous example).
1466
1467         \starttrans
1468         case x of
1469           C v0 ... vm -> E
1470         ----------------------     \lam{\forall i, 0 ≤ i ≤ m} (\lam{vi} does not occur free in E)
1471         E
1472         \stoptrans
1473
1474         \startbuffer[from]
1475         case a of
1476           (,) w0 w1 -> x0
1477         \stopbuffer
1478
1479         \startbuffer[to]
1480         x0
1481         \stopbuffer
1482
1483         \transexample{caserem}{Case removal}{from}{to}
1484
1485     \subsection[sec:normalization:nonrep]{Removing unrepresentable values}
1486       The transformations in this section are aimed at making all the
1487       values used in our expression representable. There are two main
1488       transformations that are applied to \emph{all} unrepresentable let
1489       bindings and function arguments. These are meant to address three
1490       different kinds of unrepresentable values: Polymorphic values, higher
1491       order values and literals. The transformation are described generically:
1492       They apply to all non-representable values. However, non-representable
1493       values that don't fall into one of these three categories will be moved
1494       around by these transformations but are unlikely to completely
1495       disappear. They usually mean the program was not valid in the first
1496       place, because unsupported types were used (for example, a program using
1497       strings).
1498      
1499       Each of these three categories will be detailed below, followed by the
1500       actual transformations.
1501
1502       \subsubsection{Removing Polymorphism}
1503         As noted in \in{section}[sec:prototype:polymporphism],
1504         polymorphism is made explicit in Core through type and
1505         dictionary arguments. To remove the polymorphism from a
1506         function, we can simply specialize the polymorphic function for
1507         the particular type applied to it. The same goes for dictionary
1508         arguments. To remove polymorphism from let bound values, we
1509         simply inline the let bindings that have a polymorphic type,
1510         which should (eventually) make sure that the polymorphic
1511         expression is applied to a type and/or dictionary, which can
1512         then be removed by β-reduction (\in{section}[sec:normalization:beta]).
1513
1514         Since both type and dictionary arguments are not representable,
1515         \refdef{representable}
1516         the non-representable argument specialization and
1517         non-representable let binding inlining transformations below
1518         take care of exactly this.
1519
1520         There is one case where polymorphism cannot be completely
1521         removed: Builtin functions are still allowed to be polymorphic
1522         (Since we have no function body that we could properly
1523         specialize). However, the code that generates \VHDL for builtin
1524         functions knows how to handle this, so this is not a problem.
1525
1526       \subsubsection{Defunctionalization}
1527         These transformations remove higher order expressions from our
1528         program, making all values first-order.
1529       
1530         Higher order values are always introduced by lambda abstractions, none
1531         of the other Core expression elements can introduce a function type.
1532         However, other expressions can \emph{have} a function type, when they
1533         have a lambda expression in their body. 
1534         
1535         For example, the following expression is a higher order expression
1536         that is not a lambda expression itself:
1537         
1538         \refdef{id function}
1539         \startlambda
1540           case x of
1541             High -> id
1542             Low -> λx.x
1543         \stoplambda
1544
1545         The reference to the \lam{id} function shows that we can introduce a
1546         higher order expression in our program without using a lambda
1547         expression directly. However, inside the definition of the \lam{id}
1548         function, we can be sure that a lambda expression is present.
1549         
1550         Looking closely at the definition of our normal form in
1551         \in{section}[sec:normalization:intendednormalform], we can see that
1552         there are three possibilities for higher order values to appear in our
1553         intended normal form:
1554
1555         \startitemize[KR]
1556           \item[item:toplambda] Lambda abstractions can appear at the highest level of a
1557           top level function. These lambda abstractions introduce the
1558           arguments (input ports / current state) of the function.
1559           \item[item:builtinarg] (Partial applications of) top level functions can appear as an
1560           argument to a builtin function.
1561           \item[item:completeapp] (Partial applications of) top level functions can appear in
1562           function position of an application. Since a partial application
1563           cannot appear anywhere else (except as builtin function arguments),
1564           all partial applications are applied, meaning that all applications
1565           will become complete applications. However, since application of
1566           arguments happens one by one, in the expression:
1567           \startlambda
1568             f 1 2
1569           \stoplambda
1570           the subexpression \lam{f 1} has a function type. But this is
1571           allowed, since it is inside a complete application.
1572         \stopitemize
1573
1574         We will take a typical function with some higher order values as an
1575         example. The following function takes two arguments: a \lam{Bit} and a
1576         list of numbers. Depending on the first argument, each number in the
1577         list is doubled, or the list is returned unmodified. For the sake of
1578         the example, no polymorphism is shown. In reality, at least map would
1579         be polymorphic.
1580
1581         \startlambda
1582         λy.let double = λx. x + x in
1583              case y of
1584                 Low -> map double
1585                 High -> λz. z
1586         \stoplambda
1587
1588         This example shows a number of higher order values that we cannot
1589         translate to \VHDL directly. The \lam{double} binder bound in the let
1590         expression has a function type, as well as both of the alternatives of
1591         the case expression. The first alternative is a partial application of
1592         the \lam{map} builtin function, whereas the second alternative is a
1593         lambda abstraction.
1594
1595         To reduce all higher order values to one of the above items, a number
1596         of transformations we've already seen are used. The η-abstraction
1597         transformation from \in{section}[sec:normalization:eta] ensures all
1598         function arguments are introduced by lambda abstraction on the highest
1599         level of a function. These lambda arguments are allowed because of
1600         \in{item}[item:toplambda] above. After η-abstraction, our example
1601         becomes a bit bigger:
1602
1603         \startlambda
1604         λy.λq.(let double = λx. x + x in
1605                  case y of
1606                    Low -> map double
1607                    High -> λz. z
1608               ) q
1609         \stoplambda
1610
1611         η-abstraction also introduces extra applications (the application of
1612         the let expression to \lam{q} in the above example). These
1613         applications can then propagated down by the application propagation
1614         transformation (\in{section}[sec:normalization:appprop]). In our
1615         example, the \lam{q} and \lam{r} variable will be propagated into the
1616         let expression and then into the case expression:
1617
1618         \startlambda
1619         λy.λq.let double = λx. x + x in
1620                 case y of
1621                   Low -> map double q
1622                   High -> (λz. z) q
1623         \stoplambda
1624         
1625         This propagation makes higher order values become applied (in
1626         particular both of the alternatives of the case now have a
1627         representable type. Completely applied top level functions (like the
1628         first alternative) are now no longer invalid (they fall under
1629         \in{item}[item:completeapp] above). (Completely) applied lambda
1630         abstractions can be removed by β-abstraction. For our example,
1631         applying β-abstraction results in the following:
1632
1633         \startlambda
1634         λy.λq.let double = λx. x + x in
1635                 case y of
1636                   Low -> map double q
1637                   High -> q
1638         \stoplambda
1639
1640         As you can see in our example, all of this moves applications towards
1641         the higher order values, but misses higher order functions bound by
1642         let expressions. The applications cannot be moved towards these values
1643         (since they can be used in multiple places), so the values will have
1644         to be moved towards the applications. This is achieved by inlining all
1645         higher order values bound by let applications, by the
1646         non-representable binding inlining transformation below. When applying
1647         it to our example, we get the following:
1648         
1649         \startlambda
1650         λy.λq.case y of
1651                 Low -> map (λx. x + x) q
1652                 High -> q
1653         \stoplambda
1654
1655         We've nearly eliminated all unsupported higher order values from this
1656         expressions. The one that's remaining is the first argument to the
1657         \lam{map} function. Having higher order arguments to a builtin
1658         function like \lam{map} is allowed in the intended normal form, but
1659         only if the argument is a (partial application) of a top level
1660         function. This is easily done by introducing a new top level function
1661         and put the lambda abstraction inside. This is done by the function
1662         extraction transformation from
1663         \in{section}[sec:normalization:funextract].
1664
1665         \startlambda
1666         λy.λq.case y of
1667                 Low -> map func q
1668                 High -> q
1669         \stoplambda
1670
1671         This also introduces a new function, that we have called \lam{func}:
1672
1673         \startlambda
1674         func = λx. x + x
1675         \stoplambda
1676
1677         Note that this does not actually remove the lambda, but now it is a
1678         lambda at the highest level of a function, which is allowed in the
1679         intended normal form.
1680
1681         There is one case that has not been discussed yet. What if the
1682         \lam{map} function in the example above was not a builtin function
1683         but a user-defined function? Then extracting the lambda expression
1684         into a new function would not be enough, since user-defined functions
1685         can never have higher order arguments. For example, the following
1686         expression shows an example:
1687
1688         \startlambda
1689         twice :: (Word -> Word) -> Word -> Word
1690         twice = λf.λa.f (f a)
1691
1692         main = λa.app (λx. x + x) a
1693         \stoplambda
1694
1695         This example shows a function \lam{twice} that takes a function as a
1696         first argument and applies that function twice to the second argument.
1697         Again, we've made the function monomorphic for clarity, even though
1698         this function would be a lot more useful if it was polymorphic. The
1699         function \lam{main} uses \lam{twice} to apply a lambda epression twice.
1700
1701         When faced with a user defined function, a body is available for that
1702         function. This means we could create a specialized version of the
1703         function that only works for this particular higher order argument
1704         (\ie, we can just remove the argument and call the specialized
1705         function without the argument). This transformation is detailed below.
1706         Applying this transformation to the example gives:
1707
1708         \startlambda
1709         twice' :: Word -> Word
1710         twice' = λb.(λf.λa.f (f a)) (λx. x + x) b
1711
1712         main = λa.app' a
1713         \stoplambda
1714
1715         The \lam{main} function is now in normal form, since the only higher
1716         order value there is the top level lambda expression. The new
1717         \lam{twice'} function is a bit complex, but the entire original body of
1718         the original \lam{twice} function is wrapped in a lambda abstraction
1719         and applied to the argument we've specialized for (\lam{λx. x + x})
1720         and the other arguments. This complex expression can fortunately be
1721         effectively reduced by repeatedly applying β-reduction: 
1722
1723         \startlambda
1724         twice' :: Word -> Word
1725         twice' = λb.(b + b) + (b + b)
1726         \stoplambda
1727
1728         This example also shows that the resulting normal form might not be as
1729         efficient as we might hope it to be (it is calculating \lam{(b + b)}
1730         twice). This is discussed in more detail in
1731         \in{section}[sec:normalization:duplicatework].
1732
1733       \subsubsection{Literals}
1734         There are a limited number of literals available in Haskell and Core.
1735         \refdef{enumerated types} When using (enumerating) algebraic
1736         datatypes, a literal is just a reference to the corresponding data
1737         constructor, which has a representable type (the algebraic datatype)
1738         and can be translated directly. This also holds for literals of the
1739         \hs{Bool} Haskell type, which is just an enumerated type.
1740
1741         There is, however, a second type of literal that does not have a
1742         representable type: Integer literals. Cλash supports using integer
1743         literals for all three integer types supported (\hs{SizedWord},
1744         \hs{SizedInt} and \hs{RangedWord}). This is implemented using
1745         Haskell's \hs{Num} typeclass, which offers a \hs{fromInteger} method
1746         that converts any \hs{Integer} to the Cλash datatypes.
1747
1748         When \GHC sees integer literals, it will automatically insert calls to
1749         the \hs{fromInteger} method in the resulting Core expression. For
1750         example, the following expression in Haskell creates a 32 bit unsigned
1751         word with the value 1. The explicit type signature is needed, since
1752         there is no context for \GHC to determine the type from otherwise.
1753
1754         \starthaskell
1755         1 :: SizedWord D32
1756         \stophaskell
1757
1758         This Haskell code results in the following Core expression:
1759
1760         \startlambda
1761         fromInteger @(SizedWord D32) \$dNum (smallInteger 10)
1762         \stoplambda
1763
1764         The literal 10 will have the type \lam{GHC.Prim.Int\#}, which is
1765         converted into an \lam{Integer} by \lam{smallInteger}. Finally, the
1766         \lam{fromInteger} function will finally convert this into a
1767         \lam{SizedWord D32}.
1768
1769         Both the \lam{GHC.Prim.Int\#} and \lam{Integer} types are not
1770         representable, and cannot be translated directly. Fortunately, there
1771         is no need to translate them, since \lam{fromInteger} is a builtin
1772         function that knows how to handle these values. However, this does
1773         require that the \lam{fromInteger} function is directly applied to
1774         these non-representable literal values, otherwise errors will occur.
1775         For example, the following expression is not in the intended normal
1776         form, since one of the let bindings has an unrepresentable type
1777         (\lam{Integer}):
1778
1779         \startlambda
1780         let l = smallInteger 10 in fromInteger @(SizedWord D32) \$dNum l
1781         \stoplambda
1782
1783         By inlining these let-bindings, we can ensure that unrepresentable
1784         literals bound by a let binding end up in an application of the
1785         appropriate builtin function, where they are allowed. Since it is
1786         possible that the application of that function is in a different
1787         function than the definition of the literal value, we will always need
1788         to specialize away any unrepresentable literals that are used as
1789         function arguments. The following two transformations do exactly this.
1790
1791       \subsubsection{Non-representable binding inlining}
1792         This transform inlines let bindings that are bound to a
1793         non-representable value. Since we can never generate a signal
1794         assignment for these bindings (we cannot declare a signal assignment
1795         with a non-representable type, for obvious reasons), we have no choice
1796         but to inline the binding to remove it.
1797
1798         As we have seen in the previous sections, inlining these bindings
1799         solves (part of) the polymorphism, higher order values and
1800         unrepresentable literals in an expression.
1801
1802         \starttrans
1803         letrec 
1804           a0 = E0
1805           \vdots
1806           ai = Ei
1807           \vdots
1808           an = En
1809         in
1810           M
1811         --------------------------    \lam{Ei} has a non-representable type.
1812         letrec
1813           a0 = E0 [ai=>Ei] \vdots
1814           ai-1 = Ei-1 [ai=>Ei]
1815           ai+1 = Ei+1 [ai=>Ei]
1816           \vdots
1817           an = En [ai=>Ei]
1818         in
1819           M[ai=>Ei]
1820         \stoptrans
1821
1822         \startbuffer[from]
1823         letrec
1824           a = smallInteger 10
1825           inc = λb -> add b 1
1826           inc' = add 1
1827           x = fromInteger a 
1828         in
1829           inc (inc' x)
1830         \stopbuffer
1831
1832         \startbuffer[to]
1833         letrec
1834           x = fromInteger (smallInteger 10)
1835         in
1836           (λb -> add b 1) (add 1 x)
1837         \stopbuffer
1838
1839         \transexample{nonrepinline}{Nonrepresentable binding inlining}{from}{to}
1840
1841       \subsubsection[sec:normalization:specialize]{Function specialization}
1842         This transform removes arguments to user-defined functions that are
1843         not representable at runtime. This is done by creating a
1844         \emph{specialized} version of the function that only works for one
1845         particular value of that argument (in other words, the argument can be
1846         removed).
1847
1848         Specialization means to create a specialized version of the called
1849         function, with one argument already filled in. As a simple example, in
1850         the following program (this is not actual Core, since it directly uses
1851         a literal with the unrepresentable type \lam{GHC.Prim.Int\#}).
1852
1853         \startlambda
1854         f = λa.λb.a + b
1855         inc = λa.f a 1
1856         \stoplambda
1857
1858         We could specialize the function \lam{f} against the literal argument
1859         1, with the following result:
1860
1861         \startlambda
1862         f' = λa.a + 1
1863         inc = λa.f' a
1864         \stoplambda
1865
1866         In some way, this transformation is similar to β-reduction, but it
1867         operates across function boundaries. It is also similar to
1868         non-representable let binding inlining above, since it sort of
1869         \quote{inlines} an expression into a called function.
1870
1871         Special care must be taken when the argument has any free variables.
1872         If this is the case, the original argument should not be removed
1873         completely, but replaced by all the free variables of the expression.
1874         In this way, the original expression can still be evaluated inside the
1875         new function.
1876
1877         To prevent us from propagating the same argument over and over, a
1878         simple local variable reference is not propagated (since is has
1879         exactly one free variable, itself, we would only replace that argument
1880         with itself).
1881
1882         This shows that any free local variables that are not runtime
1883         representable cannot be brought into normal form by this transform. We
1884         rely on an inlining or β-reduction transformation to replace such a
1885         variable with an expression we can propagate again.
1886
1887         \starttrans
1888         x = E
1889         ~
1890         x Y0 ... Yi ... Yn                               \lam{Yi} is not representable
1891         ---------------------------------------------    \lam{Yi} is not a local variable reference
1892         x' y0 ... yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} are all free local vars of \lam{Yi}
1893         ~                                                \lam{T0 ... Tn} are the types of \lam{Y0 ... Yn}
1894         x' = λ(y0 :: T0) ... λ(yi-1 :: Ty-1). λf0 ... λfm. λ(yi+1 :: Ty+1) ...  λ(yn :: Tn).       
1895               E y0 ... yi-1 Yi yi+1 ... yn   
1896         \stoptrans
1897
1898         This is a bit of a complex transformation. It transforms an
1899         application of the function \lam{x}, where one of the arguments
1900         (\lam{Y_i}) is not representable. A new
1901         function \lam{x'} is created that wraps the body of the old function.
1902         The body of the new function becomes a number of nested lambda
1903         abstractions, one for each of the original arguments that are left
1904         unchanged.
1905         
1906         The ith argument is replaced with the free variables of
1907         \lam{Y_i}. Note that we reuse the same binders as those used in
1908         \lam{Y_i}, since we can then just use \lam{Y_i} inside the new
1909         function body and have all of the variables it uses be in scope.
1910
1911         The argument that we are specializing for, \lam{Y_i}, is put inside
1912         the new function body. The old function body is applied to it. Since
1913         we use this new function only in place of an application with that
1914         particular argument \lam{Y_i}, behaviour should not change.
1915         
1916         Note that the types of the arguments of our new function are taken
1917         from the types of the \emph{actual} arguments (\lam{T0 ... Tn}). This
1918         means that any polymorphism in the arguments is removed, even when the
1919         corresponding explicit type lambda is not removed
1920         yet.\refdef{type lambda}
1921
1922         \todo{Examples. Perhaps reference the previous sections}
1923
1924
1925   \section{Unsolved problems}
1926     The above system of transformations has been implemented in the prototype
1927     and seems to work well to compile simple and more complex examples of
1928     hardware descriptions. \todo{Ref christiaan?} However, this normalization
1929     system has not seen enough review and work to be complete and work for
1930     every Core expression that is supplied to it. A number of problems
1931     have already been identified and are discussed in this section.
1932
1933     \subsection[sec:normalization:duplicatework]{Work duplication}
1934         A possible problem of β-reduction is that it could duplicate work.
1935         When the expression applied is not a simple variable reference, but
1936         requires calculation and the binder the lambda abstraction binds to
1937         is used more than once, more hardware might be generated than strictly
1938         needed. 
1939
1940         As an example, consider the expression:
1941
1942         \startlambda
1943         (λx. x + x) (a * b)
1944         \stoplambda
1945
1946         When applying β-reduction to this expression, we get:
1947
1948         \startlambda
1949         (a * b) + (a * b)
1950         \stoplambda
1951
1952         which of course calculates \lam{(a * b)} twice.
1953         
1954         A possible solution to this would be to use the following alternative
1955         transformation, which is of course no longer normal β-reduction. The
1956         followin transformation has not been tested in the prototype, but is
1957         given here for future reference:
1958
1959         \starttrans
1960         (λx.E) M
1961         -----------------
1962         letrec x = M in E
1963         \stoptrans
1964         
1965         This doesn't seem like much of an improvement, but it does get rid of
1966         the lambda expression (and the associated higher order value), while
1967         at the same time introducing a new let binding. Since the result of
1968         every application or case expression must be bound by a let expression
1969         in the intended normal form anyway, this is probably not a problem. If
1970         the argument happens to be a variable reference, then simple let
1971         binding removal (\in{section}[sec:normalization:simplelet]) will
1972         remove it, making the result identical to that of the original
1973         β-reduction transformation.
1974
1975         When also applying argument simplification to the above example, we
1976         get the following expression:
1977
1978         \startlambda
1979         let y = (a * b)
1980             z = (a * b)
1981         in y + z
1982         \stoplambda
1983
1984         Looking at this, we could imagine an alternative approach: Create a
1985         transformation that removes let bindings that bind identical values.
1986         In the above expression, the \lam{y} and \lam{z} variables could be
1987         merged together, resulting in the more efficient expression:
1988
1989         \startlambda
1990         let y = (a * b) in y + y
1991         \stoplambda
1992
1993       \subsection{Non-determinism}
1994         As an example, again consider the following expression:
1995
1996         \startlambda
1997         (λx. x + x) (a * b)
1998         \stoplambda
1999
2000         We can apply both β-reduction (\in{section}[sec:normalization:beta])
2001         as well as argument simplification
2002         (\in{section}[sec:normalization:argsimpl]) to this expression.
2003
2004         When applying argument simplification first and then β-reduction, we
2005         get the following expression:
2006
2007         \startlambda
2008         let y = (a * b) in y + y
2009         \stoplambda
2010
2011         When applying β-reduction first and then argument simplification, we
2012         get the following expression:
2013
2014         \startlambda
2015         let y = (a * b)
2016             z = (a * b)
2017         in y + z
2018         \stoplambda
2019
2020         As you can see, this is a different expression. This means that the
2021         order of expressions, does in fact change the resulting normal form,
2022         which is something that we would like to avoid. In this particular
2023         case one of the alternatives is even clearly more efficient, so we
2024         would of course like the more efficient form to be the normal form.
2025
2026         For this particular problem, the solutions for duplication of work
2027         seem from the previous section seem to fix the determinism of our
2028         transformation system as well. However, it is likely that there are
2029         other occurences of this problem.
2030
2031       \subsection{Casts}
2032         We do not fully understand the use of cast expressions in Core, so
2033         there are probably expressions involving cast expressions that cannot
2034         be brought into intended normal form by this transformation system.
2035
2036         The uses of casts in the core system should be investigated more and
2037         transformations will probably need updating to handle them in all
2038         cases.
2039
2040   \section[sec:normalization:properties]{Provable properties}
2041     When looking at the system of transformations outlined above, there are a
2042     number of questions that we can ask ourselves. The main question is of course:
2043     \quote{Does our system work as intended?}. We can split this question into a
2044     number of subquestions:
2045
2046     \startitemize[KR]
2047     \item[q:termination] Does our system \emph{terminate}? Since our system will
2048     keep running as long as transformations apply, there is an obvious risk that
2049     it will keep running indefinitely. This typically happens when one
2050     transformation produces a result that is transformed back to the original
2051     by another transformation, or when one or more transformations keep
2052     expanding some expression.
2053     \item[q:soundness] Is our system \emph{sound}? Since our transformations
2054     continuously modify the expression, there is an obvious risk that the final
2055     normal form will not be equivalent to the original program: Its meaning could
2056     have changed.
2057     \item[q:completeness] Is our system \emph{complete}? Since we have a complex
2058     system of transformations, there is an obvious risk that some expressions will
2059     not end up in our intended normal form, because we forgot some transformation.
2060     In other words: Does our transformation system result in our intended normal
2061     form for all possible inputs?
2062     \item[q:determinism] Is our system \emph{deterministic}? Since we have defined
2063     no particular order in which the transformation should be applied, there is an
2064     obvious risk that different transformation orderings will result in
2065     \emph{different} normal forms. They might still both be intended normal forms
2066     (if our system is \emph{complete}) and describe correct hardware (if our
2067     system is \emph{sound}), so this property is less important than the previous
2068     three: The translator would still function properly without it.
2069     \stopitemize
2070
2071     Unfortunately, the final transformation system has only been
2072     developed in the final part of the research, leaving no more time
2073     for verifying these properties. In fact, it is likely that the
2074     current transformation system still violates some of these
2075     properties in some cases and should be improved (or extra conditions
2076     on the input hardware descriptions should be formulated).
2077
2078     This is most likely the case with the completeness and determinism
2079     properties, perhaps als the termination property. The soundness
2080     property probably holds, since it is easier to manually verify (each
2081     transformation can be reviewed separately).
2082
2083     Even though no complete proofs have been made, some ideas for
2084     possible proof strategies are shown below.
2085
2086     \subsection{Graph representation}
2087       Before looking into how to prove these properties, we'll look at our
2088       transformation system from a graph perspective. The nodes of the graph are
2089       all possible Core expressions. The (directed) edges of the graph are
2090       transformations. When a transformation α applies to an expression \lam{A} to
2091       produce an expression \lam{B}, we add an edge from the node for \lam{A} to the
2092       node for \lam{B}, labeled α.
2093
2094       \startuseMPgraphic{TransformGraph}
2095         save a, b, c, d;
2096
2097         % Nodes
2098         newCircle.a(btex \lam{(λx.λy. (+) x y) 1} etex);
2099         newCircle.b(btex \lam{λy. (+) 1 y} etex);
2100         newCircle.c(btex \lam{(λx.(+) x) 1} etex);
2101         newCircle.d(btex \lam{(+) 1} etex);
2102
2103         b.c = origin;
2104         c.c = b.c + (4cm, 0cm);
2105         a.c = midpoint(b.c, c.c) + (0cm, 4cm);
2106         d.c = midpoint(b.c, c.c) - (0cm, 3cm);
2107
2108         % β-conversion between a and b
2109         ncarc.a(a)(b) "name(bred)";
2110         ObjLabel.a(btex $\xrightarrow[normal]{}{β}$ etex) "labpathname(bred)", "labdir(rt)";
2111         ncarc.b(b)(a) "name(bexp)", "linestyle(dashed withdots)";
2112         ObjLabel.b(btex $\xleftarrow[normal]{}{β}$ etex) "labpathname(bexp)", "labdir(lft)";
2113
2114         % η-conversion between a and c
2115         ncarc.a(a)(c) "name(ered)";
2116         ObjLabel.a(btex $\xrightarrow[normal]{}{η}$ etex) "labpathname(ered)", "labdir(rt)";
2117         ncarc.c(c)(a) "name(eexp)", "linestyle(dashed withdots)";
2118         ObjLabel.c(btex $\xleftarrow[normal]{}{η}$ etex) "labpathname(eexp)", "labdir(lft)";
2119
2120         % η-conversion between b and d
2121         ncarc.b(b)(d) "name(ered)";
2122         ObjLabel.b(btex $\xrightarrow[normal]{}{η}$ etex) "labpathname(ered)", "labdir(rt)";
2123         ncarc.d(d)(b) "name(eexp)", "linestyle(dashed withdots)";
2124         ObjLabel.d(btex $\xleftarrow[normal]{}{η}$ etex) "labpathname(eexp)", "labdir(lft)";
2125
2126         % β-conversion between c and d
2127         ncarc.c(c)(d) "name(bred)";
2128         ObjLabel.c(btex $\xrightarrow[normal]{}{β}$ etex) "labpathname(bred)", "labdir(rt)";
2129         ncarc.d(d)(c) "name(bexp)", "linestyle(dashed withdots)";
2130         ObjLabel.d(btex $\xleftarrow[normal]{}{β}$ etex) "labpathname(bexp)", "labdir(lft)";
2131
2132         % Draw objects and lines
2133         drawObj(a, b, c, d);
2134       \stopuseMPgraphic
2135
2136       \placeexample[right][ex:TransformGraph]{Partial graph of a lambda calculus
2137       system with β and η reduction (solid lines) and expansion (dotted lines).}
2138           \boxedgraphic{TransformGraph}
2139
2140       Of course our graph is unbounded, since we can construct an infinite amount of
2141       Core expressions. Also, there might potentially be multiple edges between two
2142       given nodes (with different labels), though seems unlikely to actually happen
2143       in our system.
2144
2145       See \in{example}[ex:TransformGraph] for the graph representation of a very
2146       simple lambda calculus that contains just the expressions \lam{(λx.λy. (+) x
2147       y) 1}, \lam{λy. (+) 1 y}, \lam{(λx.(+) x) 1} and \lam{(+) 1}. The
2148       transformation system consists of β-reduction and η-reduction (solid edges) or
2149       β-expansion and η-expansion (dotted edges).
2150
2151       \todo{Define β-reduction and η-reduction?}
2152
2153       Note that the normal form of such a system consists of the set of nodes
2154       (expressions) without outgoing edges, since those are the expression to which
2155       no transformation applies anymore. We call this set of nodes the \emph{normal
2156       set}. The set of nodes containing expressions in intended normal
2157       form \refdef{intended normal form} is called the \emph{intended
2158       normal set}.
2159
2160       From such a graph, we can derive some properties easily:
2161       \startitemize[KR]
2162         \item A system will \emph{terminate} if there is no path of infinite length
2163         in the graph (this includes cycles, but can also happen without cycles).
2164         \item Soundness is not easily represented in the graph.
2165         \item A system is \emph{complete} if all of the nodes in the normal set have
2166         the intended normal form. The inverse (that all of the nodes outside of
2167         the normal set are \emph{not} in the intended normal form) is not
2168         strictly required. In other words, our normal set must be a
2169         subset of the intended normal form, but they do not need to be
2170         the same set.
2171         form.
2172         \item A system is deterministic if all paths starting at a particular
2173         node, which end in a node in the normal set, end at the same node.
2174       \stopitemize
2175
2176       When looking at the \in{example}[ex:TransformGraph], we see that the system
2177       terminates for both the reduction and expansion systems (but note that, for
2178       expansion, this is only true because we've limited the possible
2179       expressions.  In comlete lambda calculus, there would be a path from
2180       \lam{(λx.λy. (+) x y) 1} to \lam{(λx.λy.(λz.(+) z) x y) 1} to
2181       \lam{(λx.λy.(λz.(λq.(+) q) z) x y) 1} etc.)
2182
2183       If we would consider the system with both expansion and reduction, there
2184       would no longer be termination either, since there would be cycles all
2185       over the place.
2186
2187       The reduction and expansion systems have a normal set of containing just
2188       \lam{(+) 1} or \lam{(λx.λy. (+) x y) 1} respectively. Since all paths in
2189       either system end up in these normal forms, both systems are \emph{complete}.
2190       Also, since there is only one node in the normal set, it must obviously be
2191       \emph{deterministic} as well.
2192
2193     \todo{Add content to these sections}
2194     \subsection{Termination}
2195       In general, proving termination of an arbitrary program is a very
2196       hard problem. \todo{Ref about arbitrary termination} Fortunately,
2197       we only have to prove termination for our specific transformation
2198       system.
2199
2200       A common approach for these kinds of proofs is to associate a
2201       measure with each possible expression in our system. If we can
2202       show that each transformation strictly decreases this measure
2203       (\ie, the expression transformed to has a lower measure than the
2204       expression transformed from).  \todo{ref about measure-based
2205       termination proofs / analysis}
2206       
2207       A good measure for a system consisting of just β-reduction would
2208       be the number of lambda expressions in the expression. Since every
2209       application of β-reduction removes a lambda abstraction (and there
2210       is always a bounded number of lambda abstractions in every
2211       expression) we can easily see that a transformation system with
2212       just β-reduction will always terminate.
2213
2214       For our complete system, this measure would be fairly complex
2215       (probably the sum of a lot of things). Since the (conditions on)
2216       our transformations are pretty complex, we would need to include
2217       both simple things like the number of let expressions as well as
2218       more complex things like the number of case expressions that are
2219       not yet in normal form.
2220
2221       No real attempt has been made at finding a suitable measure for
2222       our system yet.
2223
2224     \subsection{Soundness}
2225       Soundness is a property that can be proven for each transformation
2226       separately. Since our system only runs separate transformations
2227       sequentially, if each of our transformations leaves the
2228       \emph{meaning} of the expression unchanged, then the entire system
2229       will of course leave the meaning unchanged and is thus
2230       \emph{sound}.
2231
2232       The current prototype has only been verified in an ad-hoc fashion
2233       by inspecting (the code for) each transformation. A more formal
2234       verification would be more appropriate.
2235
2236       To be able to formally show that each transformation properly
2237       preserves the meaning of every expression, we require an exact
2238       definition of the \emph{meaning} of every expression, so we can
2239       compare them. Currently there seems to be no formal definition of
2240       the meaning or semantics of \GHC's core language, only informal
2241       descriptions are available.
2242
2243       It should be possible to have a single formal definition of
2244       meaning for Core for both normal Core compilation by \GHC and for
2245       our compilation to \VHDL. The main difference seems to be that in
2246       hardware every expression is always evaluated, while in software
2247       it is only evaluated if needed, but it should be possible to
2248       assign a meaning to core expressions that assumes neither.
2249       
2250       Since each of the transformations can be applied to any
2251       subexpression as well, there is a constraint on our meaning
2252       definition: The meaning of an expression should depend only on the
2253       meaning of subexpressions, not on the expressions themselves. For
2254       example, the meaning of the application in \lam{f (let x = 4 in
2255       x)} should be the same as the meaning of the application in \lam{f
2256       4}, since the argument subexpression has the same meaning (though
2257       the actual expression is different).
2258       
2259     \subsection{Completeness}
2260       Proving completeness is probably not hard, but it could be a lot
2261       of work. We have seen above that to prove completeness, we must
2262       show that the normal set of our graph representation is a subset
2263       of the intended normal set.
2264
2265       However, it is hard to systematically generate or reason about the
2266       normal set, since it is defined as any nodes to which no
2267       transformation applies. To determine this set, each transformation
2268       must be considered and when a transformation is added, the entire
2269       set should be re-evaluated. This means it is hard to show that
2270       each node in the normal set is also in the intended normal set.
2271       Reasoning about our intended normal set is easier, since we know
2272       how to generate it from its definition. \refdef{intended normal
2273       form definition}.
2274
2275       Fortunately, we can also prove the complement (which is
2276       equivalent, since $A \subseteq B \Leftrightarrow \overline{B}
2277       \subseteq \overline{A}$): Show that the set of nodes not in
2278       intended normal form is a subset of the set of nodes not in normal
2279       form. In other words, show that for every expression that is not
2280       in intended normal form, that there is at least one transformation
2281       that applies to it (since that means it is not in normal form
2282       either and since $A \subseteq C \Leftrightarrow \forall x (x \in A
2283       \rightarrow x \in C)$).
2284
2285       By systematically reviewing the entire Core language definition
2286       along with the intended normal form definition (both of which have
2287       a similar structure), it should be possible to identify all
2288       possible (sets of) core expressions that are not in intended
2289       normal form and identify a transformation that applies to it.
2290       
2291       This approach is especially useful for proving completeness of our
2292       system, since if expressions exist to which none of the
2293       transformations apply (\ie if the system is not yet complete), it
2294       is immediately clear which expressions these are and adding
2295       (or modifying) transformations to fix this should be relatively
2296       easy.
2297
2298       As observed above, applying this approach is a lot of work, since
2299       we need to check every (set of) transformation(s) separately.
2300
2301       \todo{Perhaps do a few steps of the proofs as proof-of-concept}
2302
2303 % vim: set sw=2 sts=2 expandtab: