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