Use normal style zeroes instead of using the sans font.
[matthijs/master-project/report.git] / Chapters / HardwareDescription.tex
1 \chapter[chap:description]{Hardware description}
2   In this chapter an overview will be provided of the hardware
3   description language that was created and the issues that have arisen
4   in the process. The focus will be on the issues of the language, not
5   the implementation. The prototype implementation will be discussed in
6   \in{chapter}[chap:prototype].
7
8   \todo{Shortshort introduction to Cλash (Bit, Word, and, not, etc.)}
9
10   To translate Haskell to hardware, every Haskell construct needs a
11   translation to \VHDL. There are often multiple valid translations
12   possible. When faced with choices, the most obvious choice has been
13   chosen wherever possible. In a lot of cases, when a programmer looks
14   at a functional hardware description it is completely clear what
15   hardware is described. We want our translator to generate exactly that
16   hardware whenever possible, to make working with Cλash as intuitive as
17   possible.
18    
19   \placeintermezzo{}{
20     \defref{top level binder}
21     \defref{top level function}
22     \startframedtext[width=8cm,background=box,frame=no]
23     \startalignment[center]
24       {\tfa Top level binders and functions}
25     \stopalignment
26     \blank[medium]
27       A top level binder is any binder (variable) that is declared in
28       the \quote{global} scope of a Haskell program (as opposed to a
29       binder that is bound inside a function.
30
31       In Haskell, there is no sharp distinction between a variable and a
32       function: A function is just a variable (binder) with a function
33       type. This means that a top level function is just any top level
34       binder with a function type.
35
36       As an example, consider the following Haskell snippet:
37
38       \starthaskell
39         foo :: Int -> Int
40         foo x = inc x
41           where
42             inc = \y -> y + 1
43       \stophaskell
44
45       Here, \hs{foo} is a top level binder, whereas \hs{inc} is a
46       function (since it is bound to a lambda extraction, indicated by
47       the backslash) but is not a top level binder or function.  Since
48       the type of \hs{foo} is a function type, namely \hs{Int -> Int},
49       it is also a top level function.
50     \stopframedtext
51   }
52   In this chapter we describe how to interpret a Haskell program from a
53   hardware perspective. We provide a description of each Haskell language
54   element that needs translation, to provide a clear picture of what is
55   supported and how.
56
57
58   \section[sec:description:application]{Function application}
59   \todo{Sidenote: Inputs vs arguments}
60   The basic syntactic elements of a functional program are functions and
61   function application. These have a single obvious \small{VHDL}
62   translation: Each top level function becomes a hardware component, where each
63   argument is an input port and the result value is the (single) output
64   port. This output port can have a complex type (such as a tuple), so
65   having just a single output port does not pose a limitation.
66
67   Each function application in turn becomes component instantiation. Here, the
68   result of each argument expression is assigned to a signal, which is mapped
69   to the corresponding input port. The output port of the function is also
70   mapped to a signal, which is used as the result of the application.
71
72   Since every top level function generates its own component, the
73   hierarchy of of function calls is reflected in the final \VHDL output
74   as well, creating a hierarchical \VHDL description of the hardware.
75   This separation in different components makes the resulting \VHDL
76   output easier to read and debug.
77
78   \in{Example}[ex:And3] shows a simple program using only function
79   application and the corresponding architecture.
80
81 \startbuffer[And3]
82 -- | A simple function that returns 
83 --   conjunction of three bits
84 and3 :: Bit -> Bit -> Bit -> Bit
85 and3 a b c = and (and a b) c
86 \stopbuffer
87
88   \startuseMPgraphic{And3}
89     save a, b, c, anda, andb, out;
90
91     % I/O ports
92     newCircle.a(btex $a$ etex) "framed(false)";
93     newCircle.b(btex $b$ etex) "framed(false)";
94     newCircle.c(btex $c$ etex) "framed(false)";
95     newCircle.out(btex $out$ etex) "framed(false)";
96
97     % Components
98     newCircle.anda(btex $and$ etex);
99     newCircle.andb(btex $and$ etex);
100
101     a.c    = origin;
102     b.c    = a.c + (0cm, 1cm);
103     c.c    = b.c + (0cm, 1cm);
104     anda.c = midpoint(a.c, b.c) + (2cm, 0cm);
105     andb.c = midpoint(b.c, c.c) + (4cm, 0cm);
106
107     out.c   = andb.c + (2cm, 0cm);
108
109     % Draw objects and lines
110     drawObj(a, b, c, anda, andb, out);
111
112     ncarc(a)(anda) "arcangle(-10)";
113     ncarc(b)(anda);
114     ncarc(anda)(andb);
115     ncarc(c)(andb);
116     ncline(andb)(out);
117   \stopuseMPgraphic
118
119   \placeexample[here][ex:And3]{Simple three input and gate.}
120     \startcombination[2*1]
121       {\typebufferhs{And3}}{Haskell description using function applications.}
122       {\boxedgraphic{And3}}{The architecture described by the Haskell description.}
123     \stopcombination
124
125   \section{Choice}
126     Although describing components and connections allows us to describe a lot of
127     hardware designs already, there is an obvious thing missing: Choice. We
128     need some way to be able to choose between values based on another value.
129     In Haskell, choice is achieved by \hs{case} expressions, \hs{if}
130     expressions, pattern matching and guards.
131
132     An obvious way to add choice to our language without having to recognize
133     any of Haskell's syntax, would be to add a primivite \quote{\hs{if}}
134     function. This function would take three arguments: The condition, the
135     value to return when the condition is true and the value to return when
136     the condition is false.
137
138     This \hs{if} function would then essentially describe a multiplexer and
139     allows us to describe any architecture that uses multiplexers. \fxnote{Are
140     there other mechanisms of choice in hardware?}
141
142     However, to be able to describe our hardware in a more convenient way, we
143     also want to translate Haskell's choice mechanisms. The easiest of these
144     are of course case expressions (and \hs{if} expressions, which can be very
145     directly translated to \hs{case} expressions). A \hs{case} expression can in turn
146     simply be translated to a conditional assignment, where the conditions use
147     equality comparisons against the constructors in the \hs{case} expressions.
148
149     \todo{Assignment vs multiplexers}
150
151     In \in{example}[ex:CaseInv] a simple \hs{case} expression is shown,
152     scrutinizing a boolean value. The corresponding architecture has a
153     comparator to determine which of the constructors is on the \hs{in}
154     input. There is a multiplexer to select the output signal. The two options
155     for the output signals are just constants, but these could have been more
156     complex expressions (in which case also both of them would be working in
157     parallel, regardless of which output would be chosen eventually).
158     
159     If we would translate a Boolean to a bit value, we could of course remove
160     the comparator and directly feed 'in' into the multiplexer (or even use an
161     inverter instead of a multiplexer).  However, we will try to make a
162     general translation, which works for all possible \hs{case} expressions.
163     Optimizations such as these are left for the \VHDL synthesizer, which
164     handles them very well.
165
166     \todo{Be more explicit about >2 alternatives}
167
168     \startbuffer[CaseInv]
169     inv :: Bool -> Bool
170     inv x = case x of
171       True -> False
172       False -> True
173     \stopbuffer
174
175     \startuseMPgraphic{CaseInv}
176       save in, truecmp, falseout, trueout, out, cmp, mux;
177
178       % I/O ports
179       newCircle.in(btex $in$ etex) "framed(false)";
180       newCircle.out(btex $out$ etex) "framed(false)";
181       % Constants
182       newBox.truecmp(btex $True$ etex) "framed(false)";
183       newBox.trueout(btex $True$ etex) "framed(false)";
184       newBox.falseout(btex $False$ etex) "framed(false)";
185
186       % Components
187       newCircle.cmp(btex $==$ etex);
188       newMux.mux;
189
190       in.c       = origin;
191       cmp.c      = in.c + (3cm, 0cm);
192       truecmp.c  = cmp.c + (-1cm, 1cm);
193       mux.sel    = cmp.e + (1cm, -1cm);
194       falseout.c = mux.inpa - (2cm, 0cm);
195       trueout.c  = mux.inpb - (2cm, 0cm);
196       out.c      = mux.out + (2cm, 0cm);
197
198       % Draw objects and lines
199       drawObj(in, out, truecmp, trueout, falseout, cmp, mux);
200
201       ncline(in)(cmp);
202       ncarc(truecmp)(cmp);
203       nccurve(cmp.e)(mux.sel) "angleA(0)", "angleB(-90)";
204       ncline(falseout)(mux) "posB(inpa)";
205       ncline(trueout)(mux) "posB(inpb)";
206       ncline(mux)(out) "posA(out)";
207     \stopuseMPgraphic
208
209     \placeexample[here][ex:CaseInv]{Simple inverter.}
210       \startcombination[2*1]
211         {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
212         {\boxedgraphic{CaseInv}}{The architecture described by the Haskell description.}
213       \stopcombination
214
215     A slightly more complex (but very powerful) form of choice is pattern
216     matching. A function can be defined in multiple clauses, where each clause
217     specifies a pattern. When the arguments match the pattern, the
218     corresponding clause will be used.
219
220     \startbuffer[PatternInv]
221     inv :: Bool -> Bool
222     inv True = False
223     inv False = True
224     \stopbuffer
225
226     \placeexample[here][ex:PatternInv]{Simple inverter using pattern matching.
227     Describes the same architecture as \in{example}[ex:CaseInv].}
228         {\typebufferhs{PatternInv}}
229
230     The architecture described by \in{example}[ex:PatternInv] is of course the
231     same one as the one in \in{example}[ex:CaseInv]. The general interpretation
232     of pattern matching is also similar to that of \hs{case} expressions: Generate
233     hardware for each of the clauses (like each of the clauses of a \hs{case}
234     expression) and connect them to the function output through (a number of
235     nested) multiplexers. These multiplexers are driven by comparators and
236     other logic, that check each pattern in turn.
237
238   \section{Types}
239     Translation of two most basic functional concepts has been
240     discussed: Function application and choice. Before looking further
241     into less obvious concepts like higher-order expressions and
242     polymorphism, the possible types that can be used in hardware
243     descriptions will be discussed.
244
245     Some way is needed to translate every values used to its hardware
246     equivalents. In particular, this means a hardware equivalent for
247     every \emph{type} used in a hardware description is needed
248
249     Since most functional languages have a lot of standard types that
250     are hard to translate (integers without a fixed size, lists without
251     a static length, etc.), a number of \quote{built-in} types will be
252     defined first. These types are built-in in the sense that our
253     compiler will have a fixed VHDL type for these. User defined types,
254     on the other hand, will have their hardware type derived directly
255     from their Haskell declaration automatically, according to the rules
256     sketched here.
257
258     \todo{Introduce Haskell type syntax (type constructors, type application,
259     :: operator?)}
260
261     \subsection{Built-in types}
262       The language currently supports the following built-in types. Of these,
263       only the \hs{Bool} type is supported by Haskell out of the box (the
264       others are defined by the Cλash package, so they are user-defined types
265       from Haskell's point of view).
266
267       \startdesc{\hs{Bit}}
268         This is the most basic type available. It is mapped directly onto
269         the \type{std_logic} \small{VHDL} type. Mapping this to the
270         \type{bit} type might make more sense (since the Haskell version
271         only has two values), but using \type{std_logic} is more standard
272         (and allowed for some experimentation with don't care values)
273
274         \todo{Sidenote bit vs stdlogic}
275       \stopdesc
276       \startdesc{\hs{Bool}}
277         This is the only built-in Haskell type supported and is translated
278         exactly like the Bit type (where a value of \hs{True} corresponds to a
279         value of \hs{High}). Supporting the Bool type is particularly
280         useful to support \hs{if ... then ... else ...} expressions, which
281         always have a \hs{Bool} value for the condition.
282
283         A \hs{Bool} is translated to a \type{std_logic}, just like \hs{Bit}.
284       \stopdesc
285       \startdesc{\hs{SizedWord}, \hs{SizedInt}}
286         These are types to represent integers. A \hs{SizedWord} is unsigned,
287         while a \hs{SizedInt} is signed. These types are parameterized by a
288         length type, so you can define an unsigned word of 32 bits wide as
289         follows:
290         
291         \starthaskell
292           type Word32 = SizedWord D32
293         \stophaskell
294
295         Here, a type synonym \hs{Word32} is defined that is equal to the
296         \hs{SizedWord} type constructor applied to the type \hs{D32}. \hs{D32}
297         is the \emph{type level representation} of the decimal number 32,
298         making the \hs{Word32} type a 32-bit unsigned word.
299
300         These types are translated to the \small{VHDL} \type{unsigned} and
301         \type{signed} respectively.
302         \todo{Sidenote on dependent typing?}
303       \stopdesc
304       \startdesc{\hs{Vector}}
305         This is a vector type, that can contain elements of any other type and
306         has a fixed length. It has two type parameters: Its
307         length and the type of the elements contained in it. By putting the
308         length parameter in the type, the length of a vector can be determined
309         at compile time, instead of only at runtime for conventional lists.
310
311         The \hs{Vector} type constructor takes two type arguments: The length
312         of the vector and the type of the elements contained in it. The state
313         type of an 8 element register bank would then for example be:
314
315         \starthaskell
316         type RegisterState = Vector D8 Word32
317         \stophaskell
318
319         Here, a type synonym \hs{RegisterState} is defined that is equal to
320         the \hs{Vector} type constructor applied to the types \hs{D8} (The type
321         level representation of the decimal number 8) and \hs{Word32} (The 32
322         bit word type as defined above). In other words, the
323         \hs{RegisterState} type is a vector of 8 32-bit words.
324
325         A fixed size vector is translated to a \small{VHDL} array type.
326       \stopdesc
327       \startdesc{\hs{RangedWord}}
328         This is another type to describe integers, but unlike the previous
329         two it has no specific bitwidth, but an upper bound. This means that
330         its range is not limited to powers of two, but can be any number.
331         A \hs{RangedWord} only has an upper bound, its lower bound is
332         implicitly zero. There is a lot of added implementation complexity
333         when adding a lower bound and having just an upper bound was enough
334         for the primary purpose of this type: Typesafely indexing vectors.
335
336         To define an index for the 8 element vector above, we would do:
337
338         \starthaskell
339         type RegisterIndex = RangedWord D7
340         \stophaskell
341
342         Here, a type synonym \hs{RegisterIndex} is defined that is equal to
343         the \hs{RangedWord} type constructor applied to the type \hs{D7}. In
344         other words, this defines an unsigned word with values from
345         {\definedfont[Serif*normalnum]0 to 7} (inclusive). This word can be be used to index the
346         8 element vector \hs{RegisterState} above.
347
348         This type is translated to the \type{unsigned} \small{VHDL} type.
349       \stopdesc
350
351       The integer and vector built-in types are discussed in more detail
352       in \cite[baaij09].
353
354     \subsection{User-defined types}
355       There are three ways to define new types in Haskell: Algebraic
356       datatypes with the \hs{data} keyword, type synonyms with the \hs{type}
357       keyword and type renamings with the \hs{newtype} keyword. \GHC
358       offers a few more advanced ways to introduce types (type families,
359       existential typing, \small{GADT}s, etc.) which are not standard
360       Haskell.  These will be left outside the scope of this research.
361
362       Only an algebraic datatype declaration actually introduces a
363       completely new type, for which we provide the \VHDL translation
364       below. Type synonyms and renamings only define new names for
365       existing types (where synonyms are completely interchangeable and
366       renamings need explicit conversion). Therefore, these do not need
367       any particular \VHDL translation, a synonym or renamed type will
368       just use the same representation as the original type. The
369       distinction between a renaming and a synonym does no longer matter
370       in hardware and can be disregarded in the generated \VHDL.
371
372       For algebraic types, we can make the following distinction:
373
374       \startdesc{Product types}
375         A product type is an algebraic datatype with a single constructor with
376         two or more fields, denoted in practice like (a,b), (a,b,c), etc. This
377         is essentially a way to pack a few values together in a record-like
378         structure. In fact, the built-in tuple types are just algebraic product
379         types (and are thus supported in exactly the same way).
380
381         The \quote{product} in its name refers to the collection of values belonging
382         to this type. The collection for a product type is the Cartesian
383         product of the collections for the types of its fields.
384
385         These types are translated to \VHDL record types, with one field for
386         every field in the constructor. This translation applies to all single
387         constructor algebraic datatypes, including those with just one
388         field (which are technically not a product, but generate a VHDL
389         record for implementation simplicity).
390       \stopdesc
391       \startdesc{Enumerated types}
392         \defref{enumerated types}
393         An enumerated type is an algebraic datatype with multiple constructors, but
394         none of them have fields. This is essentially a way to get an
395         enum-like type containing alternatives.
396
397         Note that Haskell's \hs{Bool} type is also defined as an
398         enumeration type, but we have a fixed translation for that.
399         
400         These types are translated to \VHDL enumerations, with one value for
401         each constructor. This allows references to these constructors to be
402         translated to the corresponding enumeration value.
403       \stopdesc
404       \startdesc{Sum types}
405         A sum type is an algebraic datatype with multiple constructors, where
406         the constructors have one or more fields. Technically, a type with
407         more than one field per constructor is a sum of products type, but
408         for our purposes this distinction does not really make a
409         difference, so this distinction is note made.
410
411         The \quote{sum} in its name refers again to the collection of values
412         belonging to this type. The collection for a sum type is the
413         union of the the collections for each of the constructors.
414
415         Sum types are currently not supported by the prototype, since there is
416         no obvious \VHDL alternative. They can easily be emulated, however, as
417         we will see from an example:
418
419         \starthaskell
420         data Sum = A Bit Word | B Word 
421         \stophaskell
422
423         An obvious way to translate this would be to create an enumeration to
424         distinguish the constructors and then create a big record that
425         contains all the fields of all the constructors. This is the same
426         translation that would result from the following enumeration and
427         product type (using a tuple for clarity):
428
429         \starthaskell
430         data SumC = A | B
431         type Sum = (SumC, Bit, Word, Word)
432         \stophaskell
433
434         Here, the \hs{SumC} type effectively signals which of the latter three
435         fields of the \hs{Sum} type are valid (the first two if \hs{A}, the
436         last one if \hs{B}), all the other ones have no useful value.
437
438         An obvious problem with this naive approach is the space usage: The
439         example above generates a fairly big \VHDL type. Since we can be
440         sure that the two \hs{Word}s in the \hs{Sum} type will never be valid
441         at the same time, this is a waste of space.
442
443         Obviously, duplication detection could be used to reuse a
444         particular field for another constructor, but this would only
445         partially solve the problem. If two fields would be, for
446         example, an array of 8 bits and an 8 bit unsiged word, these are
447         different types and could not be shared. However, in the final
448         hardware, both of these types would simply be 8 bit connections,
449         so we have a 100\% size increase by not sharing these.
450       \stopdesc
451
452       Another interesting case is that of recursive types. In Haskell, an
453       algebraic datatype can be recursive: Any of its field types can be (or
454       contain) the type being defined. The most well-known recursive type is
455       probably the list type, which is defined is:
456       
457       \starthaskell
458       data List t = Empty | Cons t (List t)
459       \stophaskell
460
461       Note that \hs{Empty} is usually written as \hs{[]} and \hs{Cons} as
462       \hs{:}, but this would make the definition harder to read.  This
463       immediately shows the problem with recursive types: What hardware type
464       to allocate here? 
465       
466       If the naive approach for sum types described above would be used,
467       a record would be created where the first field is an enumeration
468       to distinguish \hs{Empty} from \hs{Cons}. Furthermore, two more
469       fields would be added: One with the (\VHDL equivalent of) type
470       \hs{t} (assuming this type is actually known at compile time, this
471       should not be a problem) and a second one with type \hs{List t}.
472       The latter one is of course a problem: This is exactly the type
473       that was to be translated in the first place.
474       
475       The resulting \VHDL type will thus become infinitely deep. In
476       other words, there is no way to statically determine how long
477       (deep) the list will be (it could even be infinite).
478       
479       In general, recursive types can never be properly translated: All
480       recursive types have a potentially infinite value (even though in
481       practice they will have a bounded value, there is no way for the
482       compiler to automatically determine an upper bound on its size).
483
484   \subsection{Partial application}
485   Now the translation of application, choice and types has been
486   discussed, a more complex concept can be considered: Partial
487   applications. A \emph{partial application} is any application whose
488   (return) type is (again) a function type.
489
490   From this, it should be clear that the translation rules for full
491   application does not apply to a partial application: There are not
492   enough values for all the input ports in the resulting \VHDL.
493   \in{Example}[ex:Quadruple] shows an example use of partial application
494   and the corresponding architecture.
495
496 \startbuffer[Quadruple]
497 -- | Multiply the input word by four.
498 quadruple :: Word -> Word
499 quadruple n = mul (mul n)
500   where
501     mul = (*) 2
502 \stopbuffer
503
504   \startuseMPgraphic{Quadruple}
505     save in, two, mula, mulb, out;
506
507     % I/O ports
508     newCircle.in(btex $n$ etex) "framed(false)";
509     newCircle.two(btex $2$ etex) "framed(false)";
510     newCircle.out(btex $out$ etex) "framed(false)";
511
512     % Components
513     newCircle.mula(btex $\times$ etex);
514     newCircle.mulb(btex $\times$ etex);
515
516     two.c    = origin;
517     in.c     = two.c + (0cm, 1cm);
518     mula.c  = in.c + (2cm, 0cm);
519     mulb.c  = mula.c + (2cm, 0cm);
520     out.c   = mulb.c + (2cm, 0cm);
521
522     % Draw objects and lines
523     drawObj(in, two, mula, mulb, out);
524
525     nccurve(two)(mula) "angleA(0)", "angleB(45)";
526     nccurve(two)(mulb) "angleA(0)", "angleB(45)";
527     ncline(in)(mula);
528     ncline(mula)(mulb);
529     ncline(mulb)(out);
530   \stopuseMPgraphic
531
532   \placeexample[here][ex:Quadruple]{Simple three port and.}
533     \startcombination[2*1]
534       {\typebufferhs{Quadruple}}{Haskell description using function applications.}
535       {\boxedgraphic{Quadruple}}{The architecture described by the Haskell description.}
536     \stopcombination
537
538   Here, the definition of mul is a partial function application: It applies
539   the function \hs{(*) :: Word -> Word -> Word} to the value \hs{2 :: Word},
540   resulting in the expression \hs{(*) 2 :: Word -> Word}. Since this resulting
541   expression is again a function, hardware cannot be generated for it
542   directly.  This is because the hardware to generate for \hs{mul}
543   depends completely on where and how it is used. In this example, it is
544   even used twice.
545
546   However, it is clear that the above hardware description actually
547   describes valid hardware. In general, any partial applied function
548   must eventually become completely applied, at which point hardware for
549   it can be generated using the rules for function application given in
550   \in{section}[sec:description:application]. It might mean that a
551   partial application is passed around quite a bit (even beyond function
552   boundaries), but eventually, the partial application will become
553   completely applied. An example of this principe is given in
554   \in{section}[sec:normalization:defunctionalization].
555
556   \section{Costless specialization}
557     Each (complete) function application in our description generates a
558     component instantiation, or a specific piece of hardware in the final
559     design. It is interesting to note that each application of a function
560     generates a \emph{separate} piece of hardware. In the final design, none
561     of the hardware is shared between applications, even when the applied
562     function is the same (of course, if a particular value, such as the result
563     of a function application, is used twice, it is not calculated twice).
564
565     This is distinctly different from normal program compilation: Two separate
566     calls to the same function share the same machine code. Having more
567     machine code has implications for speed (due to less efficient caching)
568     and memory usage. For normal compilation, it is therefore important to
569     keep the amount of functions limited and maximize the code sharing
570     (though there is a tradeoff between speed and memory usage here).
571
572     When generating hardware, this is hardly an issue. Having more \quote{code
573     sharing} does reduce the amount of \small{VHDL} output (Since different
574     component instantiations still share the same component), but after
575     synthesis, the amount of hardware generated is not affected. This
576     means there is no tradeoff between speed and memory (or rather,
577     chip area) usage.
578
579     In particular, if we would duplicate all functions so that there is a
580     separate function for every application in the program (\eg, each function
581     is then only applied exactly once), there would be no increase in hardware
582     size whatsoever.
583     
584     Because of this, a common optimization technique called
585     \emph{specialization} can be applied to hardware generation without any
586     performance or area cost (unlike for software). 
587    
588    \fxnote{Perhaps these next three sections are a bit too
589    implementation-oriented?}
590
591     \subsection{Specialization}
592       \defref{specialization}
593       Given some function that has a \emph{domain} $D$ (\eg, the set of
594       all possible arguments that the function could be applied to), we
595       create a specialized function with exactly the same behaviour, but
596       with a domain $D' \subset D$. This subset can be chosen in all
597       sorts of ways. Any subset is valid for the general definition of
598       specialization, but in practice only some of them provide useful
599       optimization opportunities.
600
601       Common subsets include limiting a polymorphic argument to a single type
602       (\ie, removing polymorphism) or limiting an argument to just a single
603       value (\ie, cross-function constant propagation, effectively removing
604       the argument). 
605       
606       Since we limit the argument domain of the specialized function, its
607       definition can often be optimized further (since now more types or even
608       values of arguments are already known). By replacing any application of
609       the function that falls within the reduced domain by an application of
610       the specialized version, the code gets faster (but the code also gets
611       bigger, since we now have two versions instead of one). If we apply
612       this technique often enough, we can often replace all applications of a
613       function by specialized versions, allowing the original function to be
614       removed (in some cases, this can even give a net reduction of the code
615       compared to the non-specialized version).
616
617       Specialization is useful for our hardware descriptions for functions
618       that contain arguments that cannot be translated to hardware directly
619       (polymorphic or higher-order arguments, for example). If we can create
620       specialized functions that remove the argument, or make it translatable,
621       we can use specialization to make the original, untranslatable, function
622       obsolete.
623
624   \section{Higher order values}
625     What holds for partial application, can be easily generalized to any
626     higher-order expression. This includes partial applications, plain
627     variables (e.g., a binder referring to a top level function), lambda
628     expressions and more complex expressions with a function type (a \hs{case}
629     expression returning lambda's, for example).
630
631     Each of these values cannot be directly represented in hardware (just like
632     partial applications). Also, to make them representable, they need to be
633     applied: function variables and partial applications will then eventually
634     become complete applications, applied lambda expressions disappear by
635     applying β-reduction, etc.
636
637     So any higher-order value will be \quote{pushed down} towards its
638     application just like partial applications. Whenever a function boundary
639     needs to be crossed, the called function can be specialized.
640     
641     \fxnote{This section needs improvement and an example}
642
643   \section{Polymorphism}
644     In Haskell, values can be \emph{polymorphic}: They can have multiple types. For
645     example, the function \hs{fst :: (a, b) -> a} is an example of a
646     polymorphic function: It works for tuples with any two element types. Haskell
647     type classes allow a function to work on a specific set of types, but the
648     general idea is the same. The opposite of this is a \emph{monomorphic}
649     value, which has a single, fixed, type.
650
651 %    A type class is a collection of types for which some operations are
652 %    defined. It is thus possible for a value to be polymorphic while having
653 %    any number of \emph{class constraints}: The value is not defined for
654 %    every type, but only for types in the type class. An example of this is
655 %    the \hs{even :: (Integral a) => a -> Bool} function, which can map any
656 %    value of a type that is member of the \hs{Integral} type class 
657
658     When generating hardware, polymorphism cannot be easily translated. How
659     many wires will you lay down for a value that could have any type? When
660     type classes are involved, what hardware components will you lay down for
661     a class method (whose behaviour depends on the type of its arguments)?
662     Note that Cλash currently does not allow user-defined type classes,
663     but does partly support some of the built-in type classes (like \hs{Num}).
664
665     Fortunately, we can again use the principle of specialization: Since every
666     function application generates a separate piece of hardware, we can know
667     the types of all arguments exactly. Provided that existential typing
668     (which is a \GHC extension) is not used typing, all of the
669     polymorphic types in a function must depend on the types of the
670     arguments (In other words, the only way to introduce a type variable
671     is in a lambda abstraction).
672
673     If a function is monomorphic, all values inside it are monomorphic as
674     well, so any function that is applied within the function can only be
675     applied to monomorphic values. The applied functions can then be
676     specialized to work just for these specific types, removing the
677     polymorphism from the applied functions as well.
678
679     \defref{entry function}The entry function must not have a
680     polymorphic type (otherwise no hardware interface could be generated
681     for the entry function).
682
683     By induction, this means that all functions that are (indirectly) called
684     by our top level function (meaning all functions that are translated in
685     the final hardware) become monomorphic.
686
687   \section{State}
688     A very important concept in hardware designs is \emph{state}. In a
689     stateless (or, \emph{combinational}) design, every output is  directly and solely dependent on the
690     inputs. In a stateful design, the outputs can depend on the history of
691     inputs, or the \emph{state}. State is usually stored in \emph{registers},
692     which retain their value during a clockcycle, and are typically updated at
693     the start of every clockcycle. Since the updating of the state is tightly
694     coupled (synchronized) to the clock signal, these state updates are often
695     called \emph{synchronous} behaviour.
696
697     \todo{Sidenote? Registers can contain any (complex) type}
698   
699     To make Cλash useful to describe more than simple combinational
700     designs, it needs to be able to describe state in some way.
701
702     \subsection{Approaches to state}
703       In Haskell, functions are always pure (except when using unsafe
704       functions with the \hs{IO} monad, which is not supported by Cλash). This
705       means that the output of a function solely depends on its inputs. If you
706       evaluate a given function with given inputs, it will always provide the
707       same output.
708
709       \placeintermezzo{}{
710         \defref{purity}
711         \startframedtext[width=8cm,background=box,frame=no]
712         \startalignment[center]
713           {\tfa Purity}
714         \stopalignment
715         \blank[medium]
716
717         A function is said to be pure if it satisfies two conditions:
718
719         \startitemize[KR]
720         \item When a pure function is called with the same arguments twice, it should
721         return the same value in both cases.
722         \item When a pure function is called, it should have not
723         observable side-effects.
724         \stopitemize
725
726         Purity is an important property in functional languages, since
727         it enables all kinds of mathematical reasoning and
728         optimizattions with pure functions, that are not guaranteed to
729         be correct for impure functions.
730
731         An example of a pure function is the square root function
732         \hs{sqrt}. An example of an impure function is the \hs{today}
733         function that returns the current date (which of course cannot
734         exist like this in Haskell).
735         \stopframedtext
736       }
737
738       This is a perfect match for a combinational circuit, where the output
739       also solely depends on the inputs. However, when state is involved, this
740       no longer holds. Of course this purity constraint cannot just be
741       removed from Haskell. But even when designing a completely new (hardware
742       description) language, it does not seem to be a good idea to
743       remove this purity. This would that all kinds of interesting properties of
744       the functional language get lost, and all kinds of transformations
745       and optimizations are no longer be meaning preserving.
746
747       So our functions must remain pure, meaning the current state has
748       to be present in the function's arguments in some way. There seem
749       to be two obvious ways to do this: Adding the current state as an
750       argument, or including the full history of each argument.
751
752       \subsubsection{Stream arguments and results}
753         Including the entire history of each input (\eg, the value of that
754         input for each previous clockcycle) is an obvious way to make outputs
755         depend on all previous input. This is easily done by making every
756         input a list instead of a single value, containing all previous values
757         as well as the current value.
758
759         An obvious downside of this solution is that on each cycle, all the
760         previous cycles must be resimulated to obtain the current state. To do
761         this, it might be needed to have a recursive helper function as well,
762         which might be hard to be properly analyzed by the compiler.
763
764         A slight variation on this approach is one taken by some of the other
765         functional \small{HDL}s in the field: \todo{References to Lava,
766         ForSyDe, ...} Make functions operate on complete streams. This means
767         that a function is no longer called on every cycle, but just once. It
768         takes stream as inputs instead of values, where each stream contains
769         all the values for every clockcycle since system start. This is easily
770         modeled using an (infinite) list, with one element for each clock
771         cycle. Since the function is only evaluated once, its output must also
772         be a stream. Note that, since we are working with infinite lists and
773         still want to be able to simulate the system cycle-by-cycle, this
774         relies heavily on the lazy semantics of Haskell.
775
776         Since our inputs and outputs are streams, all other (intermediate)
777         values must be streams. All of our primitive operators (\eg, addition,
778         substraction, bitwise operations, etc.) must operate on streams as
779         well (note that changing a single-element operation to a stream
780         operation can done with \hs{map}, \hs{zipwith}, etc.).
781
782         This also means that primitive operations from an existing
783         language such as Haskell cannot be used directly (including some
784         syntax constructs, like \hs{case} expressions and \hs{if}
785         expressions).  This mkes this approach well suited for use in
786         \small{EDSL}s, since those already impose these same
787         limitations. \refdef{EDSL}
788
789         Note that the concept of \emph{state} is no more than having some way
790         to communicate a value from one cycle to the next. By introducing a
791         \hs{delay} function, we can do exactly that: Delay (each value in) a
792         stream so that we can "look into" the past. This \hs{delay} function
793         simply outputs a stream where each value is the same as the input
794         value, but shifted one cycle. This causes a \quote{gap} at the
795         beginning of the stream: What is the value of the delay output in the
796         first cycle? For this, the \hs{delay} function has a second input
797         (which is a value, not a stream!).
798
799         \in{Example}[ex:DelayAcc] shows a simple accumulator expressed in this
800         style.
801
802 \startbuffer[DelayAcc]
803 acc :: Stream Word -> Stream Word
804 acc in = out
805   where
806     out = (delay out 0) + in
807 \stopbuffer
808
809 \startuseMPgraphic{DelayAcc}
810   save in, out, add, reg;
811
812   % I/O ports
813   newCircle.in(btex $in$ etex) "framed(false)";
814   newCircle.out(btex $out$ etex) "framed(false)";
815
816   % Components
817   newReg.reg("") "dx(4mm)", "dy(6mm)", "reflect(true)";
818   newCircle.add(btex + etex);
819   
820   in.c    = origin;
821   add.c   = in.c + (2cm, 0cm);
822   out.c   = add.c + (2cm, 0cm);
823   reg.c   = add.c + (0cm, 2cm);
824
825   % Draw objects and lines
826   drawObj(in, out, add, reg);
827
828   nccurve(add)(reg) "angleA(0)", "angleB(180)", "posB(d)";
829   nccurve(reg)(add) "angleA(180)", "angleB(-45)", "posA(out)";
830   ncline(in)(add);
831   ncline(add)(out);
832 \stopuseMPgraphic
833
834
835         \placeexample[here][ex:DelayAcc]{Simple accumulator architecture.}
836           \startcombination[2*1]
837             {\typebufferhs{DelayAcc}}{Haskell description using streams.}
838             {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
839           \stopcombination
840
841
842         This notation can be confusing (especially due to the loop in the
843         definition of out), but is essentially easy to interpret. There is a
844         single call to delay, resulting in a circuit with a single register,
845         whose input is connected to \hs{out} (which is the output of the
846         adder), and its output is the expression \hs{delay out 0} (which is
847         connected to one of the adder inputs).
848
849       \subsubsection{Explicit state arguments and results}
850         A more explicit way to model state, is to simply add an extra argument
851         containing the current state value. This allows an output to depend on
852         both the inputs as well as the current state while keeping the
853         function pure (letting the result depend only on the arguments), since
854         the current state is now an argument.
855
856         In Haskell, this would look like
857         \in{example}[ex:ExplicitAcc]\footnote[notfinalsyntax]{This
858         example is not in the final Cλash syntax}. \todo{Referencing
859         notfinalsyntax from Introduction.tex doesn't work}
860
861 \startbuffer[ExplicitAcc]
862 -- input -> current state -> (new state, output)
863 acc :: Word -> Word -> (Word, Word)
864 acc in s = (s', out)
865   where
866     out = s + in
867     s'  = out
868 \stopbuffer
869
870         \placeexample[here][ex:ExplicitAcc]{Simple accumulator architecture.}
871           \startcombination[2*1]
872             {\typebufferhs{ExplicitAcc}}{Haskell description using explicit state arguments.}
873             % Picture is identical to the one we had just now.
874             {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
875           \stopcombination
876
877         This approach makes a function's state very explicit, which state
878         variables are used by a function can be completely determined from its
879         type signature (as opposed to the stream approach, where a function
880         looks the same from the outside, regardless of what state variables it
881         uses or whether it is stateful at all).
882         
883         This approach to state has been one of the initial drives behind
884         this research. Unlike a stream based approach it is well suited
885         to completely use existing code and language features (like
886         \hs{if} and \hs{case} expressions) because it operates on normal
887         values. Because of these reasons, this is the approach chosen
888         for Cλash. It will be examined more closely below.
889
890     \subsection{Explicit state specification}
891       The concept of explicit state has been introduced with some
892       examples above, but what are the implications of this approach?
893
894       \subsubsection{Substates}
895         Since a function's state is reflected directly in its type signature,
896         if a function calls other stateful functions (\eg, has subcircuits), it
897         has to somehow know the current state for these called functions. The
898         only way to do this, is to put these \emph{substates} inside the
899         caller's state. This means that a function's state is the sum of the
900         states of all functions it calls, and its own state. This sum
901         can be obtained using something simple like a tuple, or possibly
902         custom algebraic types for clarity.
903
904         This also means that the type of a function (at least the "state"
905         part) is dependent on its own implementation and of the functions it
906         calls.
907
908         This is the major downside of this approach: The separation between
909         interface and implementation is limited. However, since Cλash is not
910         very suitable for separate compilation (see
911         \in{section}[sec:prototype:separate]) this is not a big problem in
912         practice.
913
914         Additionally, when using a type synonym for the state type
915         of each function, we can still provide explicit type signatures
916         while keeping the state specification for a function near its
917         definition only.
918         \todo{Example}
919     
920       \subsubsection{Which arguments and results are stateful?}
921         \fxnote{This section should get some examples}
922         We need some way to know which arguments should become input ports and
923         which argument(s?) should become the current state (\eg, be bound to
924         the register outputs). This does not hold just for the top
925         level function, but also for any subfunction. Or could we perhaps
926         deduce the statefulness of subfunctions by analyzing the flow of data
927         in the calling functions?
928
929         To explore this matter, the following observeration is interesting: We
930         get completely correct behaviour when we put all state registers in
931         the top level entity (or even outside of it). All of the state
932         arguments and results on subfunctions are treated as normal input and
933         output ports. Effectively, a stateful function results in a stateless
934         hardware component that has one of its input ports connected to the
935         output of a register and one of its output ports connected to the
936         input of the same register.
937
938         \todo{Example}
939
940         Of course, even though the hardware described like this has the
941         correct behaviour, unless the layout tool does smart optimizations,
942         there will be a lot of extra wire in the design (since registers will
943         not be close to the component that uses them). Also, when working with
944         the generated \small{VHDL} code, there will be a lot of extra ports
945         just to pass on state values, which can get quite confusing.
946
947         To fix this, we can simply \quote{push} the registers down into the
948         subcircuits. When we see a register that is connected directly to a
949         subcircuit, we remove the corresponding input and output port and put
950         the register inside the subcircuit instead. This is slightly less
951         trivial when looking at the Haskell code instead of the resulting
952         circuit, but the idea is still the same.
953
954         \todo{Example}
955
956         However, when applying this technique, we might push registers down
957         too far. When you intend to store a result of a stateless subfunction
958         in the caller's state and pass the current value of that state
959         variable to that same function, the register might get pushed down too
960         far. It is impossible to distinguish this case from similar code where
961         the called function is in fact stateful. From this we can conclude
962         that we have to either:
963
964         \todo{Example of wrong downpushing}
965
966         \startitemize
967         \item accept that the generated hardware might not be exactly what we
968         intended, in some specific cases. In most cases, the hardware will be
969         what we intended.
970         \item explicitly annotate state arguments and results in the input
971         description.
972         \stopitemize
973
974         The first option causes (non-obvious) exceptions in the language
975         intepretation. Also, automatically determining where registers should
976         end up is easier to implement correctly with explicit annotations, so
977         for these reasons we will look at how this annotations could work.
978
979         \todo{Sidenote: One or more state arguments?}
980
981     \subsection[sec:description:stateann]{Explicit state annotation}
982       To make our stateful descriptions unambigious and easier to translate,
983       we need some way for the developer to describe which arguments and
984       results are intended to become stateful.
985     
986       Roughly, we have two ways to achieve this:
987       \startitemize[KR]
988         \item Use some kind of annotation method or syntactic construction in
989         the language to indicate exactly which argument and (part of the)
990         result is stateful. This means that the annotation lives
991         \quote{outside} of the function, it is completely invisible when
992         looking at the function body.
993         \item Use some kind of annotation on the type level, \ie give stateful
994         arguments and stateful (parts of) results a different type. This has the
995         potential to make this annotation visible inside the function as well,
996         such that when looking at a value inside the function body you can
997         tell if it is stateful by looking at its type. This could possibly make
998         the translation process a lot easier, since less analysis of the
999         program flow might be required.
1000       \stopitemize
1001
1002       From these approaches, the type level \quote{annotations} have been
1003       implemented in Cλash. \in{Section}[sec:prototype:statetype] expands on
1004       the possible ways this could have been implemented.
1005
1006   \todo{Note about conditions on state variables and checking them}
1007
1008   \section[sec:recursion]{Recursion}
1009   An important concept in functional languages is recursion. In its most basic
1010   form, recursion is a definition that is described in terms of itself. A
1011   recursive function is thus a function that uses itself in its body. This
1012   usually requires multiple evaluations of this function, with changing
1013   arguments, until eventually an evaluation of the function no longer requires
1014   itself.
1015
1016   Given the notion that each function application will translate to a
1017   component instantiation, we are presented with a problem. A recursive
1018   function would translate to a component that contains itself. Or, more
1019   precisely, that contains an instance of itself. This instance would again
1020   contain an instance of itself, and again, into infinity. This is obviously a
1021   problem for generating hardware.
1022
1023   This is expected for functions that describe infinite recursion. In that
1024   case, we cannot generate hardware that shows correct behaviour in a single
1025   cycle (at best, we could generate hardware that needs an infinite number of
1026   cycles to complete).
1027   
1028   However, most recursive definitions will describe finite
1029   recursion. This is because the recursive call is done conditionally. There
1030   is usually a \hs{case} expression where at least one alternative does not contain
1031   the recursive call, which we call the "base case". If, for each call to the
1032   recursive function, we would be able to detect at compile time which
1033   alternative applies, we would be able to remove the \hs{case} expression and
1034   leave only the base case when it applies. This will ensure that expanding
1035   the recursive functions will terminate after a bounded number of expansions.
1036
1037   This does imply the extra requirement that the base case is detectable at
1038   compile time. In particular, this means that the decision between the base
1039   case and the recursive case must not depend on runtime data.
1040
1041   \subsection{List recursion}
1042   The most common deciding factor in recursion is the length of a list that is
1043   passed in as an argument. Since we represent lists as vectors that encode
1044   the length in the vector type, it seems easy to determine the base case. We
1045   can simply look at the argument type for this. However, it turns out that
1046   this is rather non-trivial to write down in Haskell already, not even
1047   looking at translation. As an example, we would like to write down something
1048   like this:
1049  
1050   \starthaskell
1051     sum :: Vector n Word -> Word
1052     sum xs = case null xs of
1053       True -> 0
1054       False -> head xs + sum (tail xs)
1055   \stophaskell
1056
1057   However, the Haskell typechecker will now use the following reasoning.
1058   For simplicity, the element type of a vector is left out, all vectors
1059   are assumed to have the same element type. Below, we write conditions
1060   on type variables before the \hs{=>} operator. This is not completely
1061   valid Haskell syntax, but serves to illustrate the typechecker
1062   reasoning. Also note that a vector can never have a negative length,
1063   so \hs{Vector n} implicitly means \hs{(n >= 0) => Vector n}.
1064
1065   \todo{This typechecker disregards the type signature}
1066   \startitemize
1067   \item tail has the type \hs{(n > 0) => Vector n -> Vector (n - 1)}
1068   \item This means that xs must have the type \hs{(n > 0) => Vector n}
1069   \item This means that sum must have the type \hs{(n > 0) => Vector n -> a}
1070   \item sum is called with the result of tail as an argument, which has the
1071   type \hs{Vector n} (since \hs{(n > 0) => Vector (n - 1)} is the same as \hs{(n >= 0)
1072   => Vector n}, which is the same as just \hs{Vector n}).
1073   \item This means that sum must have the type \hs{Vector n -> a}
1074   \item This is a contradiction between the type deduced from the body of sum
1075   (the input vector must be non-empty) and the use of sum (the input vector
1076   could have any length).
1077   \stopitemize
1078
1079   As you can see, using a simple \hs{case} expression  at value level causes
1080   the type checker to always typecheck both alternatives, which cannot be
1081   done. The typechecker is unable to distinguish the two case
1082   alternatives (this is partly possible using \small{GADT}s, but that
1083   approach faced other problems \todo{ref christiaan?}).
1084
1085   This is a fundamental problem, that would seem perfectly suited for a
1086   type class.  Considering that we need to switch between to
1087   implementations of the sum function, based on the type of the
1088   argument, this sounds like the perfect problem to solve with a type
1089   class. However, this approach has its own problems (not the least of
1090   them that you need to define a new type class for every recursive
1091   function you want to define).
1092
1093   \todo{This should reference Christiaan}
1094
1095   \subsection{General recursion}
1096   Of course there are other forms of recursion, that do not depend on the
1097   length (and thus type) of a list. For example, simple recursion using a
1098   counter could be expressed, but only translated to hardware for a fixed
1099   number of iterations. Also, this would require extensive support for compile
1100   time simplification (constant propagation) and compile time evaluation
1101   (evaluation of constant comparisons), to ensure non-termination.
1102   Supporting general recursion will probably require strict conditions
1103   on the input descriptions. Even then, it will be hard (if not
1104   impossible) to really guarantee termination, since the user (or \GHC
1105   desugarer) might use some obscure notation that results in a corner
1106   case of the simplifier that is not caught and thus non-termination.
1107
1108   Evaluating all possible (and non-possible) ways to add recursion to
1109   our descriptions, it seems better to limit the scope of this research
1110   to exclude recursion. This allows for focusing on other interesting
1111   areas instead. By including (built-in) support for a number of
1112   higher-order functions like \hs{map} and \hs{fold}, we can still
1113   express most of the things we would use (list) recursion for.
1114   
1115
1116 % vim: set sw=2 sts=2 expandtab: