-
Notifications
You must be signed in to change notification settings - Fork 144
/
chisel-book.tex
7922 lines (6121 loc) · 353 KB
/
chisel-book.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[%draft,
10pt,
headinclude, footexclude,
% twoside, % this produces strange margins!
openright, % for new chapters
notitlepage,
cleardoubleempty,
headsepline,
pointlessnumbers,
bibtotoc, idxtotoc,
]{scrbook}
% iPad Air 2 resolution: 1536 x 2048
% 1.3333 ratio (4:3)
% LeeSeshia is 15,73 ? 20,96 cm, ratio 1.332
%\setlength{\paperwidth}{15.73cm} \setlength{\paperheight}{20.96cm}
\setlength{\paperwidth}{15.72cm} \setlength{\paperheight}{20.95cm}
%\typearea{calc} % without BCOR results to a DIV of 8 for 11pt
\typearea[1.1cm]{15} % used 18, but 15 gives more space for the binding, TODO: check if 1.1 cm is the correct number
\usepackage{scrlayer-scrpage}
\setkomafont{pagehead}{\scshape\small}
\setkomafont{pagenumber}{\scshape\small}
\newif\ifbook
%\booktrue % comment out for the print book version
\ifbook
\else
\ifoot{\hyperlink{contents}{{\textnormal{Contents}}}}
\cfoot{\hyperlink{index}{{\textnormal{Index}}}}
\fi
\usepackage{pslatex} % -- times instead of computer modern, especially for the plain article class
\usepackage[pdftex,
pdfauthor={Martin Schoeberl},
pdftitle={Digital Design with Chisel},
colorlinks=true,bookmarks=true]{hyperref}
\usepackage{booktabs}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{multirow}
\usepackage{cite}
\usepackage{dirtree}
\usepackage{pdfpages}
\usepackage{makeidx}
%\usepackage{showidx} % for index debugging
% For alignment on tables
\usepackage{dcolumn}
\newcommand{\cc}[1]{\multicolumn{1}{c}{#1}}
\usepackage{tikz}
\usetikzlibrary{arrows,bending}
\usetikzlibrary{positioning}
% fatter TT font
\renewcommand*\ttdefault{txtt}
% another TT, suggested by Alex
% \usepackage{inconsolata}
% \usepackage[T1]{fontenc} % needed as well?
% Smaller verbatim text
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@verbatim}
{\verbatim@font}
{\verbatim@font\small}
{}{}
\makeatother
\usepackage[procnames]{listings}
\ifbook
\hypersetup{
linkcolor = black,
citecolor = black,
urlcolor = black,
colorlinks = black,
bookmarks=false,
}
\else
\hypersetup{
linkcolor = blue,
citecolor = blue,
urlcolor = blue,
colorlinks = true,
bookmarks=true,
pdfpagemode=UseOutlines,
}
\fi
\makeindex
% not really used
\newenvironment{comment}
{ \vspace{-0.1in}
\begin{quotation}
\noindent
\small \em
\rule{\linewidth}{0.5pt}\\
}
{
\\
\rule{\linewidth}{0.5pt}
\end{quotation}
}
\newcommand{\scale}{0.7}
\input{shared/chisel.tex}
\newcommand{\code}[1]{{\lstinline[basicstyle=\small\ttfamily]{#1}}}
\newcommand{\codefoot}[1]{{\lstinline[basicstyle=\footnotesize\ttfamily]{#1}}}
\newcommand{\todo}[1]{{\emph{TODO: #1}}}
\newcommand{\martin}[1]{{\color{blue} Martin: #1}}
\newcommand{\myref}[2]{\href{#1}{#2}}
\ifbook
\renewcommand{\myref}[2]{{#2}{\footnote{\url{#1}}}}
\fi
% uncomment following for final submission
%\renewcommand{\todo}[1]{}
%\renewcommand{\martin}[1]{}
\makeindex
\begin{document}
\ifbook
\else
\includepdf{chisel-cover.pdf}
\newpage
\thispagestyle{empty}
~
\newpage
\fi
\begin{flushleft}
\pagestyle{empty}
\ \\
\vspace{1cm}
{\usekomafont{title}\mdseries\huge Digital Design with Chisel}
\ \\
\vspace{1cm}
{\usekomafont{title}\mdseries\Large Sixth Edition}
\cleardoublepage
\end{flushleft}
\newpage
\begin{flushleft}
\pagestyle{empty}
\ \\
\vspace{1cm}
{\usekomafont{title}\Huge Digital Design with Chisel\\
\bigskip
{\usekomafont{title}\huge Sixth Edition}\\
\bigskip
\bigskip
\bigskip
\bigskip
%{\large\itshape Beta Edition}\\
\bigskip
{\usekomafont{title}\huge Martin Schoeberl}
\medskip\\
%{\large\itshape [email protected]}
}
%\vspace{10cm} \emph{Version: \today}
\newpage
\end{flushleft}
\thispagestyle{empty}
\begin{flushleft}
{\small
%\lowertitleback{
Copyright \copyright{} 2016--2024 Martin Schoeberl
\medskip\\
\begin{tabular}{lp{.8\textwidth}}
\raisebox{-12pt}{\includegraphics[height=18pt]{figures/cc_by_sa}} &
This work is licensed under a Creative Commons Attribution-ShareAlike
4.0 International License.
\url{http://creativecommons.org/licenses/by-sa/4.0/}\\
\end{tabular}
%}
\medskip
Email: \url{[email protected]}\\
Visit the source at \url{https://github.com/schoeberl/chisel-book}
\medskip
First edition published 2019 by Kindle Direct Publishing,\\
\url{https://kdp.amazon.com/}
\medskip
\medskip
\textbf{Library of Congress Cataloging-in-Publication Data}
\medskip
Schoeberl, Martin
\begin{quote}
Digital Design with Chisel\\
Martin Schoeberl\\
Includes bibliographical references and an index.\\
ISBN 9781689336031
\end{quote}
\bigskip
Manufactured in the United States of America.
Typeset by Martin Schoeberl.}
\end{flushleft}
\frontmatter
\phantomsection
\hypertarget{contents}{}
\tableofcontents
\begingroup
\let\cleardoublepage\clearpage
\listoffigures
\listoftables
\lstlistoflistings
\endgroup
\chapter{Foreword}
\medskip
\medskip
It is an exciting time to be in the world of digital design. With the end of Dennard Scaling and the slowing of Moore's Law, there has perhaps never been a greater need for innovation in the field. Semiconductor companies continue to squeeze out every drop of performance they can, but the cost of these improvements has been rising drastically. Chisel reduces this cost by improving productivity. If designers can build more in less time, while amortizing the cost of verification through reuse, companies can spend less on Non-Recurring Engineering (NRE). In addition, both students and individual contributors can innovate more easily on their own.
Chisel is unlike most languages in that it is embedded in another programming language, Scala. Fundamentally, Chisel is a library of classes and functions representing the primitives necessary to express synchronous, digital circuits. A Chisel design is really a Scala program that \emph{generates} a circuit as it executes. To many, this may seem counterintuitive: ``Why not just make Chisel a stand-alone language like VHDL or SystemVerilog?'' My answer to this question is as follows: the software world has seen a substantial amount of innovation in design methodology in the past couple of decades. Rather than attempting to adapt these techniques to a new hardware language, we can simply \emph{use} a modern programming language and gain those benefits for free.
A longstanding criticism of Chisel is that it is ``difficult to learn.'' Much of this perception is due to the prevalence of large, complex designs created by experts to solve their own research or commercial needs. When learning a popular language like C++, one does not start by reading the source code of GCC. Rather, there are a plethora of courses, textbooks, and other learning materials that cater toward newcomers. In \emph{Digital Design with Chisel}, Martin has created an important resource for anyone who wishes to learn Chisel.
Martin is an experienced educator, and it shows in the organization of this book. Starting with installation and primitives, he builds the reader's understanding like a building, brick-by-brick. The included exercises are the mortar that solidifies understanding, ensuring that each concept sets in the reader's mind. The book culminates with \emph{hardware generators} like a roof giving the rest of the structure purpose. At the end, the reader is left with the knowledge to build a simple, yet useful design: a RISC processor.
In \emph{Digital Design with Chisel}, Martin has laid a strong foundation for productive digital design. What you build with it is up to you.
\medskip
\noindent Jack Koenig\\
Chisel and FIRRTL Maintainer\\
Staff Engineer, SiFive
\chapter{Preface}
% This text goes on the backside of the book, and in Amazon description
This book is an introduction to digital design with a focus on using the hardware construction language Chisel. Chisel brings advances from software engineering, such as object-orientated and functional languages, into digital design.
This book addresses hardware designers and software engineers. Hardware designers with knowledge of Verilog or VHDL can upgrade their productivity with a modern language for their next ASIC or FPGA design. Software engineers with knowledge of object-oriented and functional programming can leverage their knowledge to program hardware, for example, FPGA accelerators executing in the cloud.
The approach of this book is to present small to medium-sized typical hardware components to explore digital design with Chisel.
% about me, backside
%Martin Schoeberl is Associate Professor at the Technical University of Denmark, where he is teaching digital electronics and computer architecture. His research interest is on hard real-time systems, time-predictable computer architecture, and real-time Java. He has more than 100 publications in peer reviewed journals, conferences, and books.
%Martin has been four times at UC Berkeley on research stays, where he has picked up Chisel and was in close contact with the developers of Chisel. He lead the research project T-CREST where most of the components have been written in Chisel.
\section*{Foreword for the Second Edition}
As Chisel allows agile hardware design, so does open access and on-demand printing
allow agile textbook publishing. Less than 6 months after the first edition of this book
I am able to provide an improved and extended second edition.
Besides minor fixes, the main changes in the second edition are as follows.
The testing section has been extended. The sequential building blocks chapter contains
more example circuits. A new chapter on input processing explains input synchronization,
shows how to design a debouncing circuit, and how to filter a noisy input signal.
The example designs chapter has been extended to show different implementations of a FIFO.
The FIFO variations also show how to use type parameters and inheritance in digital design.
\section*{Foreword for the Third Edition}
Chisel has been moving forward in the last year, so it is time for a new edition of the Chisel book.
We changed all examples to the latest version of Chisel (3.5.3), and the recommended
Scala version (2.12.13).
With Chisel 3.5 the testing environment \code{PeekPokeTester} as part of the \code{iotesters}
package has been deprecated. Therefore, we have changed the testing description to the new
\myref{https://github.com/ucb-bar/chiseltest}{ChiselTest} framework.
As there are still many Chisel designs available that use the \code{PeekPokeTester},
we have moved the description for it into the appendix.
One of the fascinating aspects of the Chisel/Scala/Java environment is that we
can piggyback on the available infrastructure to distribute open-source libraries.
We can publish hardware components on Maven as simply as any other open-source Java library.
Publishing on Maven means that a 3rd party component can be integrated into the
compile flow with a single reference in the \code{build.sbt} configuration.
This is the same process as how you include the chisel library for your design.
We have added a section on how to publish a Chisel design on Maven Central.
We have improved the explanation of components with a simpler example.
Hardware \emph{generators} are written in Scala. Therefore, we have added a short
section on Scala. We have extended the hardware generator chapter with a section
on using functional programming to write generators.
The appendix has been extended with a list of reserved keywords and a list
of acronyms.
Hans Jakob Damsgaard has contributed the description of how to use external components, through Chisel's \code{BlackBox}, and how to use memories for clock domain crossing
(multi-clock memories).
\section*{Foreword for the Fourth Edition}
For the fourth edition, we have switched to the actual Chisel version 3.5.4.
We have added arbiter, priority encoder, and comparator to the chapter of
combinational building blocks.
We have extended the hardware generation chapter with more functional
examples, including building a fair arbitration tree out of a simple 2 to 1
arbitration circuits.
We have added a new chapter on interconnect, bus interfaces,
and how to connect an IO device as a memory-mapped device.
We have started a new chapter on debugging, testing, and verification.
The plan is to extend the chapter on this important topic in the next edition.
We have extended the processor chapter with a more gentle introduction
to a microprocessor, including a figure of the datapath.
\section*{Foreword for the Fifth Edition}
For the fifth edition, we have upgraded to the actual Chisel version 3.5.6 and Scala 2.13.
To make room for more advanced topics, I have removed the two appendicitis on
Chisel 2 and the PeekPokeTester. All projects that are actively maintained have finally
moved to Chisel 3, at least with the compatibility layer. The PeekPokeTester has been
deprecated with Chisel 3.5 and it is recommended to switch to ChiselTest.
If needed, those two chapters are available in the older versions of the Chisel book,
available as PDF at the \myref{https://www.imm.dtu.dk/~masca/chisel-book.html}{web page} for this book.
The fifth edition does not include major changes; it is a consolidation version.
We did considerable proofreading for more clarity in writing. Chisel has added small convenience
features (e.g., \code{ChiselEnum}) that we cover in this edition.
We extended the processor chapter and updated the Leros code snippets
to the actual version of Leros.
\section*{Foreword for the Sixth Edition}
Chisel has recently gone through some major changes. Up to Chisel 3.x, Chisel is mainly
based on Scala, which means it runs on the Java virtual machine and is platform independent.
After 3.x Chisel the architecture of the Chisel compile pipeline has changed. To indicate that change,
the version numbering system has change to increment that major version number more often.
Version 4.0 is skipped and the next Chisel version is 5.0.
From version 5.0 the compiler backend is based on \myref{https://circt.llvm.org/}{CIRCT},
a circuit compiler, which is part of the \myref{https://llvm.org/}{LLVM} project.
The main difference for the Chisel user is that CIRCT (and LLVM) are written in C++
and therefore need a different executable for each operating system (processor
architecture).
We tested the book with following Chisel Versions: 3.5.6, 3.6.1, 5.3.0, and 6.5.0.
Chisel 3.6 is the last that uses the Scala based backend to produce Verilog files.
Chisel 5 is using CIRCT and needs \code{firtool} installed.
The latest version of Chisel 6 includes the \code{firtool} binaries.
Testing with ChiselTest is still supported until Chisel 6.
Chisel 6 might switch to a different simulation and testing library.
We use Scala 2.13 and tested with Java 17.
Note that Java 21 is currently not supported by \code{sbt}.
\todo{Check above on JVMs.}
\todo{Some of this might go into getting started.}
\todo{We should also show more Leros code.}
\todo{VHDL and Verilog}
We extended the testing chapter with a description how to access internal signals. \todo{That is too
little to be mentioned here. More is needed.}
Assertions and Chisel formal (if finished).
\section*{Translations}
This book has been translated to Chinese, Japanese, and Vietnamese. All translations are available as free PDF
from the books \myref{https://www.imm.dtu.dk/~masca/chisel-book.html}{web page}.
I would like to thank Yuda Wang, Qiwei Sun, and Yun Chen for the Chinese translation;
Seiji Munetoh, Masatoshi Tanabata, and Takaaki Hagino for the Japanese translation;
and VieLe Duc Hung for the Vietnamese translation.
If you are interested to translate this book into another language, feel free to do it and
publish it under the same license. Please contact me then, so I can point to your translation.
\section*{Acknowledgements}
I want to thank everyone who has worked on Chisel for creating such
a cool hardware construction language. Chisel is so joyful to use and
therefore worth writing a book about.
I am thankful to the whole Chisel community, which is so welcoming and friendly
and never tired to answer questions on Chisel.
I would also like to thank my students in the last years of an advanced computer
architecture course where most of them picked up Chisel for the final project.
Thank you for moving out of your comfort zone and taking up the journey of
learning and using a bleeding-edge hardware description language.
Many of your questions have helped to shape this book.
It was a pleasure to use Chisel in teaching a digital electronics
course at the Technical University of Denmark since 2020.
I know it is a challenge to pickup Chisel and Java in parallel in the second
semester. Thank you to all students from this course, who had on open mind to
pickup a modern programming language for hardware description.
For the third edition, I would like to acknowledge Hans Jakob Damsgaard
(\myref{https://github.com/hansemandse}{@hansemandse}) for rewriting
all test code of this book to ChiselTest, adding ChiselTest to the testing chapter, adding the black
box description, and an example for a multi-clock memory.
\mainmatter
\chapter{Introduction}
\label{sec:intro}
This book is an introduction to digital system design using a modern hardware
construction language, \myref{https://www.chisel-lang.org/}{Chisel}~\cite{chisel:dac2012}.
In this book, we focus on a higher abstraction level than usual in digital design books,
to enable you to build more complex, interacting digital systems in a shorter time.
This book and Chisel are targeting two groups of developers:
(1) hardware designers and (2) software programmers.
Hardware designers who are fluent in VHDL or Verilog and using other languages such as Python,
Java, or Tcl to generate hardware can move to a single hardware construction language
where hardware generation is part of the language.
Software programmers may become interested in hardware design,
e.g., as future chips from Intel will include programmable hardware to speed up programs.
It is perfectly fine to use Chisel as your first hardware description language.
Chisel brings advances in software engineering, such as object-orientated
and functional programming, into the digital design domain.
Chisel does not only allow to express hardware at the register-transfer level
but allows you to write hardware \emph{generators}.
Hardware is now commonly described with a hardware description language.
The time of drawing hardware components, even with CAD tools, is
over. Some high-level schematics can give an overview of the system but are
not intended to describe the system.
The two most common hardware description languages are Verilog and VHDL.
Both languages are old, contain many legacies, and have a moving line of what
constructs of the language are synthesizable to hardware.
Do not get me wrong: VHDL and Verilog are perfectly able to describe a hardware
block that can be synthesized into an
\myref{https://en.wikipedia.org/wiki/Application-specific_integrated_circuit}{ASIC}.
For hardware design in Chisel, Verilog serves as an intermediate language
for testing and synthesis.
This book is not a general introduction to digital design and the fundamentals of it.
For an introduction of the basics in digital design, such as how to build a gate out of
CMOS transistors, refer to other digital design books.
However, this book intends to teach digital design at an abstraction level that is
current practice to describe ASICs or designs targeting
\myref{https://en.wikipedia.org/wiki/Field-programmable_gate_array}{FPGA}s.\footnote{As the author is more familiar with FPGAs
than ASICs as target technology, some design optimizations shown in this book are
targeting FPGA technology.}
As prerequisites for this book, we assume basic knowledge of
\myref{https://en.wikipedia.org/wiki/Boolean_algebra}{Boolean algebra} and the
\myref{https://en.wikipedia.org/wiki/Binary_number}{binary number system}.
Furthermore, some programming experience in any programming language
is assumed. No knowledge of Verilog or VHDL is needed.
Chisel can be your first programming language to describe digital hardware.
As the build process of the examples is based on \code{sbt} and \code{make},
basic knowledge of the command-line interface (CLI, also called terminal or
Unix shell) will be helpful.
Chisel itself is not a big language. The basic constructs fit on
\myref{https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf}{one page}
and can be learned within a few days.
Therefore, this book is not a big book, as well.
Chisel is for sure smaller than VHDL and Verilog, which carry many legacies.
The power of Chisel comes from the embedding of Chisel within
\myref{https://www.scala-lang.org/}{Scala}, which itself is an expressive language.
Chisel inherits the feature from Scala of being ``a language that grows on you''~\cite{Scala}.
However, Scala is not the topic of this book.
We provide a short section on Scala for hardware designers.
The textbook by Odersky et al.~\cite{Scala} provides a general introduction
to Scala.
This book is a tutorial in digital design and the Chisel language; it is not
a Chisel language reference, nor is it a book on complete chip design.
All code examples shown in this book are extracted from complete programs
that have been compiled and tested. Therefore, the code shall not contain
any syntax errors. The code examples are available from the
\myref{https://github.com/schoeberl/chisel-book}{GitHub repository}
of this book.
Besides showing Chisel code, we have also tried to show useful designs and
principles of good hardware description style.
This book is optimized for reading on a tablet (e.g., an iPad) or a laptop.
We include links to further reading in the running text, mostly to
\myref{https://en.wikipedia.org/}{Wikipedia} articles.
\section{Installing Chisel and FPGA Tools}
Chisel is a Scala library, and the easiest way to install Chisel and Scala is
with \code{sbt}, the Scala build tool. Scala itself depends on the installation
of \myref{https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html}{Java JDK 8}
(or a later version, but less than version 21, as 21 breaks \code{sbt}).
As Oracle has changed the license for Java, it may be easier to
install OpenJDK from \myref{https://adoptopenjdk.net/}{AdoptOpenJDK}.
More detailed setup instructions can be found in
\myref{https://github.com/schoeberl/chisel-lab/blob/master/Setup.md}{Setup.md}
from the \myref{https://github.com/schoeberl/chisel-lab}{chisel-lab}.
The \myref{https://github.com/schoeberl/chisel-lab/tree/master/lab1}{first lab}
explains how to open an existing Chisel project in IntelliJ.
\subsection{macOS}
Install the Java OpenJDK 8 (or later, but less then 21) from \myref{https://adoptopenjdk.net/}{AdoptOpenJDK}.
On Mac OS X, with the packet manager \myref{https://brew.sh/}{Homebrew},
\code{sbt} and git can be installed with:
\begin{verbatim}
$ brew install sbt git
\end{verbatim}
Install \myref{http://gtkwave.sourceforge.net/}{GTKWave} and
\myref{https://www.jetbrains.com/idea/download/}{IntelliJ} (the community edition).
When importing a project, select the JDK you installed before.
\subsection{Linux/Ubuntu}
Install Java and useful tools in Ubuntu with:
\begin{verbatim}
$ sudo apt install openjdk-8-jdk git make gtkwave
\end{verbatim}
For Ubuntu, which is based on Debian, programs are usually installed from a
Debian file (.deb). However, as of the time of this writing, \code{sbt} is not
available as a ready to install package. Therefore, the installation process
is a little bit more involved.
Follow the instructions from \myref{https://www.scala-sbt.org/download.html}{sbt download}
\subsection{Windows}
Install the Java OpenJDK (8 or 11) from \myref{https://adoptopenjdk.net/}{AdoptOpenJDK}.
Chisel and Scala can also be installed and used under Windows.
Install \myref{http://gtkwave.sourceforge.net/}{GTKWave} and
\myref{https://www.jetbrains.com/idea/download/}{IntelliJ} (the community edition).
When importing a project, select the JDK you installed before.
\code{sbt} can be installed with a Windows installer, see:
\myref{https://www.scala-sbt.org/1.x/docs/Installing-sbt-on-Windows.html}{Installing sbt on Windows}.
Install a \myref{https://git-scm.com/download/win}{git client}.
\subsection{FPGA Tools}
To build hardware for an FPGA, you need a synthesize tool. The two major
FPGA vendors, Altera, an Intel Company\footnote{former Intel and former Altera}
and AMD,\footnote{former Xilinx} provide free versions of
their tools that cover small to medium-sized FPGAs. Those medium-sized
FPGAs are large enough to build a multicore RISC style processors.
Intel provides the \myref{https://www.altera.com/products/design-software/fpga-design/quartus-prime/download.html}{Quartus Prime Lite Edition} and Xilinx the
\myref{https://www.xilinx.com/products/design-tools/vivado/vivado-webpack.html}{Vivado Design Suite, WebPACK Edition}.
Both tools are available for Windows and Linux, but not for macOS.
With \myref{https://f4pga.org/}{F4PGA} it is now possible to use a fully open-source synthesis tool
for selected FPGAs.
\section{Hello World}
Each book on a programming language shall start with a minimal example,
called the \emph{Hello World} example. The following code is a first approach:
\shortlist{code/hello_scala.txt}
\noindent Compiling and executing this short program with \code{sbt}
\begin{chisel}
$ sbt run
\end{chisel}
\noindent leads to the expected output of a Hello World program:
\begin{chisel}
[info] Running HelloScala
Hello Chisel World!
\end{chisel}
\noindent However, is this Chisel? Is this hardware generated to print a string?
No, this is plain Scala code and not a representative Hello World
program for a hardware design.
\section{Chisel Hello World}
What is then the equivalent of a Hello World program for a hardware design?
The minimal useful and visible design? A blinking LED is the hardware (or even
embedded software) version of Hello World. If a LED blinks, we are ready to
solve bigger problems!
\longlist{code/hello.txt}{A hardware Hello World in Chisel}{lst:chisel:hello}
%\index{Hello World} The index on this page does not work, it references to a intro
% page. Strange!
Listing~\ref{lst:chisel:hello} shows a blinking LED, described in Chisel.
It is not important that you understand the details of this code example.
We will cover those in the following chapters. Just note that the circuit is
usually clocked with a high frequency, e.g., 50~MHz, and we need a counter
to derive timing in the Hz range to achieve a visible blinking. In the above
example, we count from 0 up to 25000000-1 and then toggle the blinking signal
(\code{blkReg := ~blkReg}) and restart the counter (\code{cntReg := 0.U}).
That hardware then blinks the LED at 1~Hz.
\section{An IDE for Chisel}
This book makes no assumptions about your programming environment or editor you use.
Learning the basics should be easy with just using \code{sbt} at the command line
and an editor of your choice. In the tradition of other books, all commands that you
shall type in a shell/terminal/CLI are preceded by a \code{\$} character, which you
shall not type in. As an example, here is the Unix \code{ls} command, which lists files in
the current folder:
\begin{verbatim}
$ ls
\end{verbatim}
That said, an integrated development environment (IDE), where a compiler is running in
the background, can speed up coding. As Chisel is a Scala library, all IDEs
that support Scala are also good IDEs for Chisel.
It is possible in
\myref{https://www.jetbrains.com/help/idea/discover-intellij-idea-for-scala.html}{IntelliJ} and
\myref{https://www.eclipse.org/}{Eclipse}
to generate a project from the sbt project configuration in \code{build.sbt}.
In IntelliJ you need to install the Scala plugin. Then you can create a new project from existing sources with:
\emph{File - New - Project from Existing Sources...} and then select the \code{build.sbt}
file from the project.
In Eclipse you can create a project via
\begin{verbatim}
$ sbt eclipse
\end{verbatim}
and import that project into Eclipse.\footnote{This function needs the Eclipse plugin for sbt.}
\myref{https://code.visualstudio.com/}{Visual Studio Code} is another option for a Chisel IDE.
The \myref{https://marketplace.visualstudio.com/items?itemName=scalameta.metals}{Scala Metals}
extension provides Scala support.
On the left bar select \emph{Extensions} and search for \emph{Metals} and install \emph{Scala (Metals)}.
To import an \code{sbt}-based project, open the folder with \emph{File - Open}.
%Open the project folder, e.g., t-crest/patmos/hardware, by selecting File/Open Folder. Make sure the sbt project uses at least Scala version 2.11.12
%On the left bar select "Metals" and then select "Import build" - This may take a while
%That's it. However, running and debugging the project still doesn't work.
\section{Source Access and eBook Features}
This book is open source and hosted at GitHub: \myref{https://github.com/schoeberl/chisel-book}{schoeberl/chisel-book}.
All Chisel code examples, shown in this book, are included in the repository.
All code shown in the book passed the compiler and therefore should not contain any syntax errors.
Furthermore, most examples also include a test bench.
The code is extracted automatically from that source.
\index{Chisel!Examples}
We collect larger Chisel examples in the accompanying repository
\myref{https://github.com/schoeberl/chisel-examples}{chisel-examples}
and in \myref{https://github.com/freechipsproject/ip-contributions}{ip-contributions}.
If you find an error or typo in the book, a GitHub pull request is the most convenient way to incorporate your improvement.
You can also provide feedback or comments for improvements by filing an issue on GitHub
or sending a plain, old school email.
The repository of the book also contains
\myref{https://github.com/schoeberl/chisel-book/tree/master/slides}{slides in Latex}
that I use for a 13 week course on
\myref{http://www2.imm.dtu.dk/courses/02139/}{Digital Electronics}\footnote{The course page
contains the PDF versions of the slides} at the Technical University of Denmark.
That course also contains \myref{https://github.com/schoeberl/chisel-lab}{lab exercises}
in Chisel.
If you are teaching digital design with Chisel, feel free to adapt the slides and lab
exercises to your needs. All material is open-source. To build the book and slides
you need a recent version of Latex and the needed tools for Chisel (\code{sbt} and
a Java JDK installation). All code is compiled, tested, extracted, and the Latex compiled with
a simple:
\begin{chisel}
$ make
\end{chisel}
This book is freely available as a PDF eBook and in classical printed version from
\myref{https://www.amazon.com/dp/168933603X/}{Amazon}.
The eBook version features links to further resources
and \myref{https://www.wikipedia.org/}{Wikipedia} entries.
We use Wikipedia entries for background information (e.g., binary number system)
that does not directly fit into this book.
We optimized the format of the eBook for reading on a tablet, such as an iPad.
\section{Further Reading}
Here a list of further reading for digital design and Chisel:
\begin{itemize}
\item \myref{http://www.cambridge.org/es/academic/subjects/engineering/circuits-and-systems/digital-design-systems-approach}{Digital Design: A Systems Approach}, by William J. Dally and R. Curtis Harting,
is a textbook on digital design. It is available in two versions: using Verilog or VHDL as a hardware description language.
\end{itemize}
The official Chisel documentation and further documents are available online:
\begin{itemize}
\item The \myref{https://www.chisel-lang.org/}{Chisel} home page is the official starting point to
download and learn Chisel.
\item The website of the \myref{http://www2.imm.dtu.dk/courses/02139/}{Digital Electronics 2} course
at the Technical University of Denmark contains the slides for a 13 weeks course, based on Chisel.
The source code for the \myref{https://github.com/schoeberl/chisel-book/tree/master/slides}{slides}
is available as part of the source code for this book. Feel free to adapt them for your teaching needs.
\item The \myref{https://github.com/schoeberl/chisel-lab}{schoeberl/chisel-lab} GitHub repo
contains Chisel exercises for the course \myref{http://www2.imm.dtu.dk/courses/02139/}{Digital Electronics 2}.
The exercises also fit well for a selfstudy with this book.
\item The \myref{https://github.com/schoeberl/chisel-empty}{empty Chisel project} is a good starting
point with a very minimal hardware (an adder) and a test. That project is a GitHub template where you
can base your GitHub repository on.
\item The \myref{https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf}{Chisel3 Cheat Sheet} summarizes the main constructs of Chisel on a single page.
\item Scott Beamer's course \myref{https://classes.soe.ucsc.edu/cse228a/Winter24/}{Agile Hardware Design}
contains advanced Chisel examples. The \myref{https://github.com/agile-hw/lectures}{lectures}
include executable source examples and are available as Jupyter notebooks.
%\item The \myref{https://github.com/freechipsproject/chisel3/wiki}{Chisel Wiki} contains
%a short users guide to Chisel and links to further information.
\item \myref{https://github.com/ucb-bar/chiseltest}{ChiselTest} is in
its own repository.
\item The \myref{https://github.com/freechipsproject/chisel-bootcamp}{Generator Bootcamp} is
a Chisel course focusing on hardware generators, as a \myref{https://jupyter.org/}{Jupyter} notebook
\item The \myref{https://github.com/ucb-bar/chisel-tutorial}{Chisel Tutorial} provides a ready setup
project containing small exercises with testers and solutions. However, it is a bit outdated.
\item A \myref{https://github.com/ccelio/chisel-style-guide}{Chisel Style Guide} by Christopher Celio.
\end{itemize}
\section{Exercises}
Each chapter ends with a hands-on exercises. For the introduction exercise, we will use an
FPGA board to get one \myref{https://en.wikipedia.org/wiki/Light-emitting_diode}{LED}
blinking.\footnote{If you at the moment have no FPGA board available, continue to read
as we will show you a simulation version at the end of the exercise.}
As a first step clone (or fork) the \myref{https://github.com/schoeberl/chisel-examples}{chisel-examples}
repository from GitHub.
The Hello World example is in the folder \code{hello-world}, set up as
a minimal project. You can explore the Chisel code of the blinking LED
in \code{src/main/scala/Hello.scala}.
Compile the blinking LED with the following steps:
\begin{verbatim}
$ git clone https://github.com/schoeberl/chisel-examples.git
$ cd chisel-examples/hello-world/
$ sbt run
\end{verbatim}
After some initial downloading of Chisel components, this will produce the Verilog file \code{Hello.v}.
Explore this Verilog file. You will see that it contains two inputs \code{clock} and \code{reset}
and one output \code{io\_led}. When you compare this Verilog file with the Chisel module,
you will notice that the Chisel module does not contain \code{clock} or \code{reset}.
Those signals are implicitly generated, and in most designs, it is convenient not to need to
deal with these low-level details. Chisel provides register components, and those
are connected automatically to \code{clock} and \code{reset} (if needed).
The next step is to set up an FPGA project file for the synthesize tool, assign the pins,
compile\footnote{The real process is more elaborated with following steps: synthesizing the logic,
performing place and route, performing timing analysis, and generating a bitfile.
However, for the purpose of this introduction example we simply call it ``compile''
your code.} the Verilog code, and configure the FPGA with the resulting bitfile.
We cannot provide the details of these steps. Please consult the manual of
your Intel Quartus or AMD Vivado tool.
However, the examples repository contains some ready to use Quartus
projects in folder \code{quartus} for several popular FPGA boards (e.g., DE2-115).
If the repository contains support for your board, start Quartus, open the project,
compile it by pressing the \emph{Play} button, and configure the FPGA board
with the \emph{Programmer} button and one of the LEDs should blink.
{\bf Congratulations! You managed to get your first design in Chisel running in an FPGA!}
If the LED is not blinking, check the status of reset. On the DE2-115 configuration,
the reset input is connected to SW0.
Now change the blinking frequency to a slower or a faster value and
rerun the build process. Blinking frequencies and also blinking patterns
communicate different ``emotions''. For example, a slow blinking LED signals that
everything is ok, a fast blinking LED signals an alarm state.
Explore which frequencies express best those two different emotions.
As a more challenging extension to the exercise, generate the following blinking pattern:
the LED shall be on for 200~ms every second. For this pattern, you might
decouple the change of the LED blinking from the counter reset.
You will need a second constant where you change the state of the
\code{blkReg} register. What kind of emotion does this pattern produce?
Is it alarming or more like a sign-of-live signal?
If you do not (yet) have an FPGA board, you can still run the blinking LED example.
You will use the Chisel simulation. To avoid a too long simulation time change the
clock frequency in the Chisel code from 50000000 to 50000. Execute following
instruction to simulate the blinking LED:
\begin{verbatim}
$ sbt test
\end{verbatim}
This will execute the tester that runs for one million clock cycles.
The blinking frequency depends on the simulation speed, which depends on the
speed of your computer. Therefore, you might need to experiment a little bit
with the assumed clock frequency to see the simulated blinking LED.
\chapter{Basic Components}
In this section, we introduce the basic components for digital design:
combinational circuits and flip-flops.
These essential elements can be combined to build larger, more interesting circuits.
Digital systems, in general, use binary signals, which means a single bit or signal
can only have one of two possible values. These values are often called 0 and 1. However, we
also use following terms: low/high, false/true, and deasserted/asserted.
These terms mean the same two possible values of a binary signal.
\section{Chisel Types and Constants}
Chisel provides three data types to describe connections, combinational logic, and registers:
\code{Bits}, \code{UInt}, and \code{SInt}. \code{UInt} and \code{SInt} extend \code{Bits},
and all three types represent a vector of bits. \code{UInt} gives this vector of
bits the meaning of an unsigned integer and \code{SInt} of a signed
integer.\footnote{The type \codefoot{Bits} in the current version of Chisel is missing operations and
therefore not very useful for user code.}
Chisel uses \myref{https://en.wikipedia.org/wiki/Two\%27s\_complement}{two's complement}
as signed integer representation.
Here is the definition for different types, an 8-bit \code{Bits}, an 8-bit unsigned integer, and a 10-bit
signed integer:
\index{Integer!unsigned}
\index{Integer!signed}
\shortlist{code/types.txt}
\noindent The width of a vector of bits is defined by a Chisel width type (\code{Width}).
The following expression casts the Scala integer \code{n} to a Chisel \code{width},
which we use for the definition of the \code{Bits} vector:
\shortlist{code/n_w.txt}
\index{Integer!width}
\noindent Constants can be defined by using a Scala integer and converting it to a Chisel type:
\shortlist{code/constants.txt}
\index{Integer!constant}
\noindent Constants can also be defined with a width, by using the Chisel width type:
\shortlist{code/const_width.txt}
\noindent If you find the notation of 3.U and 4.W a little bit funny, consider it as a variant of an integer
constant with a type. This notation is similar to 3L, representing a long integer constant in C, Java, and Scala.
{\bf Possible pitfall:} One possible error when defining constants with a dedicated width is missing the \code{.W}
specifier for a width. E.g., \code{1.U(32)} will \emph{not} define a 32-bit wide constant representing 1.
Instead, the expression \code{(32)} is interpreted as bit extraction from position 32, which results
in a single bit constant of 0. Probably not what the original intention of the programmer was.
Chisel benefits from Scala's type inference and in many places type information can be left out.
The same is also valid for bit widths. In many cases, Chisel will automatically infer the correct width.
Therefore, a Chisel description of hardware is more concise and better readable than VHDL or
Verilog.
For constants defined in other bases than decimal, the constant is defined in a string with
a preceding \code{h} for hexadecimal (base 16), \code{o} for octal (base 8), and \code{b}
for binary (base 2). The following example shows the definition of constant 255 in different
bases. In this example we omit the bit width and Chisel infers the minimum width to fit
the constants in, in this case 8 bits.
\shortlist{code/const_base.txt}
\noindent The above code shows how to use an underscore to group digits in the
string that represents a constant. The underscore is ignored.
Characters to represent text (in \myref{https://en.wikipedia.org/wiki/ASCII}{ASCII} encoding)
can also be used as constants in Chisel:
\shortlist{code/const_char.txt}
To represent logic values, Chisel defines the type \code{Bool}.
\code{Bool} can represent a \emph{true} or \emph{false} value.
The following code shows the definition of type \code{Bool} and the definition of
\code{Bool} constants, by converting the Scala Boolean constants \code{true}
and \code{false} to Chisel \code{Bool} constants.
\shortlist{code/bool.txt}
\index{Bool}
\section{Combinational Circuits}
Chisel uses \myref{https://en.wikipedia.org/wiki/Boolean_algebra}{Boolean algebra} operators,
as they are defined in C, Java, Scala, and several other programming languages,
to described combinational circuits: \code{\&} is the AND operator and \code{|} is
the OR operator.
Following line of code defines a circuit that combines signals \code{a} and \code{b} with \emph{and}
gates and combines the result with signal \code{c} with \emph{or} gates and names it \code{logic}.
\shortlist{code/logic.txt}
\begin{figure}
\centering
\includegraphics[scale=\scale]{figures/logic}
\caption{Logic for the expression \code{(a \& b) | c}.
The wires can be a single bit or multiple bits. The Chisel expression, and the schematics are the same.}
\label{fig:logic}
\end{figure}
\noindent Figure~\ref{fig:logic} shows the schematic of this combinatorial expression.
Note that this circuit may be for a vector of bits and not only single wires
that are combined with the AND and OR circuits.
In this example, we do not define the type nor the width of signal \code{logic}.
Both are inferred from the type and width of the expression.
The standard logic operations in Chisel are:
\index{logical operations}
\shortlist{code/bool_ops.txt}
\noindent The arithmetic operations use the standard operators:
\index{arithmetic operations}
\shortlist{code/arith_ops.txt}
\noindent The resulting width of the operation is the maximum width of the operators for
addition and subtraction, the sum of the two widths for the multiplication, and usually
the width of the numerator for divide and modulo operations.\footnote{The exact
details are available in the \myref{https://github.com/chipsalliance/firrtl-spec/releases/latest/download/spec.pdf}{FIRRTL specification}.}
A signal can also first be defined as a \code{Wire} of some type. Afterward, we can assign a
value to the wire with the \code{:=} update operator.
\index{Wire}
\shortlist{code/wire.txt}
A single bit can be extracted as follows:
\shortlist{code/single_bit.txt}
\index{Bit!extraction}
\noindent A subfield can be extracted from end to start position:
\shortlist{code/sub_field.txt}
\noindent Bit fields are concatenated with the \code{\#\#} operator.\footnote{Note that there is a \codefoot{Cat} function available that performs the same
operation with \codefoot{Cat(highByte, lowByte)}.}
\shortlist{code/concat.txt}
\index{Bit!concatenation}
Table~\ref{tab:operators} shows the full list of operators
(see also \myref{https://www.chisel-lang.org/chisel3/docs/explanations/operators.html}{builtin operators}).
The Chisel operator precedence is determined by the evaluation order of the circuit,
which follows the \myref{https://docs.scala-lang.org/tour/operators.html}{Scala operator precedence}.
If in doubt, it is always a good practice to use parentheses.\footnote{The operator precedence in
Chisel is a side effect of the hardware elaboration when the tree of hardware nodes
is created by executing the Scala operators. The Scala operator precedence is similar but
not identical to Java/C. Verilog has the same operator precedence as C, but VHDL
has a different one. Verilog has precedence ordering for logic operations, but in VHDL
those operators have the same precedence and are evaluated from left to right.}
Table~\ref{tab:functions} shows various functions defined on and for Chisel data types.
\begin{table}
\centering
\begin{tabular}{lll}
\toprule
Operator & Description & Data types \\
\midrule