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
|
// Utility functions for FIRRTL IR
/* TODO
* - Adopt style more similar to Chisel3 Emitter?
* - Find way to have generic map function instead of mapE and mapS under Stmt implicits
*/
/* TODO Richard
* - add new IR nodes to all Util functions
*/
package firrtl
import scala.collection.mutable.StringBuilder
import java.io.PrintWriter
import PrimOps._
import scala.collection.mutable.ArrayBuffer
//import scala.reflect.runtime.universe._
object Utils {
// Is there a more elegant way to do this?
private type FlagMap = Map[String, Boolean]
private val FlagMap = Map[String, Boolean]().withDefaultValue(false)
val lnOf2 = scala.math.log(2) // natural log of 2
def ceil_log2(x: BigInt): BigInt = (x-1).bitLength
val gen_names = Map[String,Int]()
val delin = "_"
def BoolType () = { UIntType(IntWidth(1)) }
def firrtl_gensym (s:String):String = {
firrtl_gensym(s,Map[String,Int]())
}
def firrtl_gensym (sym_hash:Map[String,Int]):String = {
firrtl_gensym("gen",sym_hash)
}
def firrtl_gensym (s:String,sym_hash:Map[String,Int]):String = {
if (sym_hash contains s) {
val num = sym_hash(s) + 1
sym_hash + (s -> num)
(s + delin + num)
} else {
sym_hash + (s -> 0)
(s + delin + 0)
}
}
def create_mask (dt:Type) : Type = {
dt match {
case t:VectorType => VectorType(create_mask(t.tpe),t.size)
case t:BundleType => {
val fieldss = t.fields.map { f => Field(f.name,f.flip,create_mask(f.tpe)) }
BundleType(fieldss)
}
case t:UIntType => BoolType()
case t:SIntType => BoolType()
}
}
//============== TYPES ================
def mux_type_and_widths (e1:Expression,e2:Expression) : Type = mux_type_and_widths(tpe(e1),tpe(e2))
def mux_type_and_widths (t1:Type,t2:Type) : Type = {
def wmax (w1:Width,w2:Width) : Width = {
(w1,w2) match {
case (w1:IntWidth,w2:IntWidth) => IntWidth(w1.width.max(w2.width))
case (w1,w2) => MaxWidth(Seq(w1,w2))
}
}
if (equals(t1,t2)) {
(t1,t2) match {
case (t1:UIntType,t2:UIntType) => UIntType(wmax(t1.width,t2.width))
case (t1:SIntType,t2:SIntType) => SIntType(wmax(t1.width,t2.width))
case (t1:VectorType,t2:VectorType) => VectorType(mux_type_and_widths(t1.tpe,t2.tpe),t1.size)
case (t1:BundleType,t2:BundleType) => BundleType((t1.fields zip t2.fields).map{case (f1, f2) => Field(f1.name,f1.flip,mux_type_and_widths(f1.tpe,f2.tpe))})
}
} else UnknownType()
}
def module_type (m:Module) : Type = {
BundleType(m.ports.map(p => p.toField))
}
def sub_type (v:Type) : Type = {
v match {
case v:VectorType => v.tpe
case v => UnknownType()
}
}
def field_type (v:Type,s:String) : Type = {
v match {
case v:BundleType => {
val ft = v.fields.find(p => p.name == s)
ft match {
case ft:Some[Field] => ft.get.tpe
case ft => UnknownType()
}
}
case v => UnknownType()
}
}
//=====================================
def widthBANG (t:Type) : Width = {
t match {
case t:UIntType => t.width
case t:SIntType => t.width
case t:ClockType => IntWidth(1)
case t => error("No width!")
}
}
// =================================
def error(str:String) = throw new FIRRTLException(str)
def debug(node: AST)(implicit flags: FlagMap): String = {
if (!flags.isEmpty) {
var str = ""
if (flags("types")) {
val tpe = node.getType
tpe match {
case t:UnknownType => str += s"@<t:${tpe.wipeWidth.serialize}>"
}
}
str
}
else {
""
}
}
implicit class BigIntUtils(bi: BigInt){
def serialize(implicit flags: FlagMap = FlagMap): String =
"\"h" + bi.toString(16) + "\""
}
implicit class ASTUtils(ast: AST) {
def getType(): Type =
ast match {
case e: Expression => e.getType
case s: Stmt => s.getType
//case f: Field => f.getType
case t: Type => t.getType
case p: Port => p.getType
case _ => UnknownType()
}
}
implicit class PrimOpUtils(op: PrimOp) {
def serialize(implicit flags: FlagMap = FlagMap): String = op.getString
}
// =============== EXPANSION FUNCTIONS ================
def get_size (t:Type) : Int = {
t match {
case (t:BundleType) => {
var sum = 0
for (f <- t.fields) {
sum = sum + get_size(f.tpe)
}
sum
}
case (t:VectorType) => t.size * get_size(t.tpe)
case (t) => 1
}
}
def get_valid_points (t1:Type,t2:Type,flip1:Flip,flip2:Flip) : Seq[(Int,Int)] = {
//;println_all(["Inside with t1:" t1 ",t2:" t2 ",f1:" flip1 ",f2:" flip2])
(t1,t2) match {
case (t1:UIntType,t2:UIntType) => if (flip1 == flip2) Seq((0, 0)) else Seq()
case (t1:SIntType,t2:SIntType) => if (flip1 == flip2) Seq((0, 0)) else Seq()
case (t1:BundleType,t2:BundleType) => {
val points = ArrayBuffer[(Int,Int)]()
var ilen = 0
var jlen = 0
for (i <- 0 until t1.fields.size) {
for (j <- 0 until t2.fields.size) {
val f1 = t1.fields(i)
val f2 = t2.fields(j)
if (f1.name == f2.name) {
val ls = get_valid_points(f1.tpe,f2.tpe,times(flip1, f1.flip),times(flip2, f2.flip))
for (x <- ls) {
points += ((x._1 + ilen, x._2 + jlen))
}
}
jlen = jlen + get_size(t2.fields(j).tpe)
}
ilen = ilen + get_size(t1.fields(i).tpe)
jlen = 0
}
points
}
case (t1:VectorType,t2:VectorType) => {
val points = ArrayBuffer[(Int,Int)]()
var ilen = 0
var jlen = 0
for (i <- 0 until scala.math.min(t1.size,t2.size)) {
val ls = get_valid_points(t1.tpe,t2.tpe,flip1,flip2)
for (x <- ls) {
val y = ((x._1 + ilen), (x._2 + jlen))
points += y
}
ilen = ilen + get_size(t1.tpe)
jlen = jlen + get_size(t2.tpe)
}
points
}
}
}
// =========== GENDER/FLIP UTILS ============
def swap (g:Gender) : Gender = {
g match {
case UNKNOWNGENDER => UNKNOWNGENDER
case MALE => FEMALE
case FEMALE => MALE
case BIGENDER => BIGENDER
}
}
def swap (d:Direction) : Direction = {
d match {
case OUTPUT => INPUT
case INPUT => OUTPUT
}
}
def swap (f:Flip) : Flip = {
f match {
case DEFAULT => REVERSE
case REVERSE => DEFAULT
}
}
def to_gender (d:Direction) : Gender = {
d match {
case INPUT => MALE
case OUTPUT => FEMALE
}
}
def field_flip (v:Type,s:String) : Flip = {
v match {
case v:BundleType => {
val ft = v.fields.find {p => p.name == s}
ft match {
case ft:Some[Field] => ft.get.flip
case ft => DEFAULT
}
}
case v => DEFAULT
}
}
def get_field (v:Type,s:String) : Field = {
v match {
case v:BundleType => {
val ft = v.fields.find {p => p.name == s}
ft match {
case ft:Some[Field] => ft.get
case ft => error("Shouldn't be here"); Field("blah",DEFAULT,UnknownType())
}
}
case v => error("Shouldn't be here"); Field("blah",DEFAULT,UnknownType())
}
}
def times (flip:Flip,d:Direction) : Direction = times(flip, d)
def times (d:Direction,flip:Flip) : Direction = {
flip match {
case DEFAULT => d
case REVERSE => swap(d)
}
}
def times (g:Gender,flip:Flip) : Gender = times(flip, g)
def times (flip:Flip,g:Gender) : Gender = {
flip match {
case DEFAULT => g
case REVERSE => swap(g)
}
}
def times (f1:Flip,f2:Flip) : Flip = {
f2 match {
case DEFAULT => f1
case REVERSE => swap(f1)
}
}
// =========== ACCESSORS =========
def gender (e:Expression) : Gender = {
e match {
case e:WRef => gender(e)
case e:WSubField => gender(e)
case e:WSubIndex => gender(e)
case e:WSubAccess => gender(e)
case e:PrimOp => MALE
case e:UIntValue => MALE
case e:SIntValue => MALE
case e:Mux => MALE
case e:ValidIf => MALE
case _ => error("Shouldn't be here")
}}
def get_gender (s:Stmt) : Gender =
s match {
case s:DefWire => BIGENDER
case s:DefRegister => BIGENDER
case s:WDefInstance => MALE
case s:DefNode => MALE
case s:DefInstance => MALE
case s:DefPoison => UNKNOWNGENDER
case s:DefMemory => MALE
case s:Begin => UNKNOWNGENDER
case s:Connect => UNKNOWNGENDER
case s:BulkConnect => UNKNOWNGENDER
case s:Stop => UNKNOWNGENDER
case s:Print => UNKNOWNGENDER
case s:Empty => UNKNOWNGENDER
case s:IsInvalid => UNKNOWNGENDER
}
def get_gender (p:Port) : Gender =
if (p.direction == INPUT) MALE else FEMALE
def kind (e:Expression) : Kind =
e match {
case e:WRef => e.kind
case e:WSubField => kind(e.exp)
case e:WSubIndex => kind(e.exp)
case e => ExpKind()
}
def tpe (e:Expression) : Type =
e match {
case e:WRef => e.tpe
case e:WSubField => e.tpe
case e:WSubIndex => e.tpe
case e:WSubAccess => e.tpe
case e:DoPrim => e.tpe
case e:Mux => e.tpe
case e:ValidIf => e.tpe
case e:UIntValue => UIntType(e.width)
case e:SIntValue => SIntType(e.width)
case e:WVoid => UnknownType()
case e:WInvalid => UnknownType()
}
def get_type (s:Stmt) : Type = {
s match {
case s:DefWire => s.tpe
case s:DefPoison => s.tpe
case s:DefRegister => s.tpe
case s:DefNode => tpe(s.value)
case s:DefMemory => {
val depth = s.depth
val addr = Field("addr",DEFAULT,UIntType(IntWidth(ceil_log2(depth))))
val en = Field("en",DEFAULT,BoolType())
val clk = Field("clk",DEFAULT,ClockType())
val def_data = Field("data",DEFAULT,s.data_type)
val rev_data = Field("data",REVERSE,s.data_type)
val mask = Field("mask",DEFAULT,create_mask(s.data_type))
val wmode = Field("wmode",DEFAULT,UIntType(IntWidth(1)))
val rdata = Field("rdata",REVERSE,s.data_type)
val read_type = BundleType(Seq(rev_data,addr,en,clk))
val write_type = BundleType(Seq(def_data,mask,addr,en,clk))
val readwrite_type = BundleType(Seq(wmode,rdata,def_data,mask,addr,en,clk))
val mem_fields = ArrayBuffer[Field]()
s.readers.foreach {x => mem_fields += Field(x,REVERSE,read_type)}
s.writers.foreach {x => mem_fields += Field(x,REVERSE,write_type)}
s.readwriters.foreach {x => mem_fields += Field(x,REVERSE,readwrite_type)}
BundleType(mem_fields)
}
case s:DefInstance => UnknownType()
case _ => UnknownType()
}}
// =============== MAPPERS ===================
def sMap(f:Stmt => Stmt, stmt: Stmt): Stmt =
stmt match {
case w: Conditionally => Conditionally(w.info, w.pred, f(w.conseq), f(w.alt))
case b: Begin => Begin(b.stmts.map(f))
case s: Stmt => s
}
def eMap(f:Expression => Expression, stmt:Stmt) : Stmt =
stmt match {
case r: DefRegister => DefRegister(r.info, r.name, r.tpe, f(r.clock), f(r.reset), f(r.init))
case n: DefNode => DefNode(n.info, n.name, f(n.value))
case c: Connect => Connect(c.info, f(c.loc), f(c.exp))
case b: BulkConnect => BulkConnect(b.info, f(b.loc), f(b.exp))
case w: Conditionally => Conditionally(w.info, f(w.pred), w.conseq, w.alt)
case i: IsInvalid => IsInvalid(i.info, f(i.exp))
case s: Stop => Stop(s.info, s.ret, f(s.clk), f(s.en))
case p: Print => Print(p.info, p.string, p.args.map(f), f(p.clk), f(p.en))
case s: Stmt => s
}
def eMap(f: Expression => Expression, exp:Expression): Expression =
exp match {
case s: SubField => SubField(f(s.exp), s.name, s.tpe)
case s: SubIndex => SubIndex(f(s.exp), s.value, s.tpe)
case s: SubAccess => SubAccess(f(s.exp), f(s.index), s.tpe)
case m: Mux => Mux(f(m.cond), f(m.tval), f(m.fval), m.tpe)
case v: ValidIf => ValidIf(f(v.cond), f(v.value), v.tpe)
case p: DoPrim => DoPrim(p.op, p.args.map(f), p.consts, p.tpe)
case s: WSubField => WSubField(f(s.exp), s.name, s.tpe, s.gender)
case s: WSubIndex => WSubIndex(f(s.exp), s.value, s.tpe, s.gender)
case s: WSubAccess => WSubAccess(f(s.exp), f(s.index), s.tpe, s.gender)
case e: Expression => e
}
def tMap (f: Type => Type, t:Type):Type = {
t match {
case t:BundleType => BundleType(t.fields.map(p => Field(p.name, p.flip, f(p.tpe))))
case t:VectorType => VectorType(f(t.tpe), t.size)
case t => t
}
}
def tMap (f: Type => Type, c:Expression) : Expression = {
c match {
case c:DoPrim => DoPrim(c.op,c.args,c.consts,f(c.tpe))
case c:Mux => Mux(c.cond,c.tval,c.fval,f(c.tpe))
case c:ValidIf => ValidIf(c.cond,c.value,f(c.tpe))
case c:WRef => WRef(c.name,f(c.tpe),c.kind,c.gender)
case c:WSubField => WSubField(c.exp,c.name,f(c.tpe),c.gender)
case c:WSubIndex => WSubIndex(c.exp,c.value,f(c.tpe),c.gender)
case c:WSubAccess => WSubAccess(c.exp,c.index,f(c.tpe),c.gender)
case c => c
}
}
def tMap (f: Type => Type, c:Stmt) : Stmt = {
c match {
case c:DefPoison => DefPoison(c.info,c.name,f(c.tpe))
case c:DefWire => DefWire(c.info,c.name,f(c.tpe))
case c:DefRegister => DefRegister(c.info,c.name,f(c.tpe),c.clock,c.reset,c.init)
case c:DefMemory => DefMemory(c.info,c.name, f(c.data_type), c.depth, c.write_latency, c.read_latency, c.readers, c.writers, c.readwriters)
case c => c
}
}
def wMap (f: Width => Width, c:Expression) : Expression = {
c match {
case c:UIntValue => UIntValue(c.value,f(c.width))
case c:SIntValue => SIntValue(c.value,f(c.width))
case c => c
}
}
def wMap (f: Width => Width, c:Type) : Type = {
c match {
case c:UIntType => UIntType(f(c.width))
case c:SIntType => SIntType(f(c.width))
case c => c
}
}
def wMap (f: Width => Width, w:Width) : Width = {
w match {
case w:MaxWidth => MaxWidth(w.args.map(f))
case w:MinWidth => MinWidth(w.args.map(f))
case w:PlusWidth => PlusWidth(f(w.arg1),f(w.arg2))
case w:MinusWidth => MinusWidth(f(w.arg1),f(w.arg2))
case w:ExpWidth => ExpWidth(f(w.arg1))
case w => w
}
}
val ONE = IntWidth(1)
//private trait StmtMagnet {
// def map(stmt: Stmt): Stmt
//}
//private object StmtMagnet {
// implicit def forStmt(f: Stmt => Stmt) = new StmtMagnet {
// override def map(stmt: Stmt): Stmt =
// stmt match {
// case w: Conditionally => Conditionally(w.info, w.pred, f(w.conseq), f(w.alt))
// case b: Begin => Begin(b.stmts.map(f))
// case s: Stmt => s
// }
// }
// implicit def forExp(f: Expression => Expression) = new StmtMagnet {
// override def map(stmt: Stmt): Stmt =
// stmt match {
// case r: DefRegister => DefRegister(r.info, r.name, r.tpe, f(r.clock), f(r.reset), f(r.init))
// case n: DefNode => DefNode(n.info, n.name, f(n.value))
// case c: Connect => Connect(c.info, f(c.loc), f(c.exp))
// case b: BulkConnect => BulkConnect(b.info, f(b.loc), f(b.exp))
// case w: Conditionally => Conditionally(w.info, f(w.pred), w.conseq, w.alt)
// case i: IsInvalid => IsInvalid(i.info, f(i.exp))
// case s: Stop => Stop(s.info, s.ret, f(s.clk), f(s.en))
// case p: Print => Print(p.info, p.string, p.args.map(f), f(p.clk), f(p.en))
// case s: Stmt => s
// }
// }
//}
implicit class ExpUtils(exp: Expression) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
val ret = exp match {
case v: UIntValue => s"UInt${v.width.serialize}(${v.value.serialize})"
case v: SIntValue => s"SInt${v.width.serialize}(${v.value.serialize})"
case r: Ref => r.name
case s: SubField => s"${s.exp.serialize}.${s.name}"
case s: SubIndex => s"${s.exp.serialize}[${s.value}]"
case s: SubAccess => s"${s.exp.serialize}[${s.index.serialize}]"
case m: Mux => s"mux(${m.cond.serialize}, ${m.tval.serialize}, ${m.fval.serialize})"
case v: ValidIf => s"validif(${v.cond.serialize}, ${v.value.serialize})"
case p: DoPrim =>
s"${p.op.serialize}(" + (p.args.map(_.serialize) ++ p.consts.map(_.toString)).mkString(", ") + ")"
case r: WRef => r.name
case s: WSubField => s"w${s.exp.serialize}.${s.name}"
case s: WSubIndex => s"w${s.exp.serialize}[${s.value}]"
case s: WSubAccess => s"w${s.exp.serialize}[${s.index.serialize}]"
}
ret + debug(exp)
}
}
// def map(f: Expression => Expression): Expression =
// exp match {
// case s: SubField => SubField(f(s.exp), s.name, s.tpe)
// case s: SubIndex => SubIndex(f(s.exp), s.value, s.tpe)
// case s: SubAccess => SubAccess(f(s.exp), f(s.index), s.tpe)
// case m: Mux => Mux(f(m.cond), f(m.tval), f(m.fval), m.tpe)
// case v: ValidIf => ValidIf(f(v.cond), f(v.value), v.tpe)
// case p: DoPrim => DoPrim(p.op, p.args.map(f), p.consts, p.tpe)
// case s: WSubField => SubField(f(s.exp), s.name, s.tpe, s.gender)
// case s: WSubIndex => SubIndex(f(s.exp), s.value, s.tpe, s.gender)
// case s: WSubAccess => SubAccess(f(s.exp), f(s.index), s.tpe, s.gender)
// case e: Expression => e
// }
//}
implicit class StmtUtils(stmt: Stmt) {
def serialize(implicit flags: FlagMap = FlagMap): String =
{
var ret = stmt match {
case w: DefWire => s"wire ${w.name} : ${w.tpe.serialize}"
case r: DefRegister =>
val str = new StringBuilder(s"reg ${r.name} : ${r.tpe.serialize}, ${r.clock.serialize} with : ")
withIndent {
str ++= newline + s"reset => (${r.reset.serialize}, ${r.init.serialize})"
}
str
case i: DefInstance => s"inst ${i.name} of ${i.module}"
case i: WDefInstance => s"inst ${i.name} of ${i.module}"
case m: DefMemory => {
val str = new StringBuilder(s"mem ${m.name} : " + newline)
withIndent {
str ++= s"data-type => ${m.data_type}" + newline +
s"depth => ${m.depth}" + newline +
s"read-latency => ${m.read_latency}" + newline +
s"write-latency => ${m.write_latency}" + newline +
(if (m.readers.nonEmpty) m.readers.map(r => s"reader => ${r}").mkString(newline) + newline
else "") +
(if (m.writers.nonEmpty) m.writers.map(w => s"writer => ${w}").mkString(newline) + newline
else "") +
(if (m.readwriters.nonEmpty) m.readwriters.map(rw => s"readwriter => ${rw}").mkString(newline) + newline
else "") +
s"read-under-write => undefined"
}
str.result
}
case n: DefNode => s"node ${n.name} = ${n.value.serialize}"
case c: Connect => s"${c.loc.serialize} <= ${c.exp.serialize}"
case b: BulkConnect => s"${b.loc.serialize} <- ${b.exp.serialize}"
case w: Conditionally => {
var str = new StringBuilder(s"when ${w.pred.serialize} : ")
withIndent { str ++= newline + w.conseq.serialize }
w.alt match {
case s:Empty => str.result
case s => {
str ++= newline + "else :"
withIndent { str ++= newline + w.alt.serialize }
str.result
}
}
}
case b: Begin => {
val s = new StringBuilder
for (i <- 0 until b.stmts.size) {
if (i != 0) s ++= newline ++ b.stmts(i).serialize
else s ++= b.stmts(i).serialize
}
s.result + debug(b)
}
case i: IsInvalid => s"${i.exp.serialize} is invalid"
case s: Stop => s"stop(${s.clk.serialize}, ${s.en.serialize}, ${s.ret})"
case p: Print => s"printf(${p.clk.serialize}, ${p.en.serialize}, ${p.string}" +
(if (p.args.nonEmpty) p.args.map(_.serialize).mkString(", ", ", ", "") else "") + ")"
case s:Empty => "skip"
}
ret + debug(stmt)
}
// Using implicit types to allow overloading of function type to map, see StmtMagnet above
//def map[T](f: T => T)(implicit magnet: (T => T) => StmtMagnet): Stmt = magnet(f).map(stmt)
def getType(): Type =
stmt match {
case s: DefWire => s.tpe
case s: DefRegister => s.tpe
case s: DefMemory => s.data_type
case _ => UnknownType()
}
}
implicit class WidthUtils(w: Width) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
val s = w match {
case w:UnknownWidth => "" //"?"
case w: IntWidth => s"<${w.width.toString}>"
}
s + debug(w)
}
}
implicit class FlipUtils(f: Flip) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
val s = f match {
case REVERSE => "flip "
case DEFAULT => ""
}
s + debug(f)
}
def flip(): Flip = {
f match {
case REVERSE => DEFAULT
case DEFAULT => REVERSE
}
}
def toDirection(): Direction = {
f match {
case DEFAULT => OUTPUT
case REVERSE => INPUT
}
}
}
implicit class FieldUtils(field: Field) {
def serialize(implicit flags: FlagMap = FlagMap): String =
s"${field.flip.serialize}${field.name} : ${field.tpe.serialize}" + debug(field)
def flip(): Field = Field(field.name, field.flip.flip, field.tpe)
def getType(): Type = field.tpe
def toPort(): Port = Port(NoInfo, field.name, field.flip.toDirection, field.tpe)
}
implicit class TypeUtils(t: Type) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
val commas = ", " // for mkString in BundleType
val s = t match {
case c:ClockType => "Clock"
//case UnknownType => "UnknownType"
case u:UnknownType => "?"
case t: UIntType => s"UInt${t.width.serialize}"
case t: SIntType => s"SInt${t.width.serialize}"
case t: BundleType => s"{ ${t.fields.map(_.serialize).mkString(commas)}}"
case t: VectorType => s"${t.tpe.serialize}[${t.size}]"
}
s + debug(t)
}
def getType(): Type =
t match {
case v: VectorType => v.tpe
case tpe: Type => UnknownType()
}
def wipeWidth(): Type =
t match {
case t: UIntType => UIntType(UnknownWidth())
case t: SIntType => SIntType(UnknownWidth())
case _ => t
}
}
implicit class DirectionUtils(d: Direction) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
val s = d match {
case INPUT => "input"
case OUTPUT => "output"
}
s + debug(d)
}
def toFlip(): Flip = {
d match {
case INPUT => REVERSE
case OUTPUT => DEFAULT
}
}
}
implicit class PortUtils(p: Port) {
def serialize(implicit flags: FlagMap = FlagMap): String =
s"${p.direction.serialize} ${p.name} : ${p.tpe.serialize}" + debug(p)
def getType(): Type = p.tpe
def toField(): Field = Field(p.name, p.direction.toFlip, p.tpe)
}
implicit class ModuleUtils(m: Module) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
m match {
case m:InModule => {
var s = new StringBuilder(s"module ${m.name} : ")
withIndent {
s ++= m.ports.map(newline ++ _.serialize).mkString
s ++= m.body.serialize
}
s ++= debug(m)
s.toString
}
}
}
}
implicit class CircuitUtils(c: Circuit) {
def serialize(implicit flags: FlagMap = FlagMap): String = {
var s = new StringBuilder(s"circuit ${c.main} : ")
withIndent { s ++= newline ++ c.modules.map(_.serialize).mkString(newline + newline) }
s ++= newline ++ newline
s ++= debug(c)
s.toString
}
}
private var indentLevel = 0
private def newline = "\n" + (" " * indentLevel)
private def indent(): Unit = indentLevel += 1
private def unindent() { require(indentLevel > 0); indentLevel -= 1 }
private def withIndent(f: => Unit) { indent(); f; unindent() }
}
|