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
|
defpackage firrtl/verilog :
import core
import verse
import firrtl/ir-utils
import firrtl/ir2
;============ VERILOG ==============
public defstruct Verilog <: Pass :
with-output: (() -> False) -> False
public defmethod pass (b:Verilog) -> (Circuit -> Circuit) : emit-verilog{with-output(b),_}
public defmethod name (b:Verilog) -> String : "To Verilog"
public defmethod short-name (b:Verilog) -> String : "To Verilog"
;============ Utilz =============
defn width! (w:Width) -> Long :
match(w) :
(w:IntWidth) : to-long(width(w))
(w:LongWidth) : width(w)
(w) : error("Non-supported width type.")
defn width! (t:Type) -> Long :
match(t) :
(t:UIntType) : width!(width(t))
(t:SIntType) : width!(width(t))
(t) : error("Non-supported type.")
defn emit (w:Width) -> String :
match(w) :
(w:IntWidth) :
if width(w) >= 1 : string-join $ ["[" width(w) - 1 ":0]"] ;TODO check if need to special case 0 or 1 width wires
else : ""
(w:LongWidth) :
if width(w) >= to-long(1) : string-join $ ["[" width(w) - to-long(1) ":0]"] ;TODO check if need to special case 0 or 1 width wires
else : ""
(w) : error("Non-supported width type.")
defn get-width (t:Type) -> String :
match(t) :
(t:UIntType) : emit(width(t))
(t:SIntType) : emit(width(t))
(t:ClockType) : emit(IntWidth(1))
(t) : error("Non-supported type.")
defn remove-subfield (e:Expression) -> Expression :
match(map(remove-subfield,e)) :
(e:Subfield) : Ref(to-symbol $ string-join $ [emit(exp(e)) bundle-expand-delin name(e)],type(e))
(e) : e
defn get-name (e:Expression) -> Symbol :
match(e) :
(e:Ref) : name(e)
(e:Subfield) : error("Shouldn't be here")
(e) : error("Shouldn't be here")
;============ Verilog Backend =============
defn emit-as-type (e:Expression,t:Type) -> String :
match(t) :
(t:UIntType) : emit(e)
(t:SIntType) : string-join(["$signed(" emit(e) ")"])
defn emit-signed-if-any (e:Expression,ls:List<Expression>) -> String :
var signed? = false
for x in ls do :
if type(x) typeof SIntType : signed? = true
if not signed? : emit(e)
else :
match(type(e)) :
(t:SIntType) : string-join(["$signed(" emit(e) ")"])
(t:UIntType) : string-join(["$signed({1'b0," emit(e) "})"])
defn emit (e:Expression) -> String :
match(e) :
(e:Ref) : to-string $ name(e)
(e:UIntValue) :
val str = to-string(value(e))
val out = substring(str,1,length(str) - 1)
string-join $ [width!(type(e)) "'" out]
(e:SIntValue) : ;string-join $ [width!(type(e)) "'s" value(e)]
val str = to-string(value(e))
val out = substring(str,1,length(str) - 1)
string-join $ [width!(type(e)) "'s" out]
(e:Subfield) : error("Non-supported expression")
(e:Index) : error("Non-supported expression")
(e:DoPrim) :
;val sargs = map(emit-as-type{_,type(e)},args(e))
;val xargs = map(emit-signed-if-any{_,args(e)},args(e))
string-join $ switch {_ == op(e)} :
ADD-OP : [emit-as-type(args(e)[0],type(e)) " + " emit-as-type(args(e)[1],type(e))]
SUB-OP : [emit-as-type(args(e)[0],type(e)) " - " emit-as-type(args(e)[1],type(e))]
MUL-OP : [emit-as-type(args(e)[0],type(e)) " * " emit-as-type(args(e)[1],type(e)) ]
DIV-OP : [emit-as-type(args(e)[0],type(e)) " / " emit-as-type(args(e)[1],type(e)) ]
MOD-OP : [emit-as-type(args(e)[0],type(e)) " % " emit-as-type(args(e)[1],type(e)) ]
QUO-OP : [emit-as-type(args(e)[0],type(e)) " / " emit-as-type(args(e)[1],type(e)) ]
REM-OP : [emit-as-type(args(e)[0],type(e)) " % " emit-as-type(args(e)[1],type(e)) ]
ADD-WRAP-OP : [emit-as-type(args(e)[0],type(e)), " + " emit-as-type(args(e)[1],type(e))]
SUB-WRAP-OP : [emit-as-type(args(e)[0],type(e)), " - " emit-as-type(args(e)[1],type(e))]
LESS-OP : [emit-signed-if-any(args(e)[0],args(e)) " < " emit-signed-if-any(args(e)[1],args(e))]
LESS-EQ-OP : [emit-signed-if-any(args(e)[0],args(e)) " <= " emit-signed-if-any(args(e)[1],args(e))]
GREATER-OP : [emit-signed-if-any(args(e)[0],args(e)) " > " emit-signed-if-any(args(e)[1],args(e))]
GREATER-EQ-OP : [emit-signed-if-any(args(e)[0],args(e)) " >= " emit-signed-if-any(args(e)[1],args(e))]
NEQUIV-OP : [emit-signed-if-any(args(e)[0],args(e)) " != " emit-signed-if-any(args(e)[1],args(e))]
EQUIV-OP : [emit-signed-if-any(args(e)[0],args(e)) " == " emit-signed-if-any(args(e)[1],args(e))]
NEQUAL-OP : [emit-signed-if-any(args(e)[0],args(e)) " != " emit-signed-if-any(args(e)[1],args(e))]
EQUAL-OP : [emit-signed-if-any(args(e)[0],args(e)) " == " emit-signed-if-any(args(e)[1],args(e))]
MUX-OP :
val en = emit(args(e)[0])
[en " ? " emit-as-type(args(e)[1],type(e)) " : " emit-as-type(args(e)[2],type(e))]
PAD-OP :
val x = args(e)[0]
val w = width!(type(x))
val diff = (to-long(consts(e)[0]) - w)
if w == to-long(0) : [ emit(x) ]
else :
if type(e) typeof SIntType : ["{{" diff "{" emit(x) "[" w - to-long(1) "]}}, " emit(x) " }"]
else : ["{{" diff "'d0 }, " emit(x) " }"]
AS-UINT-OP :
["$unsigned(" emit(args(e)[0]) ")"]
AS-SINT-OP :
["$signed(" emit(args(e)[0]) ")"]
DYN-SHIFT-LEFT-OP : [emit-as-type(args(e)[0],type(e)) " << " emit(args(e)[1])]
DYN-SHIFT-RIGHT-OP :
if type(e) typeof SIntType : [emit-as-type(args(e)[0],type(e)) " >>> " emit(args(e)[1])]
else : [emit-as-type(args(e)[0],type(e)) " >> " emit(args(e)[1])]
SHIFT-LEFT-OP : [emit-as-type(args(e)[0],type(e)) " << " consts(e)[0]]
SHIFT-RIGHT-OP : [emit-as-type(args(e)[0],type(e)) "[" width!(type(args(e)[0])) - to-long(1) ":" consts(e)[0] "]"]
;if type(e) typeof SIntType : [emit-as-type(args(e)[0],type(e)) " >>> " consts(e)[0]]
;else : [emit-as-type(args(e)[0],type(e)) " >> " consts(e)[0]]
NEG-OP : ["-{" emit-as-type(args(e)[0],type(e)) "}"]
CONVERT-OP :
match(type(args(e)[0])) :
(t:UIntType) : ["{1'b0," emit-as-type(args(e)[0],type(e)) "}"]
(t:SIntType) : [emit-as-type(args(e)[0],type(e))]
BIT-NOT-OP : ["~ " emit-as-type(args(e)[0],type(e))]
BIT-AND-OP : [emit-as-type(args(e)[0],type(e)) " & " emit-as-type(args(e)[1],type(e))]
BIT-OR-OP : [emit-as-type(args(e)[0],type(e)) " | " emit-as-type(args(e)[1],type(e))]
BIT-XOR-OP : [emit-as-type(args(e)[0],type(e)) " ^ " emit-as-type(args(e)[1],type(e))]
CONCAT-OP : ["{" emit-as-type(args(e)[0],type(e)) "," emit-as-type(args(e)[1],type(e)) "}"]
BIT-SELECT-OP : [emit-as-type(args(e)[0],type(e)) "[" consts(e)[0] "]"]
BITS-SELECT-OP : [emit-as-type(args(e)[0],type(e)) "[" consts(e)[0] ":" consts(e)[1] "]"]
BIT-AND-REDUCE-OP :
var v = emit-as-type(args(e)[0],type(e))
for x in tail(args(e)) do :
v = concat(v, [" & " emit(x)])
v
BIT-OR-REDUCE-OP :
var v = emit-as-type(args(e)[0],type(e))
for x in tail(args(e)) do :
v = concat(v, [" | " emit(x)])
v
BIT-XOR-REDUCE-OP :
var v = emit-as-type(args(e)[0],type(e))
for x in tail(args(e)) do :
v = concat(v, [" ^ " emit(x)])
v
defn emit-module (m:InModule) :
val vdecs = Vector<KeyValue<Symbol,Stmt>>() ; all declarations in order, to preserve ordering
val decs = HashTable<Symbol,Stmt>(symbol-hash) ; all declarations, for fast lookups
val cons = HashTable<Symbol,Expression>(symbol-hash) ; all connections
val ens = HashTable<Symbol,Expression>(symbol-hash) ; all enables
defn build-table (m:InModule) :
defn build-table (s:Stmt) -> Stmt :
match(map(build-table,map(remove-subfield,s))) :
(s:DefWire|DefRegister|DefAccessor|DefMemory|DefNode|DefInstance) :
add(vdecs,name(s) => s)
decs[name(s)] = s
(s:Conditionally) :
val n = get-name(loc(conseq(s) as Connect))
ens[n] = pred(s)
cons[n] = exp(conseq(s) as Connect)
(s:Connect) :
val n = get-name(loc(s))
cons[n] = exp(s)
(s) : false
s
build-table(body(m))
build-table(m)
val wires = Vector<Streamable>()
val regs = Vector<Streamable>()
val inits = Vector<Streamable>()
val assigns = Vector<Streamable>()
val updates = HashTable<Symbol,Vector<Streamable>>(symbol-hash)
val insts = HashTable<Symbol,Symbol>(symbol-hash) ; inst -> module
val inst-ports = HashTable<Symbol,Vector<Streamable>>(symbol-hash)
val sh = get-sym-hash(m)
val rand-value = "$random" ;"0"
defn rand-string (w:Long) -> String : string-join(["{" ((w + to-long(31)) / to-long(32)) "{" rand-value "}};"])
for x in vdecs do :
val sym = key(x)
match(value(x)) :
(s:DefWire) :
add(wires,["wire " get-width(type(s)) " " sym ";"])
add(assigns,["assign " sym " = " emit(cons[sym]) ";"])
(s:DefRegister) :
add(regs,["reg " get-width(type(s)) " " sym ";"])
val my-clk-update = get?(updates,get-name(clock(s)),Vector<Streamable>())
if key?(ens,sym) :
add(my-clk-update,["if(" emit(ens[sym]) ") begin"])
val x = cons[sym]
val y = emit(x)
add(my-clk-update,[" " sym " <= " y ";"])
add(my-clk-update,["end"])
else :
add(my-clk-update,[sym " <= " emit(cons[sym]) ";"])
updates[get-name(clock(s))] = my-clk-update
val w = width!(type(s))
add(inits,[sym " = " rand-string(w)])
(s:DefMemory) :
val vtype = type(s) as VectorType
add(regs,["reg " get-width(type(vtype)) " " sym " [0:" size(vtype) - 1 "];"])
add(inits,["for (initvar = 0; initvar < " size(vtype) "; initvar = initvar+1)"])
add(inits,[" " sym "[initvar] = " rand-string(width!(type(vtype))) ])
(s:DefNode) :
add(wires,["wire " get-width(type(value(s))) " " sym ";"])
add(assigns,["assign " sym " = " emit(value(s)) ";"])
(s:DefInstance) :
inst-ports[sym] = Vector<Streamable>()
insts[sym] = name(module(s) as Ref)
for f in fields(type(module(s)) as BundleType) do :
val n* = to-symbol $ string-join $ [sym bundle-expand-delin name(f)]
add(wires,["wire " get-width(type(f)) " " n* ";"])
add(inst-ports[sym], ["." name(f) "( " n* " )"])
if flip(f) == REVERSE :
add(assigns,["assign " n* " = " emit(cons[n*]) ";"])
(s:DefAccessor) :
val mem-declaration = decs[name(source(s) as Ref)] as DefMemory
switch {_ == acc-dir(s)} :
READ :
if seq?(mem-declaration) :
; to make it sequential, register the index for an additional cycle
val index* = Ref(firrtl-gensym(name(index(s) as Ref),sh),type(index(s)))
add(regs,[ "reg " get-width(type(index*)) " " name(index*) ";"])
val w = width!(type(index*))
add(inits,[name(index*) " = " rand-string(w)])
val my-clk-update = get?(updates,get-name(clock(mem-declaration)),Vector<Streamable>())
add(my-clk-update,[name(index*) " <= " emit(index(s)) ";"])
updates[get-name(clock(mem-declaration))] = my-clk-update
; emit read accessor
add(wires,["wire " get-width(type(type(source(s)) as VectorType)) " " sym ";"])
add(assigns,["assign " sym " = " emit(source(s)) "[" emit(index*) "];"])
else :
; emit read accessor
add(wires,["wire " get-width(type(type(source(s)) as VectorType)) " " sym ";"])
add(assigns,["assign " sym " = " emit(source(s)) "[" emit(index(s)) "];"])
WRITE :
val my-clk-update = get?(updates,get-name(clock(mem-declaration)),Vector<Streamable>())
if key?(ens,sym) :
add(my-clk-update,["if(" emit(ens[sym]) ") begin"])
add(my-clk-update,[" " emit(source(s)) "[" emit(index(s)) "] <= " emit(cons[sym]) ";"])
add(my-clk-update,["end"])
else :
add(my-clk-update,[emit(source(s)) "[" emit(index(s)) "] <= " emit(cons[sym]) ";"])
updates[get-name(clock(mem-declaration))] = my-clk-update
;==== Actually printing module =====
val port-indent = " "
print-all(["module " name(m) "(\n"])
for (p in ports(m),i in 1 to false) do :
var end = ",\n"
if length(ports(m)) == i :
end = "\n);\n"
switch {_ == direction(p)} :
INPUT :
print-all([port-indent "input " get-width(type(p)) " " name(p) end])
OUTPUT :
print-all([port-indent "output " get-width(type(p)) " " name(p) end])
add(assigns,["assign " name(p) " = " emit(cons[name(p)]) ";"])
if length(ports(m)) == 0 : print(");\n")
for w in wires do :
print(" ")
println-all(w)
for r in regs do :
print(" ")
println-all(r)
if length(inits) != 0 :
println("`ifndef SYNTHESIS")
println(" integer initvar;")
println(" initial begin")
println(" #0.002;")
for i in inits do :
print-all(" ")
println-all(i)
println(" end")
println("`endif")
for a in assigns do :
print(" ")
println-all(a)
for x in insts do :
println-all([" " value(x) " " key(x) " ("])
;print-all([".clk( clk )"])
for (y in inst-ports[key(x)],i in 1 to false) do :
print(" ")
print-all(y)
if length(inst-ports[key(x)]) != i :
print(",\n")
println("\n );")
for x in updates do :
if length(value(x)) != 0 :
println-all([" always @(posedge " key(x) ") begin"])
for u in value(x) do :
print(" ")
println-all(u)
println(" end")
println("endmodule")
public defn emit-verilog (with-output:(() -> False) -> False, c:Circuit) :
with-output $ fn () :
for m in modules(c) do :
match(m) :
(m:InModule) : emit-module(m)
(m:ExModule) : false
c
|