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