forked from cambridgehackers/xbsv
/
bsvgen.py
591 lines (523 loc) · 21.1 KB
/
bsvgen.py
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
##
## Copyright (C) 2012-2013 Nokia, Inc
## Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.
## Permission is hereby granted, free of charge, to any person
## obtaining a copy of this software and associated documentation
## files (the "Software"), to deal in the Software without
## restriction, including without limitation the rights to use, copy,
## modify, merge, publish, distribute, sublicense, and/or sell copies
## of the Software, and to permit persons to whom the Software is
## furnished to do so, subject to the following conditions:
## The above copyright notice and this permission notice shall be
## included in all copies or substantial portions of the Software.
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
## BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
## ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
## CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
## SOFTWARE.
##
import os
import math
import re
import md5
import syntax
import AST
import string
import util
preambleTemplate='''
import FIFO::*;
import FIFOF::*;
import GetPut::*;
import Connectable::*;
import Clocks::*;
import FloatingPoint::*;
import Adapter::*;
import Leds::*;
import Vector::*;
import SpecialFIFOs::*;
import PortalMemory::*;
import Portal::*;
import MemPortal::*;
import MemTypes::*;
import Pipe::*;
%(extraImports)s
typedef struct {
Bit#(1) select;
Bit#(6) tag;
} ReadReqInfo deriving (Bits);
'''
requestStructTemplate='''
typedef struct {
%(paramStructDeclarations)s
} %(MethodName)s_Request deriving (Bits);
Bit#(6) %(methodName)s_Offset = %(channelNumber)s;
'''
exposedProxyInterfaceTemplate='''
%(responseElements)s
// exposed proxy interface
interface %(Dut)sPortal;
interface Portal#(%(requestChannelCount)s, %(indicationChannelCount)s, 32) portalIfc;
interface %(Ifc)s ifc;
endinterface
interface %(Dut)s;
interface StdPortal portalIfc;
interface %(Ifc)s ifc;
endinterface
'''
hiddenProxyInterfaceTemplate='''
%(responseElements)s
// hidden proxy interface
interface %(Dut)s;
%(indicationMethodDecls)s
interface ReadOnly#(Bool) interrupt;
endinterface
'''
requestOutputPipeInterfaceTemplate='''\
interface PipeOut#(%(MethodName)s_Request) %(methodName)s_PipeOut;
'''
exposedWrapperInterfaceTemplate='''
%(requestElements)s
// exposed wrapper portal interface
interface %(Dut)sPipes;
interface Vector#(%(requestChannelCount)s, PipeIn#(Bit#(32))) inputPipes;
interface Vector#(%(requestChannelCount)s, Bit#(32)) requestSizeBits;
%(requestOutputPipeInterfaces)s
endinterface
interface %(Dut)sPortal;
interface Portal#(%(requestChannelCount)s, %(indicationChannelCount)s, 32) portalIfc;
endinterface
// exposed wrapper MemPortal interface
interface %(Dut)s;
interface StdPortal portalIfc;
endinterface
'''
hiddenWrapperInterfaceTemplate='''
%(requestElements)s
// hidden wrapper interface
interface %(Dut)s;
endinterface
'''
responseStructTemplate='''
typedef struct {
%(paramStructDeclarations)s
} %(MethodName)s_Response deriving (Bits);
Bit#(6) %(methodName)s_Offset = %(channelNumber)s;
'''
wrapperCtrlTemplate='''
%(methodRules)s
'''
portalIfcTemplate='''
interface Portal portalIfc;
method Bit#(32) ifcId;
return zeroExtend(pack(id));
endmethod
method Bit#(32) ifcType;
return %(ifcType)s;
endmethod
interface Vector requests = requestPipes;
interface Vector requestSizeBits = requestBits;
interface Vector indications = indicationPipes;
interface Vector indicationSizeBits = indicationBits;
endinterface
'''
proxyInterruptImplTemplate='''
interface ReadOnly interrupt;
method Bool _read();
return (interruptEnableReg && interruptStatus);
endmethod
endinterface
'''
proxyCtrlTemplate='''
%(indicationMethodRules)s
%(startIndicationMethods)s
%(indicationMethods)s
%(endIndicationMethods)s
'''
requestRuleTemplate='''
FromBit#(32,%(MethodName)s_Request) %(methodName)s_requestFifo <- mkFromBit();
requestPipeIn[%(channelNumber)s] = toPipeIn(%(methodName)s_requestFifo);
requestBits[%(channelNumber)s] = fromInteger(valueOf(SizeOf#(%(MethodName)s_Request)));
'''
mkConnectionMethodTemplate='''
rule handle_%(methodName)s_request;
let request <- toGet(pipes.%(methodName)s_PipeOut).get();
%(invokeMethod)s
endrule
'''
indicationRuleTemplate='''
ToBit#(32,%(MethodName)s_Response) %(methodName)s_responseFifo <- mkToBit();
indicationPipes[%(channelNumber)s] = toPipeOut(%(methodName)s_responseFifo);
indicationBits[%(channelNumber)s] = fromInteger(valueOf(SizeOf#(%(MethodName)s_Response)));
'''
indicationMethodDeclTemplate='''
method Action %(methodName)s(%(formals)s);'''
indicationMethodTemplate='''
method Action %(methodName)s(%(formals)s);
%(methodName)s_responseFifo.enq(%(MethodName)s_Response {%(structElements)s});
//$display(\"indicationMethod \'%(methodName)s\' invoked\");
endmethod'''
mkHiddenWrapperInterfaceTemplate='''
// hidden wrapper implementation
module %(moduleContext)s mk%(Dut)s#(FIFO#(Bit#(15)) slaveWriteAddrFifo,
FIFO#(Bit#(15)) slaveReadAddrFifo,
FIFO#(Bit#(32)) slaveWriteDataFifo,
FIFOF#(Bit#(32)) slaveReadDataFifo)(%(Dut)s);
%(wrapperCtrl)s
endmodule
'''
mkExposedWrapperInterfaceTemplate='''
instance Connectable#(%(Dut)sPipes,%(Ifc)s);
module mkConnection#(%(Dut)sPipes pipes, %(Ifc)s ifc)(Empty);
%(mkConnectionMethodRules)s
endmodule
endinstance
// exposed wrapper Portal implementation
(* synthesize *)
module mk%(Dut)sPipes#(Bit#(32) id)(%(Dut)sPipes);
Vector#(%(requestChannelCount)s, PipeIn#(Bit#(32))) requestPipeIn = newVector();
Vector#(%(requestChannelCount)s, Bit#(32)) requestBits = newVector();
Vector#(0, PipeOut#(Bit#(32))) indicationPipes = nil;
Vector#(0, Bit#(32)) indicationBits = nil;
%(wrapperCtrl)s
interface Vector inputPipes = requestPipeIn;
interface Vector requestSizeBits = requestBits;
%(outputPipes)s
endmodule
module mk%(Dut)sPortal#(idType id, %(Ifc)s ifc)(%(Dut)sPortal)
provisos (Bits#(idType, __a),
Add#(a__, __a, 32));
let pipes <- mk%(Dut)sPipes(zeroExtend(pack(id)));
mkConnection(pipes, ifc);
let requestPipes = pipes.inputPipes;
let requestBits = pipes.requestSizeBits;
Vector#(0, PipeOut#(Bit#(32))) indicationPipes = nil;
Vector#(0, Bit#(32)) indicationBits = nil;
%(portalIfc)s
endmodule
interface %(Dut)sMemPortalPipes;
interface %(Dut)sPipes pipes;
interface MemPortal#(16,32) portalIfc;
endinterface
(* synthesize *)
module mk%(Dut)sMemPortalPipes#(Bit#(32) id)(%(Dut)sMemPortalPipes);
let p <- mk%(Dut)sPipes(zeroExtend(pack(id)));
Portal#(%(requestChannelCount)s, 0, 32) portalifc = (interface Portal;
method Bit#(32) ifcId;
return zeroExtend(pack(id));
endmethod
method Bit#(32) ifcType;
return %(ifcType)s;
endmethod
interface Vector requests = p.inputPipes;
interface Vector requestSizeBits = p.requestSizeBits;
interface Vector indications = nil;
interface Vector indicationSizeBits = nil;
endinterface);
let memPortal <- mkMemPortal(portalifc);
interface %(Dut)sPipes pipes = p;
interface MemPortal portalIfc = memPortal;
endmodule
// exposed wrapper MemPortal implementation
module mk%(Dut)s#(idType id, %(Ifc)s ifc)(%(Dut)s)
provisos (Bits#(idType, a__),
Add#(b__, a__, 32));
let dut <- mk%(Dut)sMemPortalPipes(zeroExtend(pack(id)));
mkConnection(dut.pipes, ifc);
interface MemPortal portalIfc = dut.portalIfc;
endmodule
'''
mkHiddenProxyInterfaceTemplate='''
// hidden proxy implementation
module %(moduleContext)s mk%(Dut)s#(FIFO#(Bit#(15)) slaveWriteAddrFifo,
FIFO#(Bit#(15)) slaveReadAddrFifo,
FIFO#(Bit#(32)) slaveWriteDataFifo,
FIFOF#(Bit#(32)) slaveReadDataFifo)(%(Dut)s);
%(proxyCtrl)s
%(portalIfcInterrupt)s
endmodule
'''
mkExposedProxyInterfaceTemplate='''
(* synthesize *)
module %(moduleContext)s mk%(Dut)sPortalSynth#(Bit#(32) id) (%(Dut)sPortal);
Vector#(0, PipeIn#(Bit#(32))) requestPipes = nil;
Vector#(0, Bit#(32)) requestBits = nil;
Vector#(%(channelCount)s, PipeOut#(Bit#(32))) indicationPipes = newVector();
Vector#(%(channelCount)s, Bit#(32)) indicationBits = newVector();
%(proxyCtrl)s
%(portalIfc)s
endmodule
// exposed proxy implementation
module %(moduleContext)s mk%(Dut)sPortal#(idType id) (%(Dut)sPortal)
provisos (Bits#(idType, __a),
Add#(a__, __a, 32));
let rv <- mk%(Dut)sPortalSynth(extend(pack(id)));
return rv;
endmodule
// synthesizeable proxy MemPortal
(* synthesize *)
module mk%(Dut)sSynth#(Bit#(32) id)(%(Dut)s);
let dut <- mk%(Dut)sPortal(id);
let memPortal <- mkMemPortal(dut.portalIfc);
interface MemPortal portalIfc = memPortal;
interface %(Ifc)s ifc = dut.ifc;
endmodule
// exposed proxy MemPortal
module mk%(Dut)s#(idType id)(%(Dut)s)
provisos (Bits#(idType, a__),
Add#(b__, a__, 32));
let rv <- mk%(Dut)sSynth(extend(pack(id)));
return rv;
endmodule
'''
def emitPreamble(f, files=[]):
extraImports = (['import %s::*;\n' % os.path.splitext(os.path.basename(fn))[0] for fn in files]
+ ['import %s::*;\n' % i for i in syntax.globalimports ])
f.write(preambleTemplate % {'extraImports' : ''.join(extraImports)})
class ParamMixin:
def numBitsBSV(self):
return self.type.numBitsBSV();
class NullMixin:
def emitBsvImplementation(self, f):
pass
class TypeMixin:
def toBsvType(self):
if len(self.params):
return '%s#(%s)' % (self.name, ','.join([str(p.toBsvType()) for p in self.params]))
else:
return self.name
def numBitsBSV(self):
if (self.name == 'Bit'):
return self.params[0].numeric()
if (self.name == 'Vector'):
return self.params[0].numeric() * self.params[1].numBitsBSV()
if (self.name == 'Int' or self.name == 'UInt'):
return self.params[0].numeric()
if (self.name == 'Float'):
return 32
sdef = syntax.globalvars[self.name].tdtype
if (sdef.type == 'Struct'):
return sum([e.type.numBitsBSV() for e in sdef.elements])
else:
return sdef.numBitsBSV();
class EnumMixin:
def numBitsBSV(self):
return int(math.ceil(math.log(len(self.elements),2)))
class MethodMixin:
def emitBsvImplementation(self, f):
pass
def substs(self, outerTypeName):
if self.return_type.name == 'ActionValue':
rt = self.return_type.params[0].toBsvType()
else:
rt = self.return_type.name
d = { 'dut': util.decapitalize(outerTypeName),
'Dut': util.capitalize(outerTypeName),
'methodName': self.name,
'MethodName': util.capitalize(self.name),
'channelNumber': self.channelNumber,
'ord': self.channelNumber,
'methodReturnType': rt}
return d
def collectRequestElement(self, outerTypeName):
substs = self.substs(outerTypeName)
paramStructDeclarations = [' %s %s;' % (p.type.toBsvType(), p.name)
for p in self.params]
if not self.params:
paramStructDeclarations = [' %s %s;' % ('Bit#(32)', 'padding')]
substs['paramStructDeclarations'] = '\n'.join(paramStructDeclarations)
return requestStructTemplate % substs
def collectResponseElement(self, outerTypeName):
substs = self.substs(outerTypeName)
paramStructDeclarations = [' %s %s;' % (p.type.toBsvType(), p.name)
for p in self.params]
if not self.params:
paramStructDeclarations = [' %s %s;' % ('Bit#(32)', 'padding')]
substs['paramStructDeclarations'] = '\n'.join(paramStructDeclarations)
return responseStructTemplate % substs
def collectMethodRule(self, outerTypeName, hidden=False):
substs = self.substs(outerTypeName)
if self.return_type.name == 'Action':
return requestRuleTemplate % substs
else:
return None
def collectIndicationMethodRule(self, outerTypeName):
substs = self.substs(outerTypeName)
if self.return_type.name == 'Action':
paramType = ['%s' % p.type.toBsvType() for p in self.params]
substs['paramType'] = ', '.join(paramType)
return indicationRuleTemplate % substs
else:
return None
def collectIndicationMethod(self, outerTypeName):
substs = self.substs(outerTypeName)
if self.return_type.name == 'Action':
formal = ['%s %s' % (p.type.toBsvType(), p.name) for p in self.params]
substs['formals'] = ', '.join(formal)
structElements = ['%s: %s' % (p.name, p.name) for p in self.params]
substs['structElements'] = ', '.join(structElements)
return indicationMethodTemplate % substs
else:
return None
def collectIndicationMethodDecl(self, outerTypeName):
substs = self.substs(outerTypeName)
if self.return_type.name == 'Action':
formal = ['%s %s' % (p.type.toBsvType(), p.name) for p in self.params]
substs['formals'] = ', '.join(formal)
structElements = ['%s: %s' % (p.name, p.name) for p in self.params]
substs['structElements'] = ', '.join(structElements)
return indicationMethodDeclTemplate % substs
else:
return None
class InterfaceMixin:
def substs(self,suffix,expose,proxy):
name = "%s%s"%(self.name,suffix)
dutName = util.decapitalize(name)
methods = [d for d in self.decls if d.type == 'Method' and d.return_type.name == 'Action']
# specific to wrappers
requestElements = self.collectRequestElements(name)
methodNames = self.collectMethodNames(name)
methodRuleNames = self.collectMethodRuleNames(name)
methodRules = self.collectMethodRules(name,not expose)
# specific to proxies
responseElements = self.collectResponseElements(name)
indicationMethodRuleNames = self.collectIndicationMethodRuleNames(name)
indicationMethodRules = self.collectIndicationMethodRules(name)
indicationMethods = self.collectIndicationMethods(name)
indicationMethodDecls = self.collectIndicationMethodDecls(name)
m = md5.new()
m.update(self.name)
substs = {
'Ifc': self.name,
'dut': dutName,
'Dut': util.capitalize(name),
'requestElements': ''.join(requestElements),
'methodNames': methodNames,
'methodRules': ''.join(methodRules),
'requestFailureRuleNames': "" if len(methodNames) == 0 else '(* descending_urgency = "'+', '.join(['handle_%s_requestFailure' % n for n in methodNames])+'"*)',
'channelCount': self.channelCount,
'writeChannelCount': self.channelCount,
'hiddenProxy' : "%sStatus" % name,
'moduleContext': '',
'requestChannelCount': len(methodRules) if not proxy else 0,
'responseElements': ''.join(responseElements),
'indicationMethodRules': ''.join(indicationMethodRules),
'indicationMethods': ''.join(indicationMethods),
'indicationMethodDecls' :''.join(indicationMethodDecls),
'indicationChannelCount': self.channelCount if proxy else 0,
'indicationInterfaces': ''.join(indicationTemplate % { 'Indication': name }) if not self.hasSource else '',
'hiddenWrapper' : "%sStatus" % name,
'startIndicationMethods' : '' if not expose else ' interface %s ifc;' % self.name,
'endIndicationMethods' : '' if not expose else ' endinterface',
'slaveFifoSelExposed' : '1' if proxy else '0',
'slaveFifoSelHidden' : '0' if proxy else '1',
}
substs['portalIfcInterrupt'] = 'interface ReadOnly interrupt = p.interrupt;' if not proxy else proxyInterruptImplTemplate
substs['ifcType'] = 'truncate(128\'h%s)' % m.hexdigest()
substs['portalIfc'] = portalIfcTemplate % substs
substs['wrapperCtrl'] = wrapperCtrlTemplate % substs
substs['proxyCtrl'] = proxyCtrlTemplate % substs
return substs
def emitBsvWrapper(self,f):
subs = self.substs('Wrapper',True,False)
name = "%s%s"%(self.name,'Wrapper')
methodNames = self.collectMethodNames(name)
subs['requestOutputPipeInterfaces'] = ''.join([requestOutputPipeInterfaceTemplate % {'methodName': methodName,
'MethodName': util.capitalize(methodName)}
for methodName in methodNames])
hidden = False
mkConnectionMethodRules = []
outputPipes = []
for m in self.decls:
if m.type == 'Method' and m.return_type.name == 'Action':
paramsForCall = ['request.%s' % p.name for p in m.params]
msubs = {'methodName': m.name,
'MethodName': util.capitalize(m.name),
'paramsForCall': ', '.join(paramsForCall)}
msubs['invokeMethod'] = '' if hidden else 'ifc.%(methodName)s(%(paramsForCall)s);' % msubs
mkConnectionMethodRules.append(mkConnectionMethodTemplate % msubs)
outputPipes.append(' interface %(methodName)s_PipeOut = toPipeOut(%(methodName)s_requestFifo);' % msubs)
subs['mkConnectionMethodRules'] = ''.join(mkConnectionMethodRules)
subs['outputPipes'] = '\n'.join(outputPipes)
f.write(exposedWrapperInterfaceTemplate % subs)
f.write(mkExposedWrapperInterfaceTemplate % subs)
def emitBsvProxy(self,f,suffix):
subs = self.substs(suffix,True,True)
f.write(exposedProxyInterfaceTemplate % subs)
f.write(mkExposedProxyInterfaceTemplate % subs)
def collectRequestElements(self, outerTypeName):
requestElements = []
for m in self.decls:
if m.type == 'Method':
e = m.collectRequestElement(outerTypeName)
if e:
requestElements.append(e)
return requestElements
def collectResponseElements(self, outerTypeName):
responseElements = []
for m in self.decls:
if m.type == 'Method':
e = m.collectResponseElement(outerTypeName)
if e:
responseElements.append(e)
return responseElements
def collectMethodRules(self,outerTypeName,hidden):
methodRules = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectMethodRule(outerTypeName,hidden)
if methodRule:
methodRules.append(methodRule)
return methodRules
def collectMethodRuleNames(self,outerTypeName):
methodRuleNames = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectMethodRule(outerTypeName)
if methodRule:
methodRuleNames.append('slaveWrite_%s' % m.name)
return methodRuleNames
def collectMethodNames(self,outerTypeName):
methodRuleNames = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectMethodRule(outerTypeName)
if methodRule:
methodRuleNames.append(m.name)
else:
print 'method %s has no rule' % m.name
return methodRuleNames
def collectIndicationMethodRuleNames(self,outerTypeName):
methodRuleNames = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectIndicationMethodRule(outerTypeName)
if methodRule:
methodRuleNames.append("%s_slaveRead" % m.name)
return methodRuleNames
def collectIndicationMethodRules(self,outerTypeName):
methodRules = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectIndicationMethodRule(outerTypeName)
if methodRule:
methodRules.append(methodRule)
return methodRules
def collectIndicationMethods(self,outerTypeName):
methods = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectIndicationMethod(outerTypeName)
if methodRule:
methods.append(methodRule)
return methods
def collectIndicationMethodDecls(self,outerTypeName):
methods = []
for m in self.decls:
if m.type == 'Method':
methodRule = m.collectIndicationMethodDecl(outerTypeName)
if methodRule:
methods.append(methodRule)
return methods