aboutsummaryrefslogtreecommitdiff
path: root/spec/spec.tex
blob: 75c55d6514d79792ebf2042c3e5fccf26aaaa04a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
%Useful Macros
\newcommand{\id}{\text{id }}
\newcommand{\idst}{\text{id*}}
\newcommand{\ids}{\text{id}}
\newcommand{\ints}{\text{int}}
\newcommand{\intsp}{\text{int }}
\newcommand{\strings}{\text{string}}
\newcommand{\stringsp}{\text{string }}
\newcommand{\kw}[1]{\text{\bf #1\ }}
\newcommand{\kws}[1]{\text{\bf #1}}
\newcommand{\pd}[1]{\text{\em #1\ }}
\newcommand{\pds}[1]{\text{\em #1}}
\newcommand{\bundleT}[1]{\{#1\}}
\newcommand{\info}{[\pds{info}]\ }
\newcommand{\version}{0.1.3}

\title{Specification for the FIRRTL Language:\\ Version \version \\ PRE-RELEASE VERSION - DO NOT DISTRIBUTE}
\author{Patrick S. Li \\ \href{mailto:psli@eecs.berkeley.edu}{psli@eecs.berkeley.edu}
   \and Adam M. Izraelevitz \\ \href{mailto:adamiz@eecs.berkeley.edu}{adamiz@eecs.berkeley.edu} 
   \and Jonathan Bachrach \\ \href{mailto:jrb@eecs.berkeley.edu}{jrb@eecs.berkeley.edu} }
\documentclass[12pt]{article}
\usepackage{listings}
\usepackage{amsmath}
\usepackage{proof}
\usepackage{amsfonts}
\usepackage{enumitem}
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,      
    urlcolor=cyan,
}
\usepackage[pdftex]{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}
\lhead{Specification for the FIRRTL Language}
\rhead{Version \version}
\cfoot{\thepage \\ \em{PRE-RELEASE VERSION - DO NOT DISTRIBUTE}}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}
\lstset{basicstyle=\footnotesize\ttfamily,breaklines=true}

\begin{document}
\maketitle
\tableofcontents
\newpage


\section{Introduction}

\subsection{Background}
The ideas for FIRRTL originated from work on Chisel, a hardware description language embedded in Scala used for writing highly-parameterized circuit design generators. Chisel designers manipulate circuit components using Scala functions, encode their interfaces in Scala types, and use Scala's object-orientation features to write their own circuit libraries. This form of meta-programming enables expressive, reliable and type-safe generators that improve RTL design productivity and robustness.

The computer architecture research at U.C. Berkeley relied critically on Chisel to allow small teams of graduate students to design sophisticated RTL circuits. Over a three year period with under twelve graduate students, the architecture team has taped-out over ten different designs. 

Internally, the investment in developing and learning Chisel was rewarded in huge gains in productivity. However, Chisel's external rate of adoption was slow for the following reasons:
\begin{enumerate}[topsep=3pt,itemsep=-0.5ex,partopsep=1ex,parsep=1ex]
\item Learning a functional programming language (Scala) is difficult for RTL designers with limited software-engineering experience
\item Confounding the previous point, conceptually separating the Chisel HDL from the host language is difficult for new users
\item The output of Chisel (Verilog) is unreadable and slow to simulate
\item Writing custom circuit transformers requires intimate knowledge about the internals of the Chisel compiler
\item Chisel semantics are ill-defined and thus impossible to target from other languages
\item Error checking is unprincipled due to ill-defined semantics resulting in incomprehensible error messages
\end{enumerate}

As a consequence, Chisel needed to be redesigned from the ground up to standardize its semantics, modularize its compilation process for robustness, and cleanly separate its front-end, intermediate representation, and backends. A well defined intermediate representation (IR) allows the system to be targeted by other host programming languages, making it possible for RTL designers to work within a language they are already comfortable with. A clearly defined IR with a concrete syntax also allows inspection of the output of circuit generators/transformers thus making clear the distinction between the host language and the constructed circuit. A clearly defined semantics allows users without knowledge of the compiler implementation to write circuit transformers. Examples include optimization of circuits for simulation speed, and automatic insertion of signal activity counters. An additional benefit of a well defined IR is the structural invariants that can be enforced before and after each compilation stage, resulting in a more robust compiler and structured mechanism for error checking. 

\subsection{Design Philosophy}
FIRRTL (Flexible Intermediate Representation for RTL) represents the standardized elaborated circuit that the Chisel DSL produces. FIRRTL represents the circuit immediately after Chisel's elaboration but before any circuit simplification. It is designed to resemble the Chisel DSL after all meta-programming has executed. Thus a user program that makes little use of meta-programming facilities should look almost indentical to the generated FIRRTL.

For this reason, FIRRTL has first-class support for high-level constructs such as vector types, bundle types, when statements, partial connects, and modules. These high-level constructs are then gradually removed by a sequence of "lowering" transformations. During each lowering transformation the circuit is rewritten into an equivalent circuit using simpler, lower-level constructs. Eventually the circuit is simplified to its most restricted form, resembling a structured netlist, which allows for easy translation to an output language (e.g. Verilog). This form is given the name "lowered FIRRTL" (LoFIRRTL) and is a strict subset of the full FIRRTL language.

Because the host language is now used solely for its meta-programming facilities, the frontend can be very light-weight, and additional frontends in other languages can target FIRRTL and reuse the majority of the compiler toolchain.

Similar to backends, it is often convenient to write transformers that accept only the restricted LoFIRRTL subset. However, the transformed circuit is allowed to contain any FIRRTL construct, as it can be subsequently lowered again. We intentionally designed LoFIRRTL to be a subset of the full FIRRTL language to provide this feature.

\section{Acknowledgements}
The FIRRTL language could not have been developed without the help of many of the faculty and students in the ASPIRE lab, and the University of California, Berkeley.

This project originated from discussions with our advisor, Jonathan Bachrach, who indicated the need for a structural redesign of the Chisel system around a well-defined intermediate representation. Patrick Li designed and implemented the first prototype of the FIRRTL language, wrote the initial specification for the language, and presented it to the Chisel group consisting of Scott Beamer, David Biancolin, Christopher Celio, Henry Cook, Palmer Dabbelt, Donggyu Kim, Jack Koenig, Martin Maas, Albert Magyar, Colin Schmidt, Andrew Waterman, Yunsup Lee, Richard Lin, Eric Love, Albert Ou, Stephen Twigg, Jim Lawson, Brian Richards, Krste Asanovic, and John Wawrzynek.

Adam Izraelevitz then led the design and reimplemented FIRRTL, and after many discussions with the Chisel group, refined the design to its present version.

The authors would like to thank the following individuals for their contributions to the FIRRTL project:
\begin{enumerate}
\item Andrew Waterman: for his many contributions to the design of FIRRTL's constructs, for his work on Chisel 3.0, and for porting architecture research infrastructure
\item Richard Lin: for improving the Chisel 3.0 code base for release quality
\item Jack Koenig: for implementing the FIRRTL parser in Scala
\item Henry Cook: for porting and cleaning up many aspects of Chisel 3.0, including the testing infrastructure and the parameterization library
\item Stephen Twigg: for his expertise in hardware intermediate representations and for providing many corner cases to consider
\item Palmer Dabbelt, Eric Love, Martin Maas, Christopher Celio, and Scott Beamer: for their feedback on previous drafts of the FIRRTL specification
\end{enumerate}

And finally this project would not have been possible without the continuous feedback and encouragement of our advisor, Jonathan Bachrach, and his leadership on and implementation of Chisel 3.0.

Research is partially funded by DARPA Award Number XXXX, the Center for Future Architectures Research, a member of STARnet, a Semiconductor Research Corporation program sponsored by MARCO and DARPA, and ASPIRE Lab industrial sponsors and affiliates Intel, Google, Nokia, NVIDIA, Oracle, and Samsung. Any opinions, findings, conclusions, or recommendations in this paper are solely those of the authors and do not necessarily reflect the position or the policy of the sponsors.

\section{Circuits and Modules}

\subsection{Circuits}
All FIRRTL circuits consist of a list of modules, each representing one hardware block that could be instantiated. The circuit must specify the name of the top-level module.

\begin{verbatim}
circuit MyTop :
   module MyTop :
      ...
   module MyModule :
      ...   
\end{verbatim}   

All module names in a circuit exist in the same namespace, and thus all modules must have a unique name. 

\subsection{Modules}
Each module has a given name, a list of ports, and a statement representing the circuit connections within the module. A module port is specified by its \pd{direction}, which may be input or output, a name, and the data type for the port. The port names exist in the module identifier namespace, and must be unique.

\begin{verbatim}
module MyModule :
   input foo: UInt
   output bar: UInt
   bar <= foo
\end{verbatim}  

Note that a module definition does {\em not} indicate that the module will be physically present in the final circuit. Refer to the description of the instance statement for details on how to instantiate a module (section \ref{XXX}).

\subsection{Externally Defined Modules}
Externally defined modules consist of a given name, and a list of ports, whose types and names must match its external definition.

\begin{verbatim}
module MyExternalModule :
   input foo: UInt
   output bar: UInt
   output baz: SInt
\end{verbatim}  


% The following example is the port declaration of a module that spans two clock domains.

% \[
% \begin{aligned}
% &\kw{module} TwoClock : \\
% &\quad \kw{input} clk1 : \kw{Clock}\\
% &\quad \kw{input} clk2 : \kw{Clock}\\
% &\quad ... \\
% \end{aligned}
% \]

\section{Types}

\subsection{Ground Types}

All types in FIRRTL are either one of the fundamental ground types or are built up from aggregating other types. There are three ground types in FIRRTL, an unsigned integer type, a signed integer type, and a clock type.

\subsubsection{Integer Types}

Both unsigned and signed integer types may optionally be given a known positive integer bit width.

\begin{verbatim}
UInt<10>
SInt<32>
\end{verbatim}  

Alternatively, if the bit width is omitted, it will be automatically inferred by FIRRTL's width inferencer, as detailed in section \ref{XXX}.

\begin{verbatim}
UInt
SInt
\end{verbatim}  

\subsubsection{Clock Type}

The clock type is used to describe wires and ports meant for carrying clock signals. The usage of components with clock types are restricted. Clock signals cannot be used in most primitive operations, and clock signals can only be connected to components that have been declared with the clock type. 

The clock type is specified as follows:
\begin{verbatim}
Clock
\end{verbatim}  

\subsection{Vector Types}

A vector type is used to express an ordered sequence of elements of a given type. The length of the sequence must be non-negative and known. This is akin to array types in the C programming language.

The following example specifies a ten element vector of 16-bit unsigned integers.
\begin{verbatim}
UInt<16>[10]
\end{verbatim}  

The next example specifies a ten element vector of unsigned integers of omitted but identical bit widths.
\begin{verbatim}
UInt[10]
\end{verbatim}

Note that any type, including other aggregate types, may be used as the element type in the sequence. The following example specifies a twenty element vector, each of which is a ten element vector of 16-bit unsigned integers.
\begin{verbatim}
UInt<16>[10][20]
\end{verbatim} 

\subsection{Bundle Types}

A bundle type is used to express a collection of nested and named types. All fields in a bundle type must have a given name, and type. 

The following is an example of a possible type for representing a complex number. It has two fields, \verb|real|, and \verb|imag|, both 10-bit signed integers.
\begin{verbatim}
{real:SInt<10>, imag:SInt<10>}
\end{verbatim}

Additionally, a field may optionally be declared with a {\em flipped} orientation.
\begin{verbatim}
{word:UInt<32>, valid:UInt<1>, flip ready:UInt<1>}
\end{verbatim}
In a connection between elements declared with the same bundle type, the data carried by the flipped fields flow in the opposite direction as the data carried by the non-flipped fields.

As an example, consider a module output port declared with the following type:
\begin{verbatim}
output mysignal: {word:UInt<32>, valid:UInt<1>, flip ready:UInt<1>}
\end{verbatim}
In a connection to the \verb|mysignal| port, the data carried by the \verb|word| and \verb|valid| subfields will flow out of the module, while data carried by the \verb|ready| subfield will flow into the module. More details about how the bundle field orientation affects connections are explained in section \ref{XXX}.

As in the case of vector types, a bundle field may be declared with any type, including other aggregate types. 
\begin{verbatim}
{real: {word:UInt<32>, valid:UInt<1>, flip ready:UInt<1>}
 imag: {word:UInt<32>, valid:UInt<1>, flip ready:UInt<1>}}
\end{verbatim}

When calculating the final direction of data flow, the orientation of a field is applied recursively to all nested types in the field. As an example, consider the following module port declared with a bundle type containing a nested bundle type.
\begin{verbatim}
output myport: {a: UInt, flip b: {c: UInt, flip d:UInt}}
\end{verbatim}
In a connection to \verb|myport|, the \verb|a| subfield flows out of the module. The \verb|c| subfield contained in the \verb|b| subfield flows into the module, and the \verb|d| subfield contained in the \verb|b| subfield flows out of the module.

Note that within a bundle, all field names must be unique.

\subsection{Passive Types}

Intuitively, a passive type is defined as a type where all leaf elements have a non-flipped orientation. Thus all ground types are passive types. Vector types are passive if their element type is passive. And bundle types are passive if no fields are flipped and if all field types are passive.

\subsection{Type Equivalence}

The type equivalence relation is used to determine whether a connection between two elements is legal. See section \ref{XXX} for further details about connect statements.

An unsigned integer type is always equivalent to another unsigned integer type regardless of bit width, and is not equivalent to any other type. Similarly, a signed integer type is always equivalent to another signed integer type regardless of bit width, and is not equivalent to any other type. 

Clock types are only equivalent to clock types, and are not equivalent to any other type.

Two vector types are equivalent if they have the same length, and if their element types are equivalent.

Two bundle types are equivalent when they have the same number of fields, and the i'th field from each bundle have matching names and orientations, as well as equivalent types. Consequently, \verb|{a:UInt, b:UInt}| is a different type than \verb|{b:UInt, a:UInt}|. \verb|{a: {flip b:UInt}}| is a different type than \verb|{flip a: {b: UInt}}|.

\subsection{Weak Type Equivalence}

The weak type equivalence relation is used to determine whether a partial connection between two elements is legal. See section \ref{XXX} for further details about partial connect statements.

Two types are weakly equivalent if their corresponding oriented types are equivalent.

\subsubsection{Oriented Types}
The weak type equivalence relation requires first a definition of {\em oriented types}. Intuitively, an oriented type is a type where all orientation information is collated and coupled with the leaf ground types instead of in bundle fields.

An oriented ground type is an orientation coupled with a ground type. An oriented vector type is an ordered sequence of elements of a given oriented type. The length of an oriented vector type must be known and positive. An oriented bundle type is a collection of fields containing a name and an oriented type, but no orientation.

Applying a flip orientation to an oriented type recursively reverses the orientation of every oriented ground type contained within. Applying a non-flip orientation to an oriented type does nothing.

\subsubsection{Conversion to Oriented Types}
To convert a ground type to an oriented ground type, attach a non-flip orientation to the ground type. 

To convert a vector type to an oriented vector type, convert its element type to an oriented type, and retain its length. 

To convert a bundle field to an oriented bundle field, first convert its type to an oriented type. Then apply the field orientation to the oriented type, returning a new oriented type. The new oriented type, and the original field's name combine to create the oriented bundle field. To convert a bundle type to an oriented bundle type, convert each bundle field to an oriented bundle field.

\subsubsection{Oriented Type Equivalence}
Two oriented ground types are equivalent if their orientations and types are equivalent.

Two oriented vector types are equivalent if their element types are equivalent.

Two oriented bundle types are not equivalent if there exists two fields, one from each oriented bundle type, that have identical names but whose oriented types are not equivalent. Otherwise, the oriented bundle types are equivalent.

As stated earlier, two types are weakly equivalent if their corresponding oriented types are equivalent.


\section{Statements} \label{statements}

Statements are used to instantiate and connect circuit elements together.

\subsection{The Connect Statement}
The connect statement is used to specify a physically wired connection between two circuit elements.

The following example demonstrates connecting a module's input port to its output port, where port \verb|myinput| is connected to port \verb|myoutput|.
\begin{verbatim}
module MyModule :
   input myinput: UInt
   output myoutput: UInt
   myoutput <= myinput
\end{verbatim}

In order for a connection to be legal the following conditions must hold:
\begin{enumerate}
\item The types of the left-hand and right-hand side expressions must be equivalent (see section \ref{XXX} for details).
\item The bit widths of the two expressions must allow for data to always flow from a smaller to equal size or larger bit width.
\item The gender of the left-hand side expression must be female or bi-gender (see section \ref{XXX} for an explanation of gender).
\item Either the gender of the right-hand side expression is male or bi-gender, or the right-hand side expression has a passive type.
\end{enumerate}

Connect statements from a narrower ground type element to a wider ground type element will have its value automatically sign-extended to the larger bit width. 

\subsubsection{The Connection Algorithm}
Connect statements between ground types cannot be expanded further. 

Connect statements between two vector typed elements recursively connects each subelement in the right-hand side expression to the corresponding subelement in the left-hand side expression. 

Connect statements between two bundle typed elements connects the i'th field of the right-hand side expression and the i'th field of the left-hand side expression. If the i'th field is not flipped, then the right-hand side field is connected to the left-hand side field. Conversely, if the i'th field is flipped, then the left-hand side field is connected to the right-hand side field.


\subsection{The Partial Connect Statement}
The partial connect statement is also used to specify a physically wired connection between two circuit elements. However, it enforces fewer restrictions on the types and widths of the circuit elements it connects. 

In order for a partial connect to be legal the following conditions must hold:
\begin{enumerate}
\item The types of the left-hand and right-hand side expressions must be weakly equivalent (see section \ref{XXX} for details).
\item The gender of the left-hand side expression must be female or bi-gender (see section \ref{XXX} for an explanation of gender).
\item Either the gender of the right-hand side expression is male or bi-gender, or the right-hand side expression has a passive type.
\end{enumerate}

Partial connect statements from a narrower ground type element to a wider ground type element will have its value automatically sign-extended to the larger bit width. Partial connect statements from a wider ground type element to a narrower ground type element will have its value automatically truncated to fit the smaller bit width. 

Intuitively, bundle fields with matching names will be connected appropriately, while bundle fields not present in both types will be ignored. Similarly, vectors with mismatched lengths will be connected up to the shorter length, and the remaining elements are ignored.

The following example demonstrates partially connecting a module's input port to its output port, where port \verb|myinput| is connected to port \verb|myoutput|.
\begin{verbatim}
module MyModule :
   input myinput: {flip a:UInt, b:UInt[2]}
   output myoutput: {flip a:UInt, b:UInt[3], c:UInt}
   myoutput <- myinput
\end{verbatim}

The above example is equivalent to the following:
\begin{verbatim}
module MyModule :
   input myinput: {flip a:UInt, b:UInt[2]}
   output myoutput: {flip a:UInt, b:UInt[3], c:UInt}
   myinput.a <- myoutput.a
   myoutput.b[0] <- myinput.b[0]
   myoutput.b[1] <- myinput.b[1]
\end{verbatim}
For details on the syntax and semantics of the subfield and subindex expressions, see section \ref{XXX}.

\subsubsection{The Partial Connection Algorithm}

A partial connect statement between two ground type elements connects the right-hand side expression to the left-hand side expression. Conversely, a reverse partial connect statement between two ground type elements connects the left-hand side expression to the right-hand side expression. 

A partial (or reverse partial) connect statement between two vector typed elements applies a partial (or reverse partial) connect from the first n subelements in the right-hand side expression to the first n corresponding subelements in the left-hand side expression, where n is the length of the smaller vector. 

A partial (or reverse partial) connect statement between two bundle typed elements considers any pair of fields, one from the first bundle type and one from the second, with matching names. If the first field in the pair is not flipped, then we apply a partial (or reverse partial) connect from the right-hand side field to the left-hand side field. However, if the first field is flipped, then we apply a reverse partial (or partial) connect from the right-hand side field to the left-hand side field. 

\subsection{Wire Declarations}
A wire is a named combinational circuit element that can be connected to using the connect statement.
A wire with a given name and type can be instantiated with the following statement.
\[
\kw{wire} \text{name } \kw{:} \pd{type} \\
\]

Declared wires are {\em bidirectional}, which means that they can be used as both an input (by being on the left-hand side of a connect statement), or as an output (by being on the right-hand side of a connect statement).

\subsection{Registers}
A register is a named stateful circuit element.
A register with a given name, type, clock reference, and reset reference, can be instantiated with the following statement.
\[
\kw{reg} \text{name } \kw{:} \pds{type},\pds{clk,} \pds{reset} \\
\]

Like wires, registers are also {\em bidirectional}, which means that they can be used as both an input (by being on the left-hand side of a connect statement), or as an output (by being on the right-hand side of a connect statement). 

The onreset statement is used to specify the initialization value for a register, which is assigned to the register when the declared \pds{reset} signal is asserted.

smem
read from same address as write


\subsection{Memories}
A memory is a stateful circuit element containing multiple elements.
The type for a memory must be completely specified; it cannot contain any unknown widths or bundle types with reverse fields.
Unlike registers, memories can {\em only} be read from or written to through {\em accessors}, and cannot be initialized using a special FIRRTL construct 
Instead, the circuit itself must contain the proper logic to initialize the memory.

Additionally, if a memory is written via two or more accessors to the same memory address, the resulting stored value is undefined.

Memories always have a synchronous write, but can either be declared to be read combinatorially or synchronously.
A combinatorially read memory with a given name, type, and size integer can be instantiated with the following statement.
\[
\begin{aligned}
\kw{cmem} \text{name } \kw{:} \pds{type} , size\\
\end{aligned}
\]

A synchronously read memory with a given name, type, and size integer can be instantiated with the following statement.
\[
\begin{aligned}
\kw{smem} \text{name } \kw{:} \pds{type} , size \\
\end{aligned}
\]

A synchronously read memory has the additional restriction that a read to an address on the same cycle its written returns an undefined value.

\subsection{Poisons}
A poison component is a named combinational circuit element that holds a random/garbage value.
It cannot be connected to using the connect statement, and its type cannot contain a bundle with a flipped value.

A poison component with a given name and type can be instantiated with the following statement.
\[
\kw{poison} \text{name } \kw{:} \pd{type} \\
\]

Declared poisons are {\em unidirectional}, which means that they can only be used as a source (being on the right-hand side of a connect statement).

\subsection{Nodes}
A node is simply a named intermediate value in a circuit, and is akin to a pointer in the C programming language.
A node with a given name and value can be instantiated with the following statement.
\[
\kw{node} \text{name } = \pd{exp} \\
\]
Unlike wires, nodes can only be used in {\em output} directions.
They can be connected from, but not connected to.
Consequentially, their expression cannot be a bundle type with any reversed fields.

\subsection{Accessors}
Accessors are used for either connecting to or from a vector-typed expression, from some {\em variable} index.
\[
\begin{aligned}
&\pd{dir} \kw{accessor} \text{name} = \pds{exp}[\text{index}] \pds{,clk} \\
&\pd{dir}        =     \kws{infer} \vert \kws{read} \vert \kws{write} \vert \kw{rdwr} \\
\end{aligned}
\]
Given an accessor direction, a name, an expression to access, the index at which to access, and the clock domain it is in, the above statement creates an accessor that may be used for connecting to or from the expression.
The expression must have a vector type, and the index must be a variable of UInt type.

A read, write, and inferred accessor is conceptually one-way; it must be consistently used to connect to, or to connect from, but not both.

A read-write accessor (\kws{rdwr}) is conceptually two-way; it can be used to connect to, to connect from, or both, {\em but not on the same cycle}.
If it is written to and read from on the same cycle, its behavior is undefined.

The following example demonstrates using accessors to read and write to a memory.
The accessor, \pds{reader}, acts as a memory read port that reads from the index specified by the wire \pds{i}.
The accessor, \pds{writer}, acts as a memory write port that writes 42 to the index specified by wire \pds{j}.
\[
\begin{aligned}
&\kw{wire} i : \kws{UInt}\kws{$<$} 5 \kws{$>$} \\
&\kw{wire} j : \kws{UInt}\kws{$<$} 5 \kws{$>$} \\
&\kw{cmem} m : \kws{UInt}\kws{$<$} 10 \kws{$>$},10 \\
&\kw{read} \kw{accessor} reader = m[i] , clk \\
&\kw{write} \kw{accessor} writer = m[j] , clk \\
&writer <= \kws{UInt}\kws{$<$} \kws{?} \kws{$>$}(42) \\
&\kw{node} temp = reader \\
\end{aligned}
\]

As mentioned previously, the only way to read from or write to a memory is through an accessor.
However, accessors are not restricted to accessing memories.
They can be used to access {\em any} cmem, smem, or wire/reg with vector-valued type.

An accessor passed a poisoned value as an index writes or reads a poisoned value.

\subsection{Instances}
An instance refers to a particular instantiation of a FIRRTL module.
An instance is constructed with a given name and a given module name.
\[
\begin{aligned}
\kw{inst} \text{name } \kw{:} \text{module}
\end{aligned}
\]

The resulting instance has a bundle type, where the given module's ports are fields and can be accessed using the subfield expression.
The orientation of the {\em output} ports are {\em default}, and the orientation of the {\em input} ports are {\em reverse}.
An instance may be directly connected to another element, but it must be on the right-hand side of the connect statement.

The following example illustrates directly connecting an instance to a wire:

{ \fontsize{11pt}{1.15em}\selectfont
\[
\begin{aligned}
&\kw{extmodule} Queue \ \kws{:} \\
&\quad \kw{input} clk  \ \kw{:} \kws{Clock} \\
&\quad \kw{input} in   \ \kw{:} \kws{UInt$<$}16\kws{$>$} \\
&\quad \kw{output} out \ \kw{:} \kws{UInt$<$}16\kws{$>$} \\
&\kw{module} Top \ \kws{:} \\
&\quad \kw{input} clk  \ \kw{:} \kws{Clock} \\
&\quad \kw{inst} queue \ \kw{:} Queue \\
&\quad \kw{wire} connect \ \kw{:} \bundleT{\kw{default} out \ \kw{:} \kws{UInt$<$}16\kws{$>$},\kw{reverse} in \ \kw{:} \ \kws{UInt$<$}16\kws{$>$},\kw{reverse} clk \ \kw{:} \ \kws{Clock}} \\
&\quad connect \ \kw{$<$=} queue \\
\end{aligned}
\]
}

The output ports of an instance may only be connected from, e.g., the right-hand side of a connect statement.
Conversely, the input ports of an instance may only be connected to, e.g., the left-hand side of a connect statement.

The following example illustrates a proper use of creating instances with different clock domains:

{ \fontsize{11pt}{1.15em}\selectfont
\[
\begin{aligned}
&\kw{extmodule} AsyncQueue \ \kws{:} \\
&\quad \kw{input} clk1 \ \kw{:} \kws{Clock} \\
&\quad \kw{input} clk2 \ \kw{:} \kws{Clock} \\
&\quad \kw{input} in  \ \kw{:} \bundleT{\kw{default} data \ \kw{:} \kws{UInt$<$}16\kws{$>$},\kw{reverse} ready \ \kw{:} \kws{UInt$<$}1\kws{$>$}} \\
&\quad \kw{output} out  \ \kw{:} \bundleT{\kw{default} data \ \kw{:} \kws{UInt$<$}16\kws{$>$},\kw{reverse} ready \ \kw{:} \kws{UInt$<$}1\kws{$>$}} \\
&\kw{extmodule} Source \ \kws{:} \\
&\quad \kw{input} clk \ \kw{:} \kws{Clock} \\
&\quad \kw{output} packet  \ \kw{:} \bundleT{\kw{default} data \ \kw{:} \kws{UInt$<$}16\kws{$>$},\kw{reverse} ready \ \kw{:} \kws{UInt$<$}1\kws{$>$}} \\
&\kw{extmodule} Sink \ \kws{:} \\
&\quad \kw{input} clk \ \kw{:} \kws{Clock} \\
&\quad \kw{input} packet  \ \kw{:} \bundleT{\kw{default} data \ \kw{:} \kws{UInt$<$}16\kws{$>$},\kw{reverse} ready \ \kw{:} \kws{UInt$<$}1\kws{$>$}} \\
&\kw{module} TwoClock \ \kws{:} \\
&\quad \kw{input} clk1 \ \kw{:} \kws{Clock} \\
&\quad \kw{input} clk2 \ \kw{:} \kws{Clock} \\
&\quad \kw{inst} src \ \kw{:} Source \\
&\quad src.clk \ \kw{$<$=} clk1 \\
&\quad \kw{inst} snk \ \kw{:} Sink \\
&\quad snk.clk \ \kw{$<$=} clk2 \\
&\quad \kw{inst} queue \ \kw{:} AsyncQueue \\
&\quad queue.clk1 \ \kw{$<$=} clk1 \\
&\quad queue.clk2 \ \kw{$<$=} clk2 \\
&\quad queue.in \ \kw{$<$=} src.packet \\
&\quad snk.packet \ \kw{$<$=} queue.out \\
\end{aligned}
\]
}

There are restrictions upon which modules the user is allowed to instantiate, so as not to create infinitely recursive hardware.
We define a module with no instances as a {\em level 0} module.
A module containing only instances of {\em level 0} modules is a {\em level 1} module, and a module containing only instances of {\em level 1} or below modules is a {\em level 2} module.
In general, a {\em level n} module is only allowed to contain instances of modules of level $n-1$ or below. 

\subsection{The OnReset Connect Statement}
The onreset connect statement is used to specify the default value for a \kws{reg} element.
\[
\kw{onreset} \text{r } \kw{$<$=} \text{output} 
\]

For a connection to be legal, the types of the two expressions must match exactly, including all field orientations if the elements contain bundle types.
The component on the right-hand side must be able to be used as an output, and the component on the left-hand side must be a \kws{reg} element.
The widths of the types may mismatch, and the semantics are the same as the connect statements.
Memories cannot be initialized with this construct.

By default, a \kws{reg} will not have an initialization value and will maintain its current value under the reset signal specified in their declaration.
The following example demonstrates declaring a \kws{reg}, and changing its initialization value to forty-two.

\[
\begin{aligned}
& \kw{reg} r : \kws{UInt}\kws{$<$} 10 \kws{$>$} \kws{(} clk, \ reset \kws{)}\\
& \kw{onreset} r <= \kws{UInt}\kws{$<$} \kws{?} \kws{$>$}(42)
\end{aligned}
\]

\subsection{The Partial Connect Statement}
The partial connect statement is a connect statement that does not require both expressions to be the same type. 
During the lowering pass, the partial connect will expand to some number of connect statements, possibly zero statements.
The following statement is used to connect the output of some component, to the input of another component. 
\[
\text{input } \kw{$<$--} \text{output} 
\]

For a partial connect between two components of a bundle-type, fields that are of the same type, orientation, and name will be connected.
Fields that do not match will not be connected.
For a partial connect between two components of a vector-type, the number of connected elements will be equal to the length of the shorter vector.
A partial connect between two components of the same ground type is equivalent to a normal connect statement.
All other combinations of types will not error, but will not generate any connect statements.

\subsection{The Conditional Statement}
The conditional statement is used to specify a condition that must be asserted under which a list of statements hold.
The condition must be a 1-bit unsigned integer.
The following statement states that the {\em conseq} statements hold only when {\em condition} is assert high, otherwise the {\em alt} statements hold instead.
\[
\begin{aligned}
\kw{when} \text{condition } \kw{:} \text{conseq } \kw{else :} \text{alt}
\end{aligned}
\]

Notationally, for convenience, we omit the \kws{else} branch if it is an empty statement. 

\subsubsection{Initialization Coverage}
Because of the conditional statement, it is possible for wires to be only partially connected to an expression.
In the following example, the wire {\em w} is connected to 42 when enable is asserted high, but it is not specified what {\em w} is connected to when enable is low.
This is an illegal FIRRTL circuit, and will throw a \kws{wire not initialized} error during compilation.
\[
\begin{aligned}
&\kw{wire} w : \kws{UInt}\kws{$<$} \kws{?} \kws{$>$} \\
&\kw{when} enable : \\
&\quad w <= \kws{UInt}\kws{$<$} \kws{?} \kws{$>$}(42) \\
\end{aligned}
\]

\subsubsection{Scoping}
The conditional statement creates a new {\em scope} within its consequent and alternative branches.
It is an error to refer to any component declared within a branch after the branch has ended.

Note that there is still only a single identifier namespace in a module.
Thus, there cannot be two components with identical names in the same module, {\em even if} they are in separate scopes.
This is to facilitate writing transformational passes, by ensuring that the component name and module name is sufficient to uniquely identify a component.

\subsubsection{Conditional Connect Semantics}
Inside a when, a connection to a component is conditional only if the component is declared outside the when statement.
If the component is both declared and connected to inside a when, the connection is {\em not} conditional on that when.

Conceptually, a when creates a mux between the stuff outside and the stuff inside - it acts as type of "conditional barrier".
Thus, if you draw a line between a component's declaration and a connection to it, that connection is dependent on all intersected when predicates being true.

The following example shows a {\em conditional} connection inside a when statement, where the register \pd{r} is assigned the value of 42 only if \pds{enable} is true.
\[
\begin{aligned}
&\kw{reg} r : \kws{UInt}\kws{$<$} \kws{6} \kws{$>$} \\
&\kw{when} enable : \\
&\quad r <= \kws{UInt}\kws{$<$} \kws{6} \kws{$>$}(42) \\
\end{aligned}
\]

The following shows an {\em unconditional} connection inside a when statement, where the register \pd{r} is assigned the value of 42 {\em every cycle}.
\[
\begin{aligned}
&\kw{when} enable : \\
&\quad \kw{reg} r : \kws{UInt}\kws{$<$} \kws{6} \kws{$>$} \\
&\quad r <= \kws{UInt}\kws{$<$} \kws{6} \kws{$>$}(42) \\
\end{aligned}
\]

\subsection{Statement Groups}
Several statements can be grouped into one using the following construct.
\[
\begin{aligned}
(\pd{stmt*})
\end{aligned}
\]
Ordering is important in a statement group.
Later connect statements take precedence over earlier connect statements, and circuit components cannot be referred to before they are instantiated.

\subsubsection{Last Connect Semantics}
Because of the connect statement, FIRRTL statements are {\em ordering} dependent.
Later connections take precedence over earlier connections.
In the following example, the wire w is connected to 42, not 20. 
\[
\begin{aligned}
&\kw{wire} w : \kws{UInt}\kws{$<$} \kws{?} \kws{$>$} \\
&w <= \kws{UInt}\kws{$<$} ? \kws{$>$}(20) \\
&w <= \kws{UInt}\kws{$<$} ? \kws{$>$}(42) \\
\end{aligned}
\]

By coupling the conditional statement with last connect semantics, many circuits can be expressed in a natural style.
In the following example, the wire w is connected to 20 unless the enable expression is asserted high, in which case w is connected to 42. 
\[
\begin{aligned}
&\kw{wire} w : \kws{UInt}\kws{$<$} \kws{?} \kws{$>$} \\
&w <= \kws{UInt}\kws{$<$} \kws{?} \kws{$>$}(20) \\
&\kw{when} enable : \\
&\quad w <= \kws{UInt}\kws{$<$} \kws{?} \kws{$>$}(42) \\
\end{aligned}
\]

\subsection{The Stop Statement}
The stop statement is used to halt simulations of the circuit.
\[
\begin{aligned}
\kw{stop}
\end{aligned}
\]
If a backend does not support stop, it will omit emitting this node.

\subsection{The Printf Statement}
The printf statement is used to print a formatted string during simulations of the circuit.
\[
\begin{aligned}
\kw{printf}(\strings,\pds{exp*})
\end{aligned}
\] 
If a backend does not support printf, it will omit emitting this node.

\subsection{The Empty Statement}
The empty statement is specified using the following.
\[
\begin{aligned}
\kw{skip}
\end{aligned}
\]
The empty statement does nothing and is used simply as a placeholder where a statement is expected.
It is typically used as the alternative branch in a conditional statement. 
In addition, it is useful for transformation pass writers.

\section{Expressions}

FIRRTL expressions are used for creating values corresponding to the ground types, for referring to a declared circuit component, for accessing a nested element within a component, and for performing primitive operations. 

\subsection{Unsigned Integers}

A value of type \kws{UInt} can be directly created using the following expression.
\[
\kws{UInt}\kws{$<$} \pds{width} \kws{$>$}(\text{value})
\]
The given value must be non-negative, and the given width, if known, must be large enough to hold the value.
If the width is specified as unknown, then FIRRTL infers the minimum possible width necessary to hold the value.

\subsection{Signed Integers}

A value of type \kws{SInt} can be directly created using the following expression.
\[
\kws{SInt}\kws{$<$} \pds{width} \kws{$>$}(\text{value})
\]
The given width, if known, must be large enough to hold the given value in two's complement format.
If the width is specified as unknown, then FIRRTL infers the minimum possible width necessary to hold the value.

\subsection{References}
\[
\text{name}
\]
A reference is simply a name that refers to some declared circuit component.
A reference may refer to a port, a node, a wire, a register, an instance, a memory, a node, or a structural register.

\subsection{Subfields}
\[
\pds{exp}.\text{name}
\]
The subfield expression may be used for one of two purposes:
\begin{enumerate}
\item To refer to a specific port of an instance, using instance-name.port-name. 
\item To refer to a specific field within a bundle-typed expression.
\end{enumerate}

\subsection{Subindex}
\[
\pds{exp}[\text{index}]
\]
The subindex expression is used for referring to a specific element within a vector-valued expression.
It is legal to use the subindex expression on any vector-valued expression, except for memories. 

\subsection{Primitive Operation}
\[
\pds{primop}(\pds{exp*}, \ints\text{*})
\]
There are a number of different primitive operations supported by FIRRTL. 
Each operation takes some number of expressions, along with some number of integer literals.
Section \ref{primitives} will describe the format and semantics of each operation.


\section{Primitive Operations} \label{primitives}

All primitive operations expression operands must be ground types.
In addition, some operations allow all permutations of operand ground types, while others on allow subsets.
When well defined, input arguments are allowed to be differing widths, with the semantics of sign-extending the input arguments prior to executing the operation.

\subsection{Add Operation}
\[
\begin{array}{rll}
\kws{Input Types} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{add}(\pds{op1}:UInt, \pds{op2}:UInt) & UInt & max(width(op1),width(op2)) + 1 \\
\kws{add}(\pds{op1}:UInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) + 1 \\
\kws{add}(\pds{op1}:SInt, \pds{op2}:UInt) & SInt & max(width(op1),width(op2)) + 1 \\
\kws{add}(\pds{op1}:SInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) + 1 \\
\end{array}
\]
The resultant's value is 1-bit larger than the wider of the two operands and has a signed type if either operand is signed (otherwise is unsigned).

\subsection{Subtract Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{sub}(\pds{op1}:UInt, \pds{op2}:UInt) &  SInt & max(width(op1),width(op2)) + 1  \\
\kws{sub}(\pds{op1}:UInt, \pds{op2}:SInt) &  SInt & max(width(op1),width(op2)) + 1  \\
\kws{sub}(\pds{op1}:SInt, \pds{op2}:UInt) &  SInt & max(width(op1),width(op2)) + 1  \\
\kws{sub}(\pds{op1}:SInt, \pds{op2}:SInt) &  SInt & max(width(op1),width(op2)) + 1  \\
\end{array}
\]
The subtraction operation works similarly to the add operation, but always returns a signed integer with a width that is 1-bit wider than the max of the widths of the two operands.

\subsection{Add Wrap Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{addw}(\pds{op1}:UInt, \pds{op2}:UInt) & UInt & max(width(op1),width(op2)) \\
\kws{addw}(\pds{op1}:UInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) \\
\kws{addw}(\pds{op1}:SInt, \pds{op2}:UInt) & SInt & max(width(op1),width(op2)) \\
\kws{addw}(\pds{op1}:SInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) \\
\end{array}
\]
The add wrap operation works identically to the normal add operation except that the resultant width is the maximum of the width of the two operands, instead of 1 bit greater than the maximum.
In the case of overflow, the result silently rolls over.

\subsection{Subtract Wrap Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{subw}(\pds{op1}:UInt, \pds{op2}:UInt) & UInt & max(width(op1),width(op2)) \\
\kws{subw}(\pds{op1}:UInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) \\
\kws{subw}(\pds{op1}:SInt, \pds{op2}:UInt) & SInt & max(width(op1),width(op2)) \\
\kws{subw}(\pds{op1}:SInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) \\
\end{array}
\]
Similarly to the add wrap operation, the subtract wrap operation works identically to the normal subtract operation except that the resultant width is the maximum of the width of the two operands.
In the case of overflow, the result silently rolls over.

\subsection{Multiply Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{mul}(\pds{op1}:UInt, \pds{op2}:UInt) &   UInt & width(op1) + width(op2)  \\
\kws{mul}(\pds{op1}:UInt, \pds{op2}:SInt) &   SInt & width(op1) + width(op2)  \\
\kws{mul}(\pds{op1}:SInt, \pds{op2}:UInt) &   SInt & width(op1) + width(op2)  \\
\kws{mul}(\pds{op1}:SInt, \pds{op2}:SInt) &   SInt & width(op1) + width(op2)  \\
\end{array}
\]
The resultant value has width equal to the sum of the widths of its two operands.

\subsection{Divide Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{div}(\pds{op1}:UInt, \pds{op2}:UInt) &   UInt & width(op1)     \\
\kws{div}(\pds{op1}:UInt, \pds{op2}:SInt) &   SInt & width(op1) + 1  \\
\kws{div}(\pds{op1}:SInt, \pds{op2}:UInt) &   SInt & width(op1)     \\
\kws{div}(\pds{op1}:SInt, \pds{op2}:SInt) &   SInt & width(op1) + 1  \\
\end{array}
\]
The first argument is the dividend, the second argument is the divisor.
The resultant width of a divide operation is equal to the width of the dividend, plus one if the divisor is an SInt.
The resultant value follows the following formula : div(a,b) = round-towards-zero(a/b) + mod(a,b)

\subsection{Modulus Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{mod}(\pds{op1}:UInt, \pds{op2}:UInt) &   UInt & width(op2)     \\
\kws{mod}(\pds{op1}:UInt, \pds{op2}:SInt) &   UInt & width(op2)     \\
\kws{mod}(\pds{op1}:SInt, \pds{op2}:UInt) &   SInt & width(op2) + 1 \\
\kws{mod}(\pds{op1}:SInt, \pds{op2}:SInt) &   SInt & width(op2)     \\
\end{array}
\]

The first argument is the dividend, the second argument is the divisor.
The resultant width of a modulus operation is equal to the width of the divisor, except when the modulus is positive and the result can be negative.
The resultant value follows the following formula : div(a,b) = round-towards-zero(a/b) + mod(a,b)

\subsection{Quotient Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{quo}(\pds{op1}:UInt, \pds{op2}:UInt) &   UInt & width(op1) + 1 \\
\kws{quo}(\pds{op1}:UInt, \pds{op2}:SInt) &   SInt & width(op1)     \\
\kws{quo}(\pds{op1}:SInt, \pds{op2}:UInt) &   SInt & width(op1) + 1 \\
\kws{quo}(\pds{op1}:SInt, \pds{op2}:SInt) &   SInt & width(op1)     \\
\end{array}
\]

The first argument is the dividend, the second argument is the divisor.
The resultant width of a quotient operation is equal to the width of the dividend, plus one if the divisor is an SInt.
The resultant value follows the following formula : quo(a,b) = floor(a/b) + rem(a,b)

\subsection{Remainder Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{rem}(\pds{op1}:UInt, \pds{op2}:UInt) &   UInt & width(op2)     \\
\kws{rem}(\pds{op1}:UInt, \pds{op2}:SInt) &   SInt & width(op2)     \\
\kws{rem}(\pds{op1}:SInt, \pds{op2}:UInt) &   UInt & width(op2) + 1 \\
\kws{rem}(\pds{op1}:SInt, \pds{op2}:SInt) &   SInt & width(op2)     \\
\end{array}
\]

The first argument is the dividend, the second argument is the divisor.
The resultant width of a modulus operation is equal to the width of the divisor, except when the divisor is positive and the result can be negative.
The resultant value follows the following formula : quo(a,b) = floor(a/b) + rem(a,b)

\subsection{Comparison Operations}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{lt}      (\pds{op1}:UInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{lt}      (\pds{op1}:UInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{lt}      (\pds{op1}:SInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{lt}      (\pds{op1}:SInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{leq}     (\pds{op1}:UInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{leq}     (\pds{op1}:UInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{leq}     (\pds{op1}:SInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{leq}     (\pds{op1}:SInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{gt}      (\pds{op1}:UInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{gt}      (\pds{op1}:UInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{gt}      (\pds{op1}:SInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{gt}      (\pds{op1}:SInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{geq}     (\pds{op1}:UInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{geq}     (\pds{op1}:UInt, \pds{op2}:SInt) & UInt & 1    \\
\kws{geq}     (\pds{op1}:SInt, \pds{op2}:UInt) & UInt & 1    \\
\kws{geq}     (\pds{op1}:SInt, \pds{op2}:SInt) & UInt & 1    \\
\end{array}
\]
Each operation accepts any combination of SInt or UInt input arguments, and always returns a single-bit unsigned integer.

\subsection{Equality Comparison}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{eq}(\pds{op1}:UInt, \pds{op2}:UInt)     & UInt & 1 \\
\kws{eq}(\pds{op1}:UInt, \pds{op2}:SInt)     & UInt & 1 \\
\kws{eq}(\pds{op1}:SInt, \pds{op2}:UInt)     & UInt & 1 \\
\kws{eq}(\pds{op1}:SInt, \pds{op2}:SInt)     & UInt & 1 \\
\end{array}
\]
The equality comparison operator accepts either two unsigned or signed integers and checks whether they are arithmetically equal.
The resulting value is a 1-bit unsigned integer. 

\subsection{Not-Equality Comparison}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{neq}(\pds{op1}:UInt, \pds{op2}:UInt)     & UInt & 1 \\
\kws{neq}(\pds{op1}:UInt, \pds{op2}:SInt)     & UInt & 1 \\
\kws{neq}(\pds{op1}:SInt, \pds{op2}:UInt)     & UInt & 1 \\
\kws{neq}(\pds{op1}:SInt, \pds{op2}:SInt)     & UInt & 1 \\
\end{array}
\]
The not-equality comparison operator accepts either two unsigned or signed integers and checks whether they are arithmetically not equal.
The resulting value is a 1-bit unsigned integer. 

\subsection{Equivalence Comparison}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{eqv}(\pds{op1}:UInt, \pds{op2}:UInt)     & UInt & 1 \\
\kws{eqv}(\pds{op1}:SInt, \pds{op2}:SInt)     & UInt & 1 \\
\end{array}
\]
The equivalence comparison operator accepts either two unsigned or two signed integers and checks whether they are bitwise equivalent.
The resulting value is a 1-bit unsigned integer. 

For an arithmetic equals between a signed and unsigned integer, use the equality operator.

\subsection{Not-Equivalence Comparison}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{neqv}(\pds{op1}:UInt, \pds{op2}:UInt)     & UInt & 1 \\
\kws{neqv}(\pds{op1}:SInt, \pds{op2}:SInt)     & UInt & 1 \\
\end{array}
\]
The not-equivalent comparison operator accepts either two unsigned or two signed integers and checks whether they are not bitwise equivalent.
The resulting value is a 1-bit unsigned integer. 

If an arithmetic not-equals between a signed and unsigned integer is desired, use the not-equals operator.

\subsection{Multiplex}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{mux}  (\pds{condition}:UInt, \pds{op1}:UInt, \pds{op2}:UInt) & UInt & max(width(op1),width(op2)) \\
\kws{mux}  (\pds{condition}:UInt, \pds{op1}:SInt, \pds{op2}:SInt) & SInt & max(width(op1),width(op2)) \\
\end{array}
\]
The multiplex operation accepts three signals, a 1-bit unsigned integer for the condition expression, followed by either two unsigned integers, or two signed integers.
If the condition is high, then the result is equal to the first of the two following operands.
If the condition is low, then the result is the second of the two following operands. 

The output is of the same width as the max width of the inputs.

\subsection{Padding Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{pad}(\pds{op}:UInt, \text{num})     & UInt & num \\
\kws{pad}(\pds{op}:SInt, \text{num})     & SInt & num \\
\end{array}
\]
A pad operation is provided which either zero-extends or sign-extends an expression to a specified width.
The given width, num, must be equal to or greater than the existing width of the expression. 

\subsection{Reinterpret Bits as UInt}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{asUInt}(\pds{op1}:UInt)       & UInt & width(op1) \\
\kws{asUInt}(\pds{op1}:SInt)       & UInt & width(op1) \\
\end{array}
\]
Regardless of input type, primop returns a UInt with the same width as the operand.

\subsection{Reinterpret Bits as SInt}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{asSInt}(\pds{op1}:UInt)     & SInt & width(op1) \\
\kws{asSInt}(\pds{op1}:SInt)     & SInt & width(op1) \\
\end{array}
\]
Regardless of input type, primop returns a SInt with the same width as the operand.

\subsection{Shift Left Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{shl}(\pds{op}:UInt, \text{num})      & UInt & width(op) + num \\
\kws{shl}(\pds{op}:SInt, \text{num})      & SInt & width(op) + num \\
\end{array}
\]
The shift left operation accepts either an unsigned or a signed integer, plus a non-negative integer literal specifying the number of bits to shift.
The resultant value has the same type as the operand.
The output of a shift left operation is equal to the original signal concatenated with $n$ zeros at the end, where $n$ is the shift amount.

\subsection{Shift Right Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{shr}(\pds{op}:UInt, \text{num})      & UInt & width(op) - num \\
\kws{shr}(\pds{op}:SInt, \text{num})      & SInt & width(op) - num \\
\end{array}
\]
The shift right operation accepts either an unsigned or a signed integer, plus a non-negative integer literal specifying the number of bits to shift.
The resultant value has the same type as the operand.
The shift amount must be less than or equal to the width of the operand.
The output of a shift right operation is equal to the original signal with the least significant $num$ bits truncated, where $num$ is the shift amount.

\subsection{Dynamic Shift Left Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{dshl}(\pds{op1}:UInt, \pds{op2}:UInt)  & UInt & width(op1) + pow(2,width(op2)) \\
\kws{dshl}(\pds{op1}:SInt, \pds{op2}:UInt)  & SInt & width(op1) + pow(2,width(op2)) \\
\end{array}
\]
The dynamic shift left operation accepts either an unsigned or a signed integer, plus an unsigned integer dynamically specifying the number of bits to shift.
The resultant value has the same type as the operand.
The output of a dynamic shift left operation is equal to the original signal concatenated with $n$ zeros at the end, where $n$ is the dynamic shift amount.
The output width of a dynamic shift left operation is the width of the original signal plus 2 raised to the width of the dynamic shift amount.

\subsection{Dynamic Shift Right Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{dshr}(\pds{op1}:UInt, \pds{op2}:UInt)  & UInt & width(op1) \\
\kws{dshr}(\pds{op1}:SInt, \pds{op2}:UInt)  & SInt & width(op1) \\
\end{array}
\]
The shift right operation accepts either an unsigned or a signed integer, plus a non-negative integer literal specifying the number of bits to shift.
The resultant value has the same type as the operand.
The shift amount must be less than or equal to the width of the operand.
The output of a shift right operation is equal to the original signal with the least significant $n$ bits truncated, where $n$ is the dynamic shift amount.
The output width of a dynamic shift right operation is the width of the original signal.

\subsection{Logical Convert to Signed}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{cvt}(\pds{op}:UInt)      & SInt & width(op) + 1 \\
\kws{cvt}(\pds{op}:SInt)      & SInt & width(op) \\
\end{array}
\]
The convert operation accepts either an unsigned or a signed integer.
The resultant value is always a signed integer.
The output of a convert operation will be the same arithmetic value as the input value.
The output width is the same as the input width if the input is signed, and increased by one if the input is unsigned.

\subsection{Negate}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{neg}(\pds{op1}:UInt)       & SInt & width(op1) + 1 \\
\kws{neg}(\pds{op1}:SInt)       & SInt & width(op1) \\
\end{array}
\]
If the input type is UInt, primop returns the negative value as an SInt with the width of the operand plus one.
If the input type is SInt, primop returns -1 * input value, as an SInt with the same width of the operand.

\subsection{Bitwise Operations}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{not}     (\pds{op1:UInt}) & UInt & width(op1)    \\
\kws{and}     (\pds{op1:UInt}, \pds{op2:UInt}) & UInt & max(width(op1),width(op2))    \\
\kws{or}      (\pds{op1:UInt}, \pds{op2:UInt}) & UInt & max(width(op1),width(op2))    \\
\kws{xor}     (\pds{op1:UInt}, \pds{op2:UInt}) & UInt & max(width(op1),width(op2))    \\
\end{array}
\]
The above operations correspond to bitwise not, and, or, and exclusive or respectively.
The operands must be unsigned integers, and the resultant width is equal to the width of the wider of the two operands. 

\subsection{Reduce Bitwise Operations}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{andr}     (\pds{op:UInt}) & UInt & 1    \\
\kws{orr}      (\pds{op:UInt}) & UInt & 1    \\
\kws{xorr}     (\pds{op:UInt}) & UInt & 1    \\
\end{array}
\]
The above operations correspond to bitwise not, and, or, and exclusive or respectively, reduced over every bit of a single unsigned integer.
The resultant width is always one.

\subsection{Concatenation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{cat}(\pds{op1}:UInt, \pds{op2}:UInt)  & UInt & width(op1) + width(op2)    \\
\end{array}
\]
The concatenation operator accepts two unsigned integers and returns the bitwise concatenation of the two values as an unsigned integer.
The resultant width is the sum of the widths of the two operands.

\subsection{Bit Extraction Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{bit}(\pds{op}:UInt, \text{index})  & UInt & 1    \\
\end{array}
\]
The bit extraction operation accepts an unsigned integer, plus an integer literal specifying the index of the bit to extract.
The resultant value is a 1-bit unsigned integer.
The index must be non-negative and less than the width of the operand.
An index of zero indicates the least significant bit in the operand, and an index of one less than the width the operand indicates the most significant bit in the operand.

\subsection{Bit Range Extraction Operation}
\[
\begin{array}{rll}
\kws{primop} & \kws{Resultant Type} & \kws{Resultant Width} \\
\kws{bits}(\pds{op}:UInt, \text{high}, \text{low})  & UInt & high - low + 1    \\
\end{array}
\]
The bit range extraction operation accepts either an unsigned integer, plus two integer literals that specify the high (inclusive) and low (inclusive) index of the bit range to extract.
The index must be non-negative and less than the width of the operand.
Regardless of the type of the operand, the resultant value is a $n$-bit unsigned integer, where $n = \text{high} - \text{low} + 1$. 

\section{FIRRTL Forms}

To simplify the writing of transformation passes, any FIRRTL implementation will provide a {\em resolving} pass, which resolves all types, widths, and checks the legality of the circuit, and a {\em lowering} pass, which rewrites any FIRRTL circuit into an equivalent {\em lowered form}, or LoFIRRTL.

\subsection{Resolved Form}

The resolved form is guaranteed to be well-formed, meaning all restrictions to a FIRRTL circuit have been checked. In addition, all unknown widths and inferred accessor directions have been resolved.

\subsection{Lowered Form}

The lowered form, LoFIRRTL, is a structured subset of FIRRTL, making it a minimal representation that is convenient for low-level transforms. 

The body of a lowered module consists of a list of declarations, connect statements, and {\em predicated single connect statements}.
A predicated single connect statement is a conditional statement containing a single connect statement and no else branch.

The following circuit is lowered:
\[
\begin{aligned}
&\kw{module} \text{MyCounter} :                              \\
&\quad \kw{clock} \text{clk : UInt$<$1$>$}                        \\
&\quad \kw{input} \text{reset : UInt$<$1$>$}                        \\
&\quad \kw{input} \text{inc : UInt$<$1$>$}                           \\
&\quad \kw{output} \text{out : UInt$<$3$>$}                         \\
&\quad \kw{reg} \text{counter : UInt$<$3$>$, clk, reset} \\
&\quad \kw{when} \text{inc : counter $<$= addw(counter, UInt$<$1$>$(1))}   \\
&\quad \text{out $<$= counter}  \\
\end{aligned}
\]

The following restrictions also hold for modules in LoFIRRTL.

\begin{itemize}
\item \kws{No Nested Expressions} : 
In the declaration of the structural elements, the only nested expressions allowed are references, and unsigned and signed literals.
All other nested expressions must be lifted to a named node, and referred to through a reference. 
\item \kws{No Composite Types} :
No module port or wire may be declared with a bundle or vector type.
The lowering pass will recursively expand ports into its constituent elements until all ports are declared with ground types.
\item \kws{Single Connect} :
Every declared component can only be connected to once within a module.
This connect could be a predicated single connect.
\item \kws{No Nested Whens} :
Other than predicated single connect statements, no other conditional statements are allowed.
\item \kws{Inlined Lowered Form} :
A further (and optional) pass provided by FIRRTL is the inlining pass, which recursively inlines all instances in the top-level module until the top-level module is the only remaining module in the circuit.
Inlined LoFIRRTL is essentially a flat netlist which specifies every component used in a circuit and their input connections. 
\end{itemize}

\section{Annotations - IN PROGRESS}
Supporting annotations is a critical piece of FIRRTL, yet is a very difficult problem to solve properly.
We are in the experimental phase of supporting annotations, and our philosophy is outlined below.
It remains to be seen whether our philosophy is correct - if not, we will certainly devise a new strategy.

\begin{enumerate}[topsep=3pt,itemsep=-0.5ex,partopsep=1ex,parsep=1ex]
\item Writing a correct circuit is difficult - avoid silent failures at all costs.
\item If annotations are held in the graph, every pass must properly propagate all possible annotations.
\item A pass incorrectly propagating an annotation cannot be easily detected (silent failure).
\item If annotations are held in an exteral data structure mapping names to annotations, the structure must updated after every pass.
\item Incorrectly updating the structure will cause a mismatching of names between circuit components and annotation entries, which is easily detected.
\item Thus, we feel the ability to detect failure outweighs the additional burden on annotation writers.
\end{enumerate}

To implement this philosophy, we encourage passes to either preserve names in the graph, use simple algorithms to transform names, or provide a rename table after a pass.
The annotation writer then updates their data structure accordingly.

\section{Concrete Syntax}\label{concrete}
This section describes the text format for FIRRTL that is supported by the provided readers and writers.

\subsection*{General Principles}
FIRRTL's text format is human-readable and uses indentation to indicate block structuring.
The following characters are allowed in identifiers: upper and lower case letters, digits, as well as the punctuation characters \verb|~!@#$%^*-_+=?/|.
Identifiers cannot begin with a digit. 

Comments begin with a semicolon and extend until the end of the line.
Commas are treated as whitespace, and may be used by the user for clarity if desired. 

Statements are grouped into statement groups using parenthesis, however a colon at the end of a line will automatically assume the next indented region is a statement group.
This mechanism is used for indicating block structuring. 

The following circuit, module, port and statement examples all exclude the info token \verb|@[filename:line.col]|, which can be optionally included at the beginning of the first line of each elements' concrete syntax.

\subsection*{Circuits and Modules}
A circuit is specified the following way.
\begin{verbatim}
circuit name : (modules ...)
\end{verbatim}
Or by taking advantage of indentation structuring:
\begin{verbatim}
circuit name :
   modules ...
\end{verbatim}

A module is specified the following way.
\begin{verbatim}
module name : (ports ... stmts ...)
\end{verbatim}
The module body consists of a sequence of ports followed immediately by a sequence of statements.
If there is more than one statement they are grouped into a statement group by the parser. 
By using indentation structuring:
\begin{verbatim}
module name :
   ports ...
   stmts ...
\end{verbatim}

The following shows an example of a simple module.
\begin{verbatim}
module mymodule :
   input a: UInt<1>
   output b: UInt<1>
   clock clk: UInt<1>
   b <= a
\end{verbatim}

\subsection*{Types}
The unsigned and signed integer types are specified the following way.
The following examples demonstrate an unsigned integer with known bit width, signed integer with known bit width, an unsigned integer with unknown bit width, and signed integer with unknown bit width.
\begin{verbatim}
UInt<42>
SInt<42>
UInt<?>
SInt<?>
\end{verbatim}

The bundle type consists of a number of fields surrounded with braces.
The following shows an example of a decoupled bundle type.
Note that the commas are for clarity only and are not necessary.
\begin{verbatim}
{default data: UInt<10>,
 default valid: UInt<1>,
 reverse ready: UInt<1>} 
\end{verbatim}

The vector type is specified by immediately postfixing a type with a bracketed integer literal.
The following example demonstrates a ten-element vector of 16-bit unsigned integers.
\begin{verbatim}
UInt<16>[10]
\end{verbatim}

\subsection*{Statements}
The following examples demonstrate declaring wires, registers, memories, nodes, instances, poisons, and accessors.
\begin{verbatim}
wire mywire : UInt<10> 
reg myreg : UInt<10>, clk, reset 
cmem mycombmem : UInt<10>,16
smem myseqmem : UInt<10>,16
inst myinst : MyModule 
poison mypoison : UInt<10> 
infer accessor myaccessor = e[i],clk
\end{verbatim}

The connect statement is specified using the \verb|<=| operator.
\begin{verbatim}
x <= y
\end{verbatim}

The onreset connect statement is specified using the onreset keyword and the \verb|<=| operator.
\begin{verbatim}
onreset x <= y 
\end{verbatim}

The partial connect statement is specified using the \verb|<-| operator.
\begin{verbatim}
x <- y 
\end{verbatim}

The assert statement is specified using the assert keyword.
\begin{verbatim}
assert x
\end{verbatim}

The conditional statement is specified with the \verb|when| keyword.
\begin{verbatim}
when x : x <= y else : x <= z
\end{verbatim}
Or by using indentation structuring:
\begin{verbatim}
when x :
   x <= y
else :
   x <= z
\end{verbatim}

If there is no alternative branch specified, the parser will automatically insert an empty statement.
\begin{verbatim}
when x :
   x <= y
\end{verbatim}

For convenience when expressing nested conditional statements, the colon following the \verb|else| keyword may be elided if the next statement is another conditional statement.
\begin{verbatim}
when x :
   x <= y
else when y :
   x <= z
else :
   x <= w
\end{verbatim}

\subsection*{Expressions}

The UInt and SInt constructors create literal integers from a given value and bit width.
The following examples demonstrate creating literal integers of both known and unknown bit width.
\begin{verbatim}
UInt<4>(42)
SInt<4>(-42)
UInt<?>(42)
SInt<?>(-42)
\end{verbatim}

References are specified with an identifier.
\begin{verbatim}
x
\end{verbatim}

Subfields are expressed using the dot operator.
\begin{verbatim}
x.data
\end{verbatim}

Subindices are expressed using the \verb|[]| operator.
\begin{verbatim}
x[10]
\end{verbatim}

Primitive operations are expressed by following the name of the primitive with a list containing the operands. 
\begin{verbatim}
add(x, y)
add(x, add(x, y))
shl(x, 42)
\end{verbatim}

\section{FIRRTL Language Definition}

\subsection{Abstract Syntax Tree}
{ \fontsize{10pt}{1.10em}\selectfont
\[
\begin{array}{rrll}
\pd{circuit}    &=     &\kw{circuit} \id \kw{:} (\pd{module*})                                        &\text{Circuit}\\
\pd{module}     &=     &\info \kw{module}  \id \kw{:} (\pd{port*} \pd{stmt})                          &\text{Module}\\
                &\vert &\info \kw{extmodule}  \id \kw{:} (\pd{port*})                                 &\text{External Module}\\
\pd{port}       &=     &\info \pd{dir} \id \kw{:} \pd{type}                                           &\text{Port}\\
\pd{dir}        &=     &\kws{input} \vert \kws{output}                                                &\text{Port Direction}\\
\pd{type}       &=     &\kws{UInt} \kws{$<$} \pds{width} \kws{$>$}                                    &\text{Unsigned Integer}\\
                &\vert &\kws{SInt} \kws{$<$} \pds{width} \kws{$>$}                                    &\text{Signed Integer}\\
                &\vert &\kws{Clock}                                                                   &\text{Clock}\\
                &\vert &\bundleT{\pd{field*}}                                                         &\text{Bundle}\\
                &\vert &\pds{type}[\ints]                                                             &\text{Vector}\\
\pd{field}      &=     &\pd{orientation} \id \kw{:} \pd{type}                                         &\text{Bundle Field}\\
\pd{orientation}&=     &\kws{default} \vert \kws{reverse}                                             &\text{Orientation}\\
\pd{width}      &=     &\ints \vert \kw{?}                                                            &\text{Known/Unknown Integer Width}\\
\pd{stmt}       &=     &\info \kw{wire} \id \kw{:} \pd{type}                                          &\text{Wire Declaration}\\
                &\vert &\info \kw{reg} \id \kw{:}  \pds{type} , \pds{exp} , \pds{exp} , \pds{exp}     &\text{Register Declaration}\\
                &\vert &\info \kw{mem} \id \kw{:} \pds{type}, 
                        \ints,\ints,\ints,(\idst),(\idst),(\idst)                                     &\text{Memory Declaration}\\
                &\vert &\info \kw{inst} \id \kw{:} \id                                                &\text{Instance Declaration}\\
                &\vert &\info \kw{poison} \id \kw{:} \pds{type}                                       &\text{Poison Declaration}\\
                &\vert &\info \kw{node} \id  = \pd{exp}                                               &\text{Node Declaration}\\
                &\vert &\info \pd{exp} \kw{$<$=} \pd{exp}                                             &\text{Connect}\\
                &\vert &\info \pd{exp} \kw{$<$--} \pd{exp}                                            &\text{Partial Connect}\\
                &\vert &\info \kw{when} \pd{exp} \kw{:} \pd{stmt} \kw{else :} \pd{stmt}               &\text{Conditional}\\
                &\vert &\info \kw{stop}(\pds{exp},\pds{exp},\ints)                                    &\text{Stop Statement}\\
                &\vert &\info \kw{printf}(\pds{exp},\pds{exp},\strings,\pds{exp*})                    &\text{Printf Statement}\\
                &\vert &\info \kw{skip}                                                               &\text{Empty Statement}\\
                &\vert &\info (\pd{stmt*})                                                            &\text{Statement Group}\\
\pd{exp}        &=     &\info \kws{UInt} \kws{$<$} \pds{width} \kws{$>$}(\ints)                       &\text{Literal Unsigned Integer}\\
                &\vert &\info \kws{SInt} \kws{$<$} \pds{width} \kws{$>$}(\ints)                       &\text{Literal Signed Integer}\\
                &\vert &\info \id                                                                     &\text{Reference}\\
                &\vert &\info \pds{exp}.\id                                                           &\text{Subfield}\\
                &\vert &\info \pds{exp}[\ints]                                                        &\text{Subindex}\\
                &\vert &\info \pds{exp}[\pds{exp}]                                                    &\text{Subaccess}\\
                &\vert &\info \pds{primop}(\pds{exp*}, \ints\text{*})                                 &\text{Primitive Operation}\\
\pd{info}       &=     &\text{filename } \kw{:} \text{line } . \text{ col}                            &\text{File Location}\\
                &\vert &\kw{noinfo}                                                                   &\text{No File Location}\\
\end{array}
\]
}
\[
{ \fontsize{10pt}{1.07em}\selectfont
\begin{array}{rrll}
\pd{primop}   &=               &\kws{add}            &\text{Unsigned/Signed Add}\\
              &\vert           &\kws{sub}            &\text{Unsigned/Signed Subtract}\\
              &\vert           &\kws{addw}           &\text{Unsigned/Signed Add Wrap}\\
              &\vert           &\kws{subw}           &\text{Unsigned/Signed Subtract Wrap}\\
              &\vert           &\kws{mul}            &\text{Unsigned/Signed Multiply}\\
              &\vert           &\kws{div}            &\text{Unsigned/Signed Divide}\\
              &\vert           &\kws{mod}            &\text{Unsigned/Signed Modulo}\\
              &\vert           &\kws{quo}            &\text{Unsigned/Signed Quotient}\\
              &\vert           &\kws{rem}            &\text{Unsigned/Signed Remainder}\\
              &\vert           &\kws{lt}             &\text{Unsigned/Signed Less Than}\\
              &\vert           &\kws{leq}            &\text{Unsigned/Signed Less or Equal}\\
              &\vert           &\kws{gt}             &\text{Unsigned/Signed Greater Than}\\
              &\vert           &\kws{geq}            &\text{Unsigned/Signed Greater or Equal}\\
              &\vert           &\kws{eq}             &\text{Unsigned/Signed Equal}\\
              &\vert           &\kws{neq}            &\text{Unsigned/Signed Not-Equal}\\
              &\vert           &\kws{mux}            &\text{Unsigned/Signed/Clock Multiplex}\\
              &\vert           &\kws{pad}            &\text{Unsigned/Signed Pad to Length}\\
              &\vert           &\kws{asUInt}         &\text{Unsigned/Signed Reinterpret Bits as UInt}\\
              &\vert           &\kws{asSInt}         &\text{Unsigned/Signed Reinterpret Bits as SInt}\\
              &\vert           &\kws{shl}            &\text{Unsigned/Signed Shift Left}\\
              &\vert           &\kws{shr}            &\text{Unsigned/Signed Shift Right}\\
              &\vert           &\kws{dshl}           &\text{Unsigned/Signed Dynamic Shift Left}\\
              &\vert           &\kws{dshr}           &\text{Unsigned/Signed Dynamic Shift Right}\\
              &\vert           &\kws{cvt}            &\text{Unsigned/Signed to Signed Logical Conversion}\\
              &\vert           &\kws{neg}            &\text{Unsigned/Signed Negate}\\
              &\vert           &\kws{not}            &\text{Unsigned Not}\\
              &\vert           &\kws{and}            &\text{Unsigned And}\\
              &\vert           &\kws{or}             &\text{Unsigned Or}\\
              &\vert           &\kws{xor}            &\text{Unsigned Xor}\\
              &\vert           &\kws{andr}           &\text{Unsigned And Reduce}\\
              &\vert           &\kws{orr}            &\text{Unsigned Or Reduce}\\
              &\vert           &\kws{xorr}           &\text{Unsigned Xor Reduce}\\
              &\vert           &\kws{cat}            &\text{Unsigned Concatenation}\\
              &\vert           &\kws{bit}            &\text{Single Bit Extraction}\\
              &\vert           &\kws{bits}           &\text{Multiple Bit Extraction}\\
              &\vert           &\kws{toClock}        &\text{Interpret Unsigned Bit as Clock}\\
              &\vert           &\kws{fromClock}      &\text{Interpret Clock as Unsigned Bit}
\end{array}
}
\]

\subsection{Notation}
The above definition specifies the structure of the abstract syntax tree corresponding to a FIRRTL circuit.
Nodes in the abstract syntax tree are {\em italicized}.
Keywords are shown in {\bf bold}.
The special productions id, int, and string, indicates an identifier, an integer literal, and a string respectively.
Tokens followed by an asterisk, {\em e.g.} \pds{field}*, indicates a list formed from repeated occurrences of the token.

Keep in the mind that the above definition is only the {\em abstract} syntax tree, and is a representation of the in-memory FIRRTL data structure.
Readers and writers are provided for converting a FIRRTL data structure into a purely textual representation, which is defined in Section \ref{concrete}.


\section{Future Plans}
Some choices were made during the design of this specification which were intentionally conservative, so that future versions could lift the restrictions if suitable semantics and implementations are determined.
By restricting this version and potentially lifting these restrictions in future versions, all existing FIRRTL circuits will remain valid.

The following design decisions could potentially be changed in future spec revisions:
\begin{enumerate}[topsep=3pt,itemsep=-0.5ex,partopsep=1ex,parsep=1ex]
\item Disallowing zero-width types
\item Always expanding memories into smaller memories (if its type is a non-ground-type)
\item Not including a \kws{ROM} node
\item Custom annotations are not held in FIRRTL nodes
\item Not requiring that all names are unique
\end{enumerate}

\section{Questions and Answers}
\begin{enumerate}[topsep=3pt,itemsep=-0.5ex,partopsep=1ex,parsep=1ex]
\item Why are there three connect operators?
Each is needed for a particular use case - the better question is why did we chose to create multiple connect statements instead of other constructs.
Statements, as opposed to expressions, are very restricted in how they nest.
Thus, the desired supported behavior (partial connects, full connects, and resets) will never be used in an arbitrary nested expression where the semantics would be unintuitive.
In addition, both the implementation and the user only needs to look at the single statement to implement it.

\item Aren't there a lot of idiosyncrasies in FIRRTL?
The FIRRTL specification is an ongoing process, and as we push more code through it, it is likely to change.
In our opinion, the idiosyncrasies are necessary for a cohesive design (and all languages have idiosyncrasies).
It remains an unknown whether there are too many idiosyncrasies for frontend writers.
Because the spec is not frozen, we can certainly adapt it if necessary.
However, at this point, we just need to push more code through.

\item Why have a separate construct for initializing a register?
The problem is initializing a register with a vector/bundle type, where a subset of the fields are initialized.
If the initial value is kept with the declaration, we would need a new construct to specify a subset of values of ALL (potentially) nested vector/bundle types.
It makes much more sense to separate initialization from the declaration, and use something like a <= to initialize the fields/vector sub-components of the register.
The next question is why not just have users specify the initial value using their own "when reset :" statement.
This doesn't work because of last connect semantics - the user could easily clobber their initialization when statement without knowing.
Creating an onreset statement does two things: (1) specifies to the USER exactly what the reset value will be for any sub-component of a register, (2) encapsulates the reset value in a way that is easy for the implementation to special case it (so it doesn't get clobbered).

\item Why do operations allow inputs of differing widths? 
We tried restricting widths, but it actually complicated width inference and made supporting front-ends with more lax width restrictions very difficult.
Because there is perfectly well defined semantics, we opted to allow differing widths.
In line with the Linux "funnel" philosophy of being accepting with your inputs and restrictive with your outputs.

\item Why require all names unique?
Passes usually need unique names, so there needs to be a renaming pass somewhere.
Standardizing how names gets mangled requires a lot of thought, and we didn't feel comfortable putting this into the spec at the moment and potentially regretting it later.
For now, names have to be unique, and it is the front-end's responsibility to do this.

\item Why allow declaring components in when statements? 
We want the important property that a module is just a box of components inside - for any jumble of components, you can always lace them in the box, and it will preserve the semantics.
You need to declare wires inside whens - because generators could run within a when in a front-end.
You should always be able to pull them into a module if we want.
Now its inconsistent if you can't declare registers in the scope.

\item Why not just have LoFIRRTL?
LoFIRRTL leaves out general when usage, vector and bundle types, and requires a single connect.
For performance backends, we will need to emit arrays and structs.
If there is only a lowered circuit, we lose that ability.
We cannot simply add vector/bundle types to LoFIRRTL as front-ends cannot easily remove whens without removing the complex types as well.
Instead, one will need the expressiveness in FIRRTL to write a performant backend which does not need to operate on LoFIRRTL.

\item Why the stop statement have no arguements?
Like the enable for write-accessors, the lowering step will preserve the sequence of when statements under which a simulation will stop.

\item Why disallow zero-width wires? 
Very tricky to get the semantics correct.
On the todo list.

\item Why not require default value for wires? Isn't this a SAT problem?
We do the same thing that is done in Java, and is standard programming language practice.

\item Why did/didn't you include XXX primop?
Up for debate.

\item How do you support subword assignment?
We decided to not support subword assignment directly, and instead require the user to separate the subword assignment into a vector type. Then, the user uses the subindex expression to assign to an element in the vector.

\end{enumerate}

\end{document}