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.
6 When translating Haskell to hardware, we need to make choices in what kind
7 of hardware to generate for what Haskell constructs. When faced with
8 choices, we've tried to stick with the most obvious choice wherever
9 possible. In a lot of cases, when you look at a hardware description it is
10 comletely clear what hardware is described. We want our translator to
11 generate exactly that hardware whenever possible, to minimize the amount of
12 surprise for people working with it.
14 In this chapter we try to describe how we interpret a Haskell program from a
15 hardware perspective. We provide a description of each Haskell language
16 element that needs translation, to provide a clear picture of what is
19 \section{Function application}
20 The basic syntactic element of a functional program are functions and
21 function application. These have a single obvious \small{VHDL} translation: Each
22 function becomes a hardware component, where each argument is an input port
23 and the result value is the output port.
25 Each function application in turn becomes component instantiation. Here, the
26 result of each argument expression is assigned to a signal, which is mapped
27 to the corresponding input port. The output port of the function is also
28 mapped to a signal, which is used as the result of the application.
30 \in{Example}[ex:And3] shows a simple program using only function
31 application and the corresponding architecture.
34 -- | A simple function that returns
35 -- the and of three bits
36 and3 :: Bit -> Bit -> Bit -> Bit
37 and3 a b c = and (and a b) c
40 \startuseMPgraphic{And3}
41 save a, b, c, anda, andb, out;
44 newCircle.a(btex $a$ etex) "framed(false)";
45 newCircle.b(btex $b$ etex) "framed(false)";
46 newCircle.c(btex $c$ etex) "framed(false)";
47 newCircle.out(btex $out$ etex) "framed(false)";
50 newCircle.anda(btex $and$ etex);
51 newCircle.andb(btex $and$ etex);
54 b.c = a.c + (0cm, 1cm);
55 c.c = b.c + (0cm, 1cm);
56 anda.c = midpoint(a.c, b.c) + (2cm, 0cm);
57 andb.c = midpoint(b.c, c.c) + (4cm, 0cm);
59 out.c = andb.c + (2cm, 0cm);
61 % Draw objects and lines
62 drawObj(a, b, c, anda, andb, out);
64 ncarc(a)(anda) "arcangle(-10)";
71 \placeexample[here][ex:And3]{Simple three port and.}
72 \startcombination[2*1]
73 {\typebufferhs{And3}}{Haskell description using function applications.}
74 {\boxedgraphic{And3}}{The architecture described by the Haskell description.}
77 TODO: Define top level function and subfunctions/circuits.
80 Since describing components and connections allows us to describe a lot of
81 hardware designs already, there is an obvious thing missing: Choice. We
82 need some way to be able to choose between values based on another value.
83 In Haskell, choice is achieved by case expressions, if expressions or
84 pattern matching (all of which can be reduced to case expressions).
86 An obvious way to add choice to our language without having to recognize
87 any of Haskell's syntax, would be to add a primivite \quote{\hs{if}}
88 function. This function would take three arguments: The condition, the
89 value to return when the condition is true and the value to return when
90 the condition is false.
92 This \hs{if} function would then essentially describe a multiplexer and
93 allows us to describe any architecture that uses multiplexers. (TODO: Are
94 there other mechanisms of choice in hardware?)
96 However, to be able to describe our hardware in a more convenient way, we
97 also need to translate Haskell's choice mechanisms. The easiest of these
98 are of course case expressions (and if expressions, which can be very
99 directly translated to case expressions). A case expression can in turn
100 simply be translated to a conditional assignment, where the conditions use
101 equality comparisons against the constructors in the case expressions.
103 In \in{example}[ex:CaseInv] a simple case statement is shown,
104 scrutinizing a boolean value. If we would translate a Boolean to a bit
105 value, we could of course remove the comparator and directly feed 'in'
106 into the multiplex (or even use an inverter instead of a multiplexer).
107 However, we will try to make a general translation, which works for all
108 possible case statements. Optimizations such as these are left for the
109 \VHDL synthesizer, which handles them very well.
111 \startbuffer[CaseInv]
118 \startuseMPgraphic{CaseInv}
119 save in, truecmp, falseout, trueout, out, cmp, mux;
122 newCircle.in(btex $in$ etex) "framed(false)";
123 newCircle.out(btex $out$ etex) "framed(false)";
125 newBox.truecmp(btex $True$ etex) "framed(false)";
126 newBox.trueout(btex $True$ etex) "framed(false)";
127 newBox.falseout(btex $False$ etex) "framed(false)";
130 newCircle.cmp(btex $==$ etex);
134 cmp.c = in.c + (3cm, 0cm);
135 truecmp.c = cmp.c + (-1cm, 1cm);
136 mux.sel = cmp.e + (1cm, -1cm);
137 falseout.c = mux.inpa - (2cm, 0cm);
138 trueout.c = mux.inpb - (2cm, 0cm);
139 out.c = mux.out + (2cm, 0cm);
141 % Draw objects and lines
142 drawObj(in, out, truecmp, trueout, falseout, cmp, mux);
146 nccurve(cmp.e)(mux.sel) "angleA(0)", "angleB(-90)";
147 ncline(falseout)(mux) "posB(inpa)";
148 ncline(trueout)(mux) "posB(inpb)";
149 ncline(mux)(out) "posA(out)";
152 \placeexample[here][ex:CaseInv]{Simple inverter.}
153 \startcombination[2*1]
154 {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
155 {\boxedgraphic{CaseInv}}{The architecture described by the Haskell description.}
158 Slightly more complex (but very powerful) forms of choice are pattern
159 matches. A function can be defined in multiple clauses, where each clause
160 specifies a pattern. When the arguments match the pattern, the
161 corresponding clause will be used.
163 \startbuffer[PatternInv]
169 \placeexample[here][ex:PatternInv]{Simple inverter using pattern matching.}
170 {\typebufferhs{CaseInv}}
172 The architecture described in \in{example}[ex:PatternInv] is of course the
173 same one as the one in \in{example}[ex:CaseInv]. The general interpration
174 of pattern matching is also similar to that of case expressions: Generate
175 hardware for each of the clause (like each of the clauses of a case
176 expression) and connect them to the function output through (a number of
177 nested) multiplexers. These multiplexers are driven by comparators and
178 other logic, that check each pattern in turn.
181 Apart from giving structure to our hardware, we'll also need to provide
182 some way to translate the values used to hardware equivalents. In
183 particular, this means having to come up with a hardware equivalent for
184 every \emph{type} used in our program.
186 Since most functional languages have a lot of standard types that are
187 hard to translate (integers without a fixed size, lists without a static
188 length, etc.), we will start out by defining a number of \quote{builtin}
189 types ourselves. These types are builtin in the sense that our compiler
190 will have a fixed VHDL type for these. User defined types, on the other
191 hand, will have their hardware type derived directly from their Haskell
192 declaration automatically, according to the rules we sketch here.
194 \subsection{Builtin types}
196 This is the most basic type available. It is mapped directly onto
197 the \type{std_logic} \small{VHDL} type. Mapping this to the
198 \type{bit} type might make more sense (since the Haskell version
199 only has two values), but using \type{std_logic} is more standard
200 (and allowed for some experimentation with don't care values)
203 This is a builtin Haskell type, but is translated exactly like the
204 Bit type. Supporting the Bool type is particularly useful to support
205 \hs{if ... then ... else ...} expressions, which always have a
206 \hs{Bool} value for the condition.
208 A \hs{Bool} is translated to a \type{std_logic}, just like \hs{Bit}.
210 \startdesc{SizedWord, SizedInt}
211 These are types to represent integers. \hs{SizedWord} is unsigned,
212 while \hs{SizedInt} is signed. These types are parameterized by a
213 length type, so you can define an unsigned word of 32 bits wide as
217 type Word32 = SizedWord D32
220 Here, \hs{D32} is the \emph{type level representation} of the number
221 32. TODO: Introduce dependent types somewhere.
223 These types are translated to the \small{VHDL} \type{unsigned} and
224 \type{signed} respectively.
226 \startdesc{RangedWord}
227 This is another type to describe integers, but unlike the previous
228 two it has no specific width, but an upper bound. This means that
229 its range is not limited to powers of two, but can be any number.
230 A \hs{RangedWord} only has an upper bound, its lower bound is
231 implicitly zero. There is a lot of added implementation complexity
232 when adding a lower bound and having just an upper bound was enough
233 for the primary purpose of this type: Typesafely indexing vectors.
235 This type is translated to the \type{unsigned} \small{VHDL} type.
238 This is a vector type, with a fixed length. It has two type
239 parameters: Its length and the type of the elements contained in it.
241 A fixed size vector is translated to a \small{VHDL} array type.
243 The \hs{TF} in its name is a reference to the implementation used in
244 the prototype, which uses \emph{type families}.
247 TODO: Reference Christiaan / describe dependent typing
248 \subsection{User-defined types}
249 There are three ways to define new types in Haskell: Algebraic
250 datatypes with the \hs{data} keyword, type synonyms with the \hs{type}
251 keyword and type renamings with the \hs{newtype} keyword. This
252 expclitely excludes more advanced type creation from \GHC extensions
253 such as type families, existential typing, \small{GADT}s, etc.
255 The first of these actually introduces a new type, for which we provide
256 the \VHDL translation below. The latter two only define new names for
257 existing types (where synonyms are completely interchangeable and
258 renamings need explicit conversion). Therefore, these don't need any
259 particular \VHDL translation, a synonym or renamed type will just use
260 the same representation as the equivalent type.
262 For algebraic types, we can make the following distinction:
264 \startdesc{Product types}
265 A product type is an algebraic datatype with a single constructor with
266 two or more fields. This is essentially a way to pack a few values
267 together in a record-like structure. In fact, the builtin tuple types
268 are just product types (and are thus supported in exactly the same
271 The "product" in its name refers to the collection of values belonging
272 to this type. The collection for a product type is the cartesic
273 product of the collections for the types of its fields.
275 These types are translated to \VHDL record types, with one field for
276 every field in the constructor. This translation applies to all single
277 constructor algebraic datatypes, including those with no fields (unit
278 types) and just one field (which are technically not a product).
280 \startdesc{Enumerated types}
281 An enumerated type is an algebraic datatype with multiple constructors, but
282 none of them have fields. This is essentially a way to get an
283 enum-like type containing alternatives.
285 Note that Haskell's \hs{Bool} type is also defined as an
286 enumeration type, but we have a fixed translation for that.
288 These types are translated to \VHDL enumerations, with one value for
289 each constructor. This allows references to these constructors to be
290 translated to the corresponding enumeration value.
292 \startdesc{Sum types}
293 A sum type is an algebraic datatype with multiple constructors, where
294 the constructors have one or more fields. Technically, a type with
295 more than one field per constructor is a sum of products type, but
296 for our purposes this distinction does not really make a difference,
297 so we'll leave it out.
299 Sum types are currently not supported by the prototype, since its
300 translation is not so obvious as before. The can easily be emulated,
301 as we will see from an example:
304 data Sum = A Bit Word | B Word
307 An obvious way to translate this would be to create an enumeration to
308 distinguish the constructors and then create a big record that
309 contains all the fields of all the constructors. This is the same
310 translation that would result from the following enumeration and
311 product type (using a tuple for clarity):
315 type Sum = (SumC, Bit, Word, Word)
318 Here, the \hs{SumC} type effectively signals which of the fields of
319 the \hs{Sum} type are valid, all the other ones have no useful value.
321 An obvious problem with this naive approach is the space usage: The
322 example above generates a fairly big \VHDL type. However, we can be
323 sure that the two \hs{Word}s in the \hs{Sum} type will never be valid
324 at the same time, so this is a waste of space.
326 Obviously, we could do some duplication detection here to reuse a
327 particular field for another constructor, but this would only
328 partially solve the problem. If I would, for example, have an array of
329 8 bits and a 8 bit unsiged word, these are different types and could
330 not be shared. However, in the final hardware, both of these types
331 would simply be 8 bit connections, so we have a 100\% size increase by
335 Another interesting case is that of recursive types. In Haskell, an
336 algebraic datatype can be recursive: Any of its field types can be (or
337 contain) the type being defined. The most well-known recursive type is
338 probably the list type, which is defined is:
341 data List a = Empty | Cons a (List a)
344 Where \hs{Empty} is usually written as \hs{[]} and \hs{Cons} as \hs{:}.
345 This immediately shows the problem with recursive types: What hardware
346 type to allocate here? There is no way to statically determine how long
349 In general, we can say we can never properly translated recursive types:
350 All recursive types have a potentially infinite value (even though in
351 practice they will have a bounded value, there is no way for the
352 compiler to determine an upper bound on its size.
354 \subsection{Partial application}
355 It should be obvious that we cannot generate hardware signals for all
356 expressions we can express in Haskell. The most obvious criterium for this
357 is the type of an expression. We will see more of this below, but for now it
358 should be obvious that any expression of a function type cannot be
359 represented as a signal or i/o port to a component.
361 From this, we can see that the above translation rules do not apply to a
362 partial application. \in{Example}[ex:Quadruple] shows an example use of
363 partial application and the corresponding architecture.
365 \startbuffer[Quadruple]
366 -- | Multiply the input word by four.
367 quadruple :: Word -> Word
368 quadruple n = mul (mul n)
373 \startuseMPgraphic{Quadruple}
374 save in, two, mula, mulb, out;
377 newCircle.in(btex $n$ etex) "framed(false)";
378 newCircle.two(btex $2$ etex) "framed(false)";
379 newCircle.out(btex $out$ etex) "framed(false)";
382 newCircle.mula(btex $\times$ etex);
383 newCircle.mulb(btex $\times$ etex);
386 in.c = two.c + (0cm, 1cm);
387 mula.c = in.c + (2cm, 0cm);
388 mulb.c = mula.c + (2cm, 0cm);
389 out.c = mulb.c + (2cm, 0cm);
391 % Draw objects and lines
392 drawObj(in, two, mula, mulb, out);
394 nccurve(two)(mula) "angleA(0)", "angleB(45)";
395 nccurve(two)(mulb) "angleA(0)", "angleB(45)";
401 \placeexample[here][ex:Quadruple]{Simple three port and.}
402 \startcombination[2*1]
403 {\typebufferhs{Quadruple}}{Haskell description using function applications.}
404 {\boxedgraphic{Quadruple}}{The architecture described by the Haskell description.}
407 Here, the definition of mul is a partial function application: It applies
408 \hs{2 :: Word} to the function \hs{(*) :: Word -> Word -> Word} resulting in
409 the expression \hs{(*) 2 :: Word -> Word}. Since this resulting expression
410 is again a function, we can't generate hardware for it directly. This is
411 because the hardware to generate for \hs{mul} depends completely on where
412 and how it is used. In this example, it is even used twice!
414 However, it is clear that the above hardware description actually describes
415 valid hardware. In general, we can see that any partial applied function
416 must eventually become completely applied, at which point we can generate
417 hardware for it using the rules for function application above. It might
418 mean that a partial application is passed around quite a bit (even beyond
419 function boundaries), but eventually, the partial application will become
422 \section{Costless specialization}
423 Each (complete) function application in our description generates a
424 component instantiation, or a specific piece of hardware in the final
425 design. It is interesting to note that each application of a function
426 generates a \emph{separate} piece of hardware. In the final design, none
427 of the hardware is shared between applications, even when the applied
428 function is the same.
430 This is distinctly different from normal program compilation: Two separate
431 calls to the same function share the same machine code. Having more
432 machine code has implications for speed (due to less efficient caching)
433 and memory usage. For normal compilation, it is therefore important to
434 keep the amount of functions limited and maximize the code sharing.
436 When generating hardware, this is hardly an issue. Having more \quote{code
437 sharing} does reduce the amount of \small{VHDL} output (Since different
438 component instantiations still share the same component), but after
439 synthesis, the amount of hardware generated is not affected.
441 In particular, if we would duplicate all functions so that there is a
442 duplicate for every application in the program (\eg, each function is then
443 only applied exactly once), there would be no increase in hardware size
446 TODO: Perhaps these next two sections are a bit too
447 implementation-oriented?
449 \subsection{Specialization}
450 Because of this, a common optimization technique called
451 \emph{specialization} is as good as free for hardware generation. Given
452 some function that has a \emph{domain} of $D$ (\eg, the set of all
453 possible arguments that could be applied), we create a specialized
454 function with exactly the same behaviour, but with an domain of $D'
455 \subset D$. This subset can be derived in all sort of ways, but commonly
456 this is done by limiting a polymorphic argument to a single type (\eg,
457 removing polymorphism) or by limiting an argument to just a single value
458 (\eg, cross-function constant propagation, effectively removing the
461 Since we limit the argument domain of the specialized function, its
462 definition can often be optimized further (since now more types or even
463 values of arguments are already know). By replacing any application of
464 the function that falls within the reduced domain by an application of
465 the specialized version, the code gets faster (but the code also gets
466 bigger, since we now have two versions instead of one!). If we apply
467 this technique often enough, we can often replace all applications of a
468 function by specialized versions, allowing the original function to be
469 removed (in some cases, this can even give a net reduction of the code
470 compared to the non-specialized version).
472 Specialization is useful for our hardware descriptions for functions
473 that contain arguments that cannot be translated to hardware directly
474 (polymorphic or higher order arguments, for example). If we can create
475 specialized functions that remove the argument, or make it translatable,
476 we can use specialization to make the original, untranslatable, function
479 \section{Higher order values}
480 What holds for partial application, can be easily generalized to any
481 higher order expression. This includes partial applications, plain
482 variables (e.g., a binder referring to a top level function), lambda
483 expressions and more complex expressions with a function type (a case
484 expression returning lambda's, for example).
486 Each of these values cannot be directly represented in hardware (just like
487 partial applications). Also, to make them representable, they need to be
488 applied: function variables and partial applications will then eventually
489 become complete applications, applied lambda expressions disappear by
490 applying β-reduction, etc.
492 So any higher order value will be \quote{pushed down} towards its
493 application just like partial applications. Whenever a function boundary
494 needs to be crossed, the called function can be specialized.
496 TODO: This is section should be improved
498 \section{Polymorphism}
499 In Haskell, values can be polymorphic: They can have multiple types. For
500 example, the function \hs{fst :: (a, b) -> a} is an example of a
501 polymorphic function: It works for tuples with any element types. Haskell
502 typeclasses allow a function to work on a specific set of types, but the
503 general idea is the same.
505 % A type class is a collection of types for which some operations are
506 % defined. It is thus possible for a value to be polymorphic while having
507 % any number of \emph{class constraints}: The value is not defined for
508 % every type, but only for types in the type class. An example of this is
509 % the \hs{even :: (Integral a) => a -> Bool} function, which can map any
510 % value of a type that is member of the \hs{Integral} type class
512 When generating hardware, polymorphism can't be easily translated. How
513 many wire will you lay down for a value that could have any type? When
514 type classes are involved, what hardware components will you lay down for
515 a class method (whose behaviour depends on the type of its arguments)?
517 Fortunately, we can again use the principle of specialization: Since every
518 function application generates separate pieces of hardware, we can know
519 the types of all arguments exactly. Provided that we don't use existential
520 typing, all of the polymorphic types in a function must depend on the
521 types of the arguments (In other words, the only way to introduce a type
522 variable is in a lambda abstraction). Our top level function must not have
523 a polymorphic type (otherwise we wouldn't know the hardware interface to
524 our top level function).
526 If a function is monomorphic, all values inside it are monomorphic as
527 well, so any function that is applied within the function can only be
528 applied to monomorphic values. The applied functions can then be
529 specialized to work just for these specific types, removing the
530 polymorphism from the applied functions as well.
532 By induction, this means that all functions that are (indirectly) called
533 by our top level function (meaning all functions that are translated in
534 the final hardware) become monomorphic.
537 A very important concept in hardware designs is \emph{state}. In a
538 stateless (or, \emph{combinatoric}) design, every output is a directly and solely dependent on the
539 inputs. In a stateful design, the outputs can depend on the history of
540 inputs, or the \emph{state}. State is usually stored in \emph{registers},
541 which retain their value during a clockcycle, and are typically updated at
542 the start of every clockcycle. Since the updating of the state is tightly
543 coupled (synchronized) to the clock signal, these state updates are often
544 called \emph{synchronous}.
546 To make our hardware description language useful to describe more that
547 simple combinatoric designs, we'll need to be able to describe state in
550 \subsection{Approaches to state}
551 In Haskell, functions are always pure (except when using unsafe
552 functions like \hs{unsafePerformIO}, which should be prevented whenever
553 possible). This means that the output of a function solely depends on
554 its inputs. If you evaluate a given function with given inputs, it will
555 always provide the same output.
559 This is a perfect match for a combinatoric circuit, where the output
560 also soley depend on the inputs. However, when state is involved, this
561 no longer holds. Since we're in charge of our own language, we could
562 remove this purity constraint and allow a function to return different
563 values depending on the cycle in which it is evaluated (or rather, the
564 current state). However, this means that all kinds of interesting
565 properties of our functional language get lost, and all kinds of
566 transformations and optimizations might no longer be meaning preserving.
568 Provided that we want to keep the function pure, the current state has
569 to be present in the function's arguments in some way. There seem to be
570 two obvious ways to do this: Adding the current state as an argument, or
571 including the full history of each argument.
573 \subsubsection{Stream arguments and results}
574 Including the entire history of each input (\eg, the value of that
575 input for each previous clockcycle) is an obvious way to make outputs
576 depend on all previous input. This is easily done by making every
577 input a list instead of a single value, containing all previous values
578 as well as the current value.
580 An obvious downside of this solution is that on each cycle, all the
581 previous cycles must be resimulated to obtain the current state. To do
582 this, it might be needed to have a recursive helper function as well,
583 wich might be hard to properly analyze by the compiler.
585 A slight variation on this approach is one taken by some of the other
586 functional \small{HDL}s in the field (TODO: References to Lava,
587 ForSyDe, ...): Make functions operate on complete streams. This means
588 that a function is no longer called on every cycle, but just once. It
589 takes stream as inputs instead of values, where each stream contains
590 all the values for every clockcycle since system start. This is easily
591 modeled using an (infinite) list, with one element for each clock
592 cycle. Since the funciton is only evaluated once, its output is also a
593 stream. Note that, since we are working with infinite lists and still
594 want to be able to simulate the system cycle-by-cycle, this relies
595 heavily on the lazy semantics of Haskell.
597 Since our inputs and outputs are streams, all other (intermediate)
598 values must be streams. All of our primitive operators (\eg, addition,
599 substraction, bitwise operations, etc.) must operate on streams as
600 well (note that changing a single-element operation to a stream
601 operation can done with \hs{map}, \hs{zipwith}, etc.).
603 Note that the concept of \emph{state} is no more than having some way
604 to communicate a value from one cycle to the next. By introducing a
605 \hs{delay} function, we can do exactly that: Delay (each value in) a
606 stream so that we can "look into" the past. This \hs{delay} function
607 simply outputs a stream where each value is the same as the input
608 value, but shifted one cycle. This causes a \quote{gap} at the
609 beginning of the stream: What is the value of the delay output in the
610 first cycle? For this, the \hs{delay} function has a second input
611 (which is a value, not a stream!).
613 \in{Example}[ex:DelayAcc] shows a simple accumulator expressed in this
616 \startbuffer[DelayAcc]
617 acc :: Stream Word -> Stream Word
620 out = (delay out 0) + in
623 \startuseMPgraphic{DelayAcc}
624 save in, out, add, reg;
627 newCircle.in(btex $in$ etex) "framed(false)";
628 newCircle.out(btex $out$ etex) "framed(false)";
631 newReg.reg("") "dx(4mm)", "dy(6mm)", "reflect(true)";
632 newCircle.add(btex + etex);
635 add.c = in.c + (2cm, 0cm);
636 out.c = add.c + (2cm, 0cm);
637 reg.c = add.c + (0cm, 2cm);
639 % Draw objects and lines
640 drawObj(in, out, add, reg);
642 nccurve(add)(reg) "angleA(0)", "angleB(180)", "posB(d)";
643 nccurve(reg)(add) "angleA(180)", "angleB(-45)", "posA(out)";
649 \placeexample[here][ex:DelayAcc]{Simple accumulator architecture.}
650 \startcombination[2*1]
651 {\typebufferhs{DelayAcc}}{Haskell description using streams.}
652 {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
656 This notation can be confusing (especially due to the loop in the
657 definition of out), but is essentially easy to interpret. There is a
658 single call to delay, resulting in a circuit with a single register,
659 whose input is connected to \hs{outl (which is the output of the
660 adder)}, and it's output is the \hs{delay out 0} (which is connected
661 to one of the adder inputs).
663 This notation has a number of downsides, amongst which are limited
664 readability and ambiguity in the interpretation. TODO: Reference
667 \subsubsection{Explicit state arguments and results}
668 A more explicit way to model state, is to simply add an extra argument
669 containing the current state value. This allows an output to depend on
670 both the inputs as well as the current state while keeping the
671 function pure (letting the result depend only on the arguments), since
672 the current state is now an argument.
674 In Haskell, this would look like \in{example}[ex:ExplicitAcc].
676 \startbuffer[ExplicitAcc]
677 -- input -> current state -> (new state, output)
678 acc :: Word -> Word -> (Word, Word)
679 acc in (State s) = (State s', out)
685 \placeexample[here][ex:ExplicitAcc]{Simple accumulator architecture.}
686 \startcombination[2*1]
687 {\typebufferhs{ExplicitAcc}}{Haskell description using explicit state arguments.}
688 % Picture is identical to the one we had just now.
689 {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
692 This approach makes a function's state very explicit, which state
693 variables are used by a function can be completely determined from its
694 type signature (as opposed to the stream approach, where a function
695 looks the same from the outside, regardless of what state variables it
696 uses (or wether it's stateful at all).
698 This approach is the one chosen for Cλash and will be examined more
701 \subsection{Explicit state specification}
702 We've seen the concept of explicit state in a simple example below, but
703 what are the implications of this approach?
705 \subsubsection{Substates}
706 Since a function's state is reflected directly in its type signature,
707 if a function calls other stateful functions (\eg, has subcircuits) it
708 has to somehow know the current state for these called functions. The
709 only way to do this, is to put these \emph{substates} inside the
710 caller's state. This means that a function's state is the sum of the
711 states of all functions it calls, and its own state.
713 This also means that the type of a function (at least the "state"
714 part) is dependent on its implementation and the functions it calls.
715 This is the major downside of this approach: The separation between
716 interface and implementation is limited. However, since Cλash is not
717 very suitable for separate compilation (see
718 \in{section}[sec:prototype:separate]) this is not a big problem in
719 practice. Additionally, when using a type synonym for the state type
720 of each function, we can still provide explicit type signatures
721 while keeping the state specification for a function near its
725 We need some way to know which arguments should become input ports and
726 which argument(s?) should become the current state (\eg, be bound to
727 the register outputs). This does not hold holds not just for the top
728 level function, but also for any subfunctions. Or could we perhaps
729 deduce the statefulness of subfunctions by analyzing the flow of data
730 in the calling functions?
732 To explore this matter, we make an interesting observation: We get
733 completely correct behaviour when we put all state registers in the
734 top level entity (or even outside of it). All of the state arguments
735 and results on subfunctions are treated as normal input and output
736 ports. Effectively, a stateful function results in a stateless
737 hardware component that has one of its input ports connected to the
738 output of a register and one of its output ports connected to the
739 input of the same register.
743 Of course, even though the hardware described like this has the
744 correct behaviour, unless the layout tool does smart optimizations,
745 there will be a lot of extra wire in the design (since registers will
746 not be close to the component that uses them). Also, when working with
747 the generated \small{VHDL} code, there will be a lot of extra ports
748 just to pass one state values, which can get quite confusing.
750 To fix this, we can simply \quote{push} the registers down into the
751 subcircuits. When we see a register that is connected directly to a
752 subcircuit, we remove the corresponding input and output port and put
753 the register inside the subcircuit instead. This is slightly less
754 trivial when looking at the Haskell code instead of the resulting
755 circuit, but the idea is still the same.
759 However, when applying this technique, we might push registers down
760 too far. When you intend to store a result of a stateless subfunction
761 in the caller's state and pass the current value of that state
762 variable to that same function, the register might get pushed down too
763 far. It is impossible to distinguish this case from similar code where
764 the called function is in fact stateful. From this we can conclude
765 that we have to either:
768 \item accept that the generated hardware might not be exactly what we
769 intended, in some specific cases. In most cases, the hardware will be
771 \item explicitely annotate state arguments and results in the input
775 The first option causes (non-obvious) exceptions in the language
776 intepretation. Also, automatically determining where registers should
777 end up is easier to implement correctly with explicit annotations, so
778 for these reasons we will look at how this annotations could work.
781 TODO: Note about conditions on state variables and checking them.
783 \subsection{Explicit state annotation}
784 To make our stateful descriptions unambigious and easier to translate,
785 we need some way for the developer to describe which arguments and
786 results are intended to become stateful.
788 Roughly, we have two ways to achieve this:
790 \item Use some kind of annotation method or syntactic construction in
791 the language to indicate exactly which argument and (part of the)
792 result is stateful. This means that the annotation lives
793 \quote{outside} of the function, it is completely invisible when
794 looking at the function body.
795 \item Use some kind of annotation on the type level, \eg give stateful
796 arguments and (part of) results a different type. This has the
797 potential to make this annotation visible inside the function as well,
798 such that when looking at a value inside the function body you can
799 tell if it's stateful by looking at its type. This could possibly make
800 the translation process a lot easier, since less analysis of the
801 program flow might be required.
804 From these approaches, the type level \quote{annotations} have been
805 implemented in Cλash. \in{Section}[sec:prototype:statetype] expands on
806 the possible ways this could have been implemented.
808 TODO: Say something about dependent types and fixed size vectors
810 \section[sec:recursion]{Recursion}
811 An import concept in functional languages is recursion. In it's most basic
812 form, recursion is a function that is defined in terms of itself. This
813 usually requires multiple evaluations of this function, with changing
814 arguments, until eventually an evaluation of the function no longer requires
817 Recursion in a hardware description is a bit of a funny thing. Usually,
818 recursion is associated with a lot of nondeterminism, stack overflows, but
819 also flexibility and expressive power.
821 Given the notion that each function application will translate to a
822 component instantiation, we are presented with a problem. A recursive
823 function would translate to a component that contains itself. Or, more
824 precisely, that contains an instance of itself. This instance would again
825 contain an instance of itself, and again, into infinity. This is obviously a
826 problem for generating hardware.
828 This is expected for functions that describe infinite recursion. In that
829 case, we can't generate hardware that shows correct behaviour in a single
830 cycle (at best, we could generate hardware that needs an infinite number of
833 However, most recursive hardware descriptions will describe finite
834 recursion. This is because the recursive call is done conditionally. There
835 is usually a case statement where at least one alternative does not contain
836 the recursive call, which we call the "base case". If, for each call to the
837 recursive function, we would be able to detect which alternative applies,
838 we would be able to remove the case expression and leave only the base case
839 when it applies. This will ensure that expanding the recursive functions
840 will terminate after a bounded number of expansions.
842 This does imply the extra requirement that the base case is detectable at
843 compile time. In particular, this means that the decision between the base
844 case and the recursive case must not depend on runtime data.
846 \subsection{List recursion}
847 The most common deciding factor in recursion is the length of a list that is
848 passed in as an argument. Since we represent lists as vectors that encode
849 the length in the vector type, it seems easy to determine the base case. We
850 can simply look at the argument type for this. However, it turns out that
851 this is rather non-trivial to write down in Haskell in the first place. As
852 an example, we would like to write down something like this:
855 sum :: Vector n Word -> Word
856 sum xs = case null xs of
858 False -> head xs + sum (tail xs)
861 However, the typechecker will now use the following reasoning (element type
862 of the vector is left out):
865 \item tail has the type \hs{(n > 0) => Vector n -> Vector (n - 1)}
866 \item This means that xs must have the type \hs{(n > 0) => Vector n}
867 \item This means that sum must have the type \hs{(n > 0) => Vector n -> a}
868 \item sum is called with the result of tail as an argument, which has the
869 type \hs{Vector n} (since \hs{(n > 0) => n - 1 == m}).
870 \item This means that sum must have the type \hs{Vector n -> a}
871 \item This is a contradiction between the type deduced from the body of sum
872 (the input vector must be non-empty) and the use of sum (the input vector
873 could have any length).
876 As you can see, using a simple case at value level causes the type checker
877 to always typecheck both alternatives, which can't be done! This is a
878 fundamental problem, that would seem perfectly suited for a type class.
879 Considering that we need to switch between to implementations of the sum
880 function, based on the type of the argument, this sounds like the perfect
881 problem to solve with a type class. However, this approach has its own
882 problems (not the least of them that you need to define a new typeclass for
883 every recursive function you want to define).
885 Another approach tried involved using GADTs to be able to do pattern
886 matching on empty / non empty lists. While this worked partially, it also
887 created problems with more complex expressions.
889 TODO: How much detail should there be here? I can probably refer to
892 Evaluating all possible (and non-possible) ways to add recursion to our
893 descriptions, it seems better to leave out list recursion alltogether. This
894 allows us to focus on other interesting areas instead. By including
895 (builtin) support for a number of higher order functions like map and fold,
896 we can still express most of the things we would use list recursion for.
898 \subsection{General recursion}
899 Of course there are other forms of recursion, that do not depend on the
900 length (and thus type) of a list. For example, simple recursion using a
901 counter could be expressed, but only translated to hardware for a fixed
902 number of iterations. Also, this would require extensive support for compile
903 time simplification (constant propagation) and compile time evaluation
904 (evaluation constant comparisons), to ensure non-termination. Even then, it
905 is hard to really guarantee termination, since the user (or GHC desugarer)
906 might use some obscure notation that results in a corner case of the
907 simplifier that is not caught and thus non-termination.
909 Due to these complications, we leave other forms of recursion as