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
|
// SPDX-License-Identifier: Apache-2.0
package firrtl
package proto
import java.io.OutputStream
import FirrtlProtos._
import Firrtl.Statement.{Formal, ReadUnderWrite}
import Firrtl.Expression.PrimOp.Op
import com.google.protobuf.{CodedOutputStream, WireFormat}
import firrtl.PrimOps._
import scala.collection.JavaConverters._
object ToProto {
/** Serialize a FIRRTL Circuit to an Output Stream as a ProtoBuf message
*
* @param ostream Output stream that will be written
* @param circuit The Circuit to serialize
*/
def writeToStream(ostream: OutputStream, circuit: ir.Circuit): Unit = {
writeToStreamFast(ostream, circuit.info, circuit.modules.map(() => _), circuit.main)
}
/** Serialized a deconstructed Circuit with lazy Modules
*
* This serializer allows intermediate objects to be garbage collected during serialization
* to save time and memory
*
* @param ostream Output stream that will be written
* @param info Info of Circuit
* @param modules Functions to generate Modules lazily
* @param main Top-level module of the Circuit
*/
// Note this function is sensitive to changes to the Firrtl and Circuit protobuf message definitions
def writeToStreamFast(
ostream: OutputStream,
info: ir.Info,
modules: Seq[() => ir.DefModule],
main: String
): Unit = {
val costream = CodedOutputStream.newInstance(ostream)
// Write each module for the circuit
val ostreamInner = new java.io.ByteArrayOutputStream()
val costreamInner = CodedOutputStream.newInstance(ostreamInner)
for (mod <- modules) {
costreamInner.writeMessage(Firrtl.Circuit.MODULE_FIELD_NUMBER, convert(mod()).build)
}
val top = Firrtl.Top.newBuilder().setName(main).build
costreamInner.writeMessage(Firrtl.Circuit.TOP_FIELD_NUMBER, top)
// Write Circuit header first
costream.writeTag(Firrtl.CIRCUIT_FIELD_NUMBER, WireFormat.WIRETYPE_LENGTH_DELIMITED)
costream.writeUInt32NoTag(costreamInner.getTotalBytesWritten)
costream.flush()
// Write Modules
costreamInner.flush()
ostreamInner.writeTo(ostream)
ostreamInner.flush()
}
val convert: Map[ir.PrimOp, Op] = Map(
Add -> Op.OP_ADD,
Sub -> Op.OP_SUB,
Mul -> Op.OP_TIMES,
Div -> Op.OP_DIVIDE,
Rem -> Op.OP_REM,
Lt -> Op.OP_LESS,
Leq -> Op.OP_LESS_EQ,
Gt -> Op.OP_GREATER,
Geq -> Op.OP_GREATER_EQ,
Eq -> Op.OP_EQUAL,
Neq -> Op.OP_NOT_EQUAL,
Pad -> Op.OP_PAD,
AsUInt -> Op.OP_AS_UINT,
AsSInt -> Op.OP_AS_SINT,
AsClock -> Op.OP_AS_CLOCK,
AsFixedPoint -> Op.OP_AS_FIXED_POINT,
AsAsyncReset -> Op.OP_AS_ASYNC_RESET,
Shl -> Op.OP_SHIFT_LEFT,
Shr -> Op.OP_SHIFT_RIGHT,
Dshl -> Op.OP_DYNAMIC_SHIFT_LEFT,
Dshr -> Op.OP_DYNAMIC_SHIFT_RIGHT,
Cvt -> Op.OP_CONVERT,
Neg -> Op.OP_NEG,
Not -> Op.OP_BIT_NOT,
And -> Op.OP_BIT_AND,
Or -> Op.OP_BIT_OR,
Xor -> Op.OP_BIT_XOR,
Andr -> Op.OP_AND_REDUCE,
Orr -> Op.OP_OR_REDUCE,
Xorr -> Op.OP_XOR_REDUCE,
Cat -> Op.OP_CONCAT,
Bits -> Op.OP_EXTRACT_BITS,
Head -> Op.OP_HEAD,
Tail -> Op.OP_TAIL,
IncP -> Op.OP_INCREASE_PRECISION,
DecP -> Op.OP_DECREASE_PRECISION,
SetP -> Op.OP_SET_PRECISION,
AsInterval -> Op.OP_AS_INTERVAL,
Squeeze -> Op.OP_SQUEEZE,
Wrap -> Op.OP_WRAP,
Clip -> Op.OP_CLIP
)
def convert(ruw: ir.ReadUnderWrite.Value): ReadUnderWrite = ruw match {
case ir.ReadUnderWrite.Undefined => ReadUnderWrite.UNDEFINED
case ir.ReadUnderWrite.Old => ReadUnderWrite.OLD
case ir.ReadUnderWrite.New => ReadUnderWrite.NEW
}
def convert(formal: ir.Formal.Value): Formal = formal match {
case ir.Formal.Assert => Formal.ASSERT
case ir.Formal.Assume => Formal.ASSUME
case ir.Formal.Cover => Formal.COVER
}
def convertToIntegerLiteral(value: BigInt): Firrtl.Expression.IntegerLiteral.Builder = {
Firrtl.Expression.IntegerLiteral
.newBuilder()
.setValue(value.toString)
}
def convertToBigInt(value: BigInt): Firrtl.BigInt.Builder = {
Firrtl.BigInt
.newBuilder()
.setValue(com.google.protobuf.ByteString.copyFrom(value.toByteArray))
}
def convert(info: ir.Info): Firrtl.SourceInfo.Builder = {
val ib = Firrtl.SourceInfo.newBuilder()
info match {
case ir.NoInfo =>
ib.setNone(Firrtl.SourceInfo.None.newBuilder)
case f: ir.FileInfo =>
ib.setText(f.unescaped)
// TODO properly implement MultiInfo
case ir.MultiInfo(infos) =>
val x = if (infos.nonEmpty) infos.head else ir.NoInfo
convert(x)
}
}
def convert(expr: ir.Expression): Firrtl.Expression.Builder = {
val eb = Firrtl.Expression.newBuilder()
expr match {
case ir.Reference(name, _, _, _) =>
val rb = Firrtl.Expression.Reference
.newBuilder()
.setId(name)
eb.setReference(rb)
case ir.SubField(e, name, _, _) =>
val sb = Firrtl.Expression.SubField
.newBuilder()
.setExpression(convert(e))
.setField(name)
eb.setSubField(sb)
case ir.SubIndex(e, value, _, _) =>
val sb = Firrtl.Expression.SubIndex
.newBuilder()
.setExpression(convert(e))
.setIndex(convertToIntegerLiteral(value))
eb.setSubIndex(sb)
case ir.SubAccess(e, index, _, _) =>
val sb = Firrtl.Expression.SubAccess
.newBuilder()
.setExpression(convert(e))
.setIndex(convert(index))
eb.setSubAccess(sb)
case ir.UIntLiteral(value, width) =>
val ub = Firrtl.Expression.UIntLiteral
.newBuilder()
.setValue(convertToIntegerLiteral(value))
convert(width).foreach(ub.setWidth)
eb.setUintLiteral(ub)
case ir.SIntLiteral(value, width) =>
val sb = Firrtl.Expression.SIntLiteral
.newBuilder()
.setValue(convertToIntegerLiteral(value))
convert(width).foreach(sb.setWidth)
eb.setSintLiteral(sb)
case ir.FixedLiteral(value, width, point) =>
val fb = Firrtl.Expression.FixedLiteral
.newBuilder()
.setValue(convertToBigInt(value))
convert(width).foreach(fb.setWidth)
convert(point).foreach(fb.setPoint)
eb.setFixedLiteral(fb)
case ir.DoPrim(op, args, consts, _) =>
val db = Firrtl.Expression.PrimOp
.newBuilder()
.setOp(convert(op))
consts.foreach(c => db.addConst(convertToIntegerLiteral(c)))
args.foreach(a => db.addArg(convert(a)))
eb.setPrimOp(db)
case ir.Mux(cond, tval, fval, _) =>
val mb = Firrtl.Expression.Mux
.newBuilder()
.setCondition(convert(cond))
.setTValue(convert(tval))
.setFValue(convert(fval))
eb.setMux(mb)
case ir.ValidIf(cond, value, _) =>
val vb = Firrtl.Expression.ValidIf
.newBuilder()
.setCondition(convert(cond))
.setValue(convert(value))
eb.setValidIf(vb)
}
}
def convert(dir: MPortDir): Firrtl.Statement.MemoryPort.Direction = {
import Firrtl.Statement.MemoryPort.Direction._
dir match {
case MInfer => MEMORY_PORT_DIRECTION_INFER
case MRead => MEMORY_PORT_DIRECTION_READ
case MWrite => MEMORY_PORT_DIRECTION_WRITE
case MReadWrite => MEMORY_PORT_DIRECTION_READ_WRITE
}
}
def convert(tpe: ir.Type, depth: BigInt): Firrtl.Statement.CMemory.TypeAndDepth.Builder =
Firrtl.Statement.CMemory.TypeAndDepth
.newBuilder()
.setDataType(convert(tpe))
.setDepth(convertToBigInt(depth))
def convert(stmt: ir.Statement): Seq[Firrtl.Statement.Builder] = {
stmt match {
case ir.Block(stmts) => stmts.flatMap(convert(_))
case ir.EmptyStmt => Seq.empty
case other =>
val sb = Firrtl.Statement.newBuilder()
other match {
case ir.DefNode(_, name, expr) =>
val nb = Firrtl.Statement.Node
.newBuilder()
.setId(name)
.setExpression(convert(expr))
sb.setNode(nb)
case ir.DefWire(_, name, tpe) =>
val wb = Firrtl.Statement.Wire
.newBuilder()
.setId(name)
.setType(convert(tpe))
sb.setWire(wb)
case ir.DefRegister(_, name, tpe, clock, reset, init) =>
val rb = Firrtl.Statement.Register
.newBuilder()
.setId(name)
.setType(convert(tpe))
.setClock(convert(clock))
.setReset(convert(reset))
.setInit(convert(init))
sb.setRegister(rb)
case ir.DefInstance(_, name, module, _) =>
val ib = Firrtl.Statement.Instance
.newBuilder()
.setId(name)
.setModuleId(module)
sb.setInstance(ib)
case ir.Connect(_, loc, expr) =>
val cb = Firrtl.Statement.Connect
.newBuilder()
.setLocation(convert(loc))
.setExpression(convert(expr))
sb.setConnect(cb)
case ir.PartialConnect(_, loc, expr) =>
val cb = Firrtl.Statement.PartialConnect
.newBuilder()
.setLocation(convert(loc))
.setExpression(convert(expr))
sb.setPartialConnect(cb)
case ir.Conditionally(_, pred, conseq, alt) =>
val cs = convert(conseq)
val as = convert(alt)
val wb = Firrtl.Statement.When
.newBuilder()
.setPredicate(convert(pred))
cs.foreach(wb.addConsequent)
as.foreach(wb.addOtherwise)
sb.setWhen(wb)
case ir.Print(_, string, args, clk, en) =>
val pb = Firrtl.Statement.Printf
.newBuilder()
.setValue(string.string)
.setClk(convert(clk))
.setEn(convert(en))
args.foreach(a => pb.addArg(convert(a)))
sb.setPrintf(pb)
case ir.Stop(_, ret, clk, en) =>
val stopb = Firrtl.Statement.Stop
.newBuilder()
.setReturnValue(ret)
.setClk(convert(clk))
.setEn(convert(en))
sb.setStop(stopb)
case ir.Verification(op, _, clk, cond, en, msg) =>
val vb = Firrtl.Statement.Verification
.newBuilder()
.setOp(convert(op))
.setClk(convert(clk))
.setCond(convert(cond))
.setEn(convert(en))
.setMsg(msg.string)
sb.setVerification(vb)
case ir.IsInvalid(_, expr) =>
val ib = Firrtl.Statement.IsInvalid
.newBuilder()
.setExpression(convert(expr))
sb.setIsInvalid(ib)
case ir.DefMemory(_, name, dtype, depth, wlat, rlat, rs, ws, rws, ruw) =>
val mem = Firrtl.Statement.Memory
.newBuilder()
.setId(name)
.setType(convert(dtype))
.setBigintDepth(convertToBigInt(depth))
.setWriteLatency(wlat)
.setReadLatency(rlat)
.setReadUnderWrite(convert(ruw))
mem.addAllReaderId(rs.asJava)
mem.addAllWriterId(ws.asJava)
mem.addAllReadwriterId(rws.asJava)
sb.setMemory(mem)
case CDefMemory(_, name, tpe, size, seq, ruw) =>
val mb = Firrtl.Statement.CMemory
.newBuilder()
.setId(name)
.setTypeAndDepth(convert(tpe, size))
.setSyncRead(seq)
.setReadUnderWrite(convert(ruw))
sb.setCmemory(mb)
case CDefMPort(_, name, _, mem, exprs, dir) =>
val pb = Firrtl.Statement.MemoryPort
.newBuilder()
.setId(name)
.setMemoryId(mem)
.setMemoryIndex(convert(exprs.head))
.setExpression(convert(exprs(1)))
.setDirection(convert(dir))
sb.setMemoryPort(pb)
case ir.Attach(_, exprs) =>
val ab = Firrtl.Statement.Attach.newBuilder()
exprs.foreach(e => ab.addExpression(convert(e)))
sb.setAttach(ab)
}
stmt match {
case hasInfo: ir.HasInfo => sb.setSourceInfo(convert(hasInfo.info))
case _ => // Do nothing
}
Seq(sb)
}
}
def convert(field: ir.Field): Firrtl.Type.BundleType.Field.Builder = {
val b = Firrtl.Type.BundleType.Field
.newBuilder()
.setId(field.name)
.setIsFlipped(field.flip == ir.Flip)
.setType(convert(field.tpe))
b
}
/** Converts a Width to a ProtoBuf Width Builder
*
* @param width Input width
* @return Option width where None means the width field should be cleared in the parent object
*/
def convert(width: ir.Width): Option[Firrtl.Width.Builder] = width match {
case ir.IntWidth(w) => Some(Firrtl.Width.newBuilder().setValue(w.toInt))
case ir.UnknownWidth => None
}
def convert(vtpe: ir.VectorType): Firrtl.Type.VectorType.Builder =
Firrtl.Type.VectorType
.newBuilder()
.setType(convert(vtpe.tpe))
.setSize(vtpe.size)
def convert(tpe: ir.Type): Firrtl.Type.Builder = {
val tb = Firrtl.Type.newBuilder()
tpe match {
case ir.UIntType(width) =>
val ut = Firrtl.Type.UIntType.newBuilder()
convert(width).foreach(ut.setWidth)
tb.setUintType(ut)
case ir.SIntType(width) =>
val st = Firrtl.Type.SIntType.newBuilder()
convert(width).foreach(st.setWidth)
tb.setSintType(st)
case ir.FixedType(width, point) =>
val ft = Firrtl.Type.FixedType.newBuilder()
convert(width).foreach(ft.setWidth)
convert(point).foreach(ft.setPoint)
tb.setFixedType(ft)
case ir.ClockType =>
val ct = Firrtl.Type.ClockType.newBuilder()
tb.setClockType(ct)
case ir.AsyncResetType =>
val at = Firrtl.Type.AsyncResetType.newBuilder()
tb.setAsyncResetType(at)
case ir.ResetType =>
val rt = Firrtl.Type.ResetType.newBuilder()
tb.setResetType(rt)
case ir.AnalogType(width) =>
val at = Firrtl.Type.AnalogType.newBuilder()
convert(width).foreach(at.setWidth)
tb.setAnalogType(at)
case ir.BundleType(fields) =>
val bt = Firrtl.Type.BundleType.newBuilder()
fields.foreach(f => bt.addField(convert(f)))
tb.setBundleType(bt)
case vtpe: ir.VectorType =>
val vtb = convert(vtpe)
tb.setVectorType(vtb)
}
}
def convert(direction: ir.Direction): Firrtl.Port.Direction = direction match {
case ir.Input => Firrtl.Port.Direction.PORT_DIRECTION_IN
case ir.Output => Firrtl.Port.Direction.PORT_DIRECTION_OUT
}
def convert(port: ir.Port): Firrtl.Port.Builder = {
Firrtl.Port
.newBuilder()
.setId(port.name)
.setDirection(convert(port.direction))
.setType(convert(port.tpe))
}
def convert(param: ir.Param): Firrtl.Module.ExternalModule.Parameter.Builder = {
import Firrtl.Module.ExternalModule._
val pb = Parameter
.newBuilder()
.setId(param.name)
param match {
case ir.IntParam(_, value) =>
pb.setInteger(convertToBigInt(value))
case ir.DoubleParam(_, value) =>
pb.setDouble(value)
case ir.StringParam(_, ir.StringLit(value)) =>
pb.setString(value)
case ir.RawStringParam(_, value) =>
pb.setRawString(value)
}
}
def convert(module: ir.DefModule): Firrtl.Module.Builder = {
val ports = module.ports.map(convert(_))
val b = Firrtl.Module.newBuilder()
module match {
case mod: ir.Module =>
val stmts = convert(mod.body)
val mb = Firrtl.Module.UserModule
.newBuilder()
.setId(mod.name)
ports.foreach(mb.addPort)
stmts.foreach(mb.addStatement)
b.setUserModule(mb)
case ext: ir.ExtModule =>
val eb = Firrtl.Module.ExternalModule
.newBuilder()
.setId(ext.name)
.setDefinedName(ext.defname)
ports.foreach(eb.addPort)
val params = ext.params.map(convert(_))
params.foreach(eb.addParameter)
b.setExternalModule(eb)
}
}
def convert(circuit: ir.Circuit): Firrtl = {
val moduleBuilders = circuit.modules.map(convert(_))
val cb = Firrtl.Circuit.newBuilder
.addTop(Firrtl.Top.newBuilder().setName(circuit.main))
for (m <- moduleBuilders) {
cb.addModule(m)
}
Firrtl
.newBuilder()
.addCircuit(cb.build())
.build()
}
}
|