-
Notifications
You must be signed in to change notification settings - Fork 0
/
compile.js
1209 lines (966 loc) · 33.2 KB
/
compile.js
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
#!/usr/bin/env node
'use strict';
const util = require('util');
const fs = require('fs');
const assert = require('assert');
const CMDR = require('commander').program;
const PEG = require('pegjs');
const CRAM = require('./tools/write-cram-mem');
const DRAM = require('./tools/write-dram-mem');
const logic = require('./logic.js');
// Provided by caller of `compile()`.
var options;
function parseFile(parser, filename) {
let fileAST;
try {
// Pass "options" so we can call our `astDirToDir()` function from parser.
fileAST = parser.parse(fs.readFileSync(filename, 'utf8'), {astDirToDir});
} catch (e) {
console.log(`ERROR: Parsing Failure: ${e.message}`);
if (e.location) {
console.log(`\
start: ${e.location.start}
end: ${e.location.end}`);
} else {
console.log(`Exception: ${dumpThing(e)}`);
}
process.exit(1);
}
return fileAST;
}
function parseBackplanes(parser) {
const filename = options.src;
const bp = parseFile(parser, filename)[0];
if (options.dumpAst) fs.writeFileSync(`${bp.name}.before.evaluation`, dumpThing(bp));
bp.boards = {};
// For each slot for which we haven't already parsed the board netlist,
// parse it and save it in `bp.boards` indexed by module ID (e.g., 'edp').
// While we're at it, accumulate the board's list of net names and what
// is connected, remembering direction and PDF reference for each such.
bp.slots
.filter(slot => slot.module && slot.module.id != 'ignore' && !bp.boards[slot.module.id])
.forEach(slot => {
const id = slot.module.id;
const boardPath = `board/${id}.board`;
console.log(`[parse ${boardPath}]`);
const board = parseFile(parser, boardPath);
bp.boards[id] = board;
if (board.bpPins && options.dumpPins) {
fs.writeFileSync(`${id}.bp-pins`,
Object.keys(board.bpPins)
.sort()
.map(bpp => Object.values(board.bpPins[bpp])
.map(p => {
const pdfRef = p.page.pdfRef.padEnd(7);
const chipPin = `${p.chip.name}.${p.pin}`.padEnd(9);
return `\
${bpp} ${p.dir} ${chipPin} ${pdfRef} ${p.net}`;
})
.join('\n')
)
.join('\n') + '\n');
}
});
return bp;
}
////////////////////////////////////////////////////////////////////////////////
function bindSlots(bp, cramDefs) {
// Build bpMacroEnv which is the basis of macros used for each board.
const bpMacroEnv = {};
(bp.macros || []).forEach(macro => bpMacroEnv[macro.id] = macro.value);
bp.cramDefs = cramDefs;
bp.vNetToPins = {};
console.log(`Backplane ${bp.name}:`);
// For each slot, expand the board's macros for the slot (and
// backplane, and CPU type) specifics.
bp.slots
.filter(slot => slot.module && slot.module.id != 'ignore')
.forEach(slot => {
const slotNumber = slot.n.padStart(2, '0');
const slotName = slotNumber;
const id = slot.module.id;
const board = bp.boards[id];
const macros = slot.module.macros || [];
const macroDesc = macros.map(macro => `${macro.id}=${macro.value}`).join (' ');
console.log(` Slot ${slotName}: ${id.padEnd(4)} ${macroDesc.padEnd(12)} ${slot.module.comments}`);
// Each board macro env starts with copy of BP macro vars as
// base, then we add this board's values, possibly overriding
// existing ones.
const macroEnv = {...bpMacroEnv};
macros.forEach(macro => macroEnv[macro.id] = macro.value);
// Remember this slot's macros so we can generate Verilog `defines for them.
slot.macroEnv = macroEnv;
// Create a slot-unique copy of each board's chips and interconnecting nets.
slot.chips = {};
slot.verilogRefNum = 0;
// Bind backplane pins to their nets.
Object.keys(board.bpPins).forEach(bpp => {
const pinNets = board.bpPins[bpp];
const gNets = Object.values(pinNets).
map(pinNet => pinNet.netAST ?
canonicalize(pinNet.netAST.map(e => evalExpr(e, macroEnv, true)).join('')) :
pinNet.net);
const dirs = Object.values(pinNets)
.map(pinNet => pinNet.dir)
.sort().
join('');
if (!gNets.every(e => e === gNets[0])) {
console.error(`
ERROR: Not all nets on ${id}.${bpp} are the same net:
${gNets.join('\n ')}
`);
}
// For pins driven by CRAM modules, define global net name from
// CRAM definitions, in preference to the definition on the module.
// E.g., `crm.be2[cpu.44]`
const cramPinName = `${id}.${bpp}[${id}.${slotNumber}]`;
const cd = cramDefs.bp[cramPinName];
const gNet = cd ? cd.net : gNets[0];
const vNet = verilogify(gNet);
slot.bpPins[bpp] = { gNet, vNet, pinNets, dirs, bpp, };
addSlotVNet(bp, slot.bpPins[bpp], slotNumber, `${slotNumber}.${id}`);
});
if (options.dumpSlots) {
fs.writeFileSync(`${slotNumber}.${id}.slot`,
Object.keys(slot.bpPins)
.sort()
.map(bpp => {
const v = slot.bpPins[bpp];
return `\
${slotNumber}.${bpp}[${v.dirs}]: ${v.vNet}`;
})
.join('\n') + '\n');
}
board.pages
.flatMap(page => page.chips) // Collect all the chips on all the pages
.forEach(chip => {
// Insert hand-coded verilog if present as if it were a "chip".
if (chip.nodeType === 'Verilog') {
slot.verilogRefNum = slot.verilogRefNum + 1;
chip.name = `verilog${slot.verilogRefNum}`;
slot.chips[chip.name] = {
type: 'verilog',
desc: '',
refDes: chip.name,
verilog: chip.v,
pins: [],
};
} else {
slot.chips[chip.name] = {
type: chip.type,
desc: chip.desc,
refDes: chip.name,
pins: chip.pins.reduce((cur, pin) => {
let net = null;
if (pin.bpPin) {
const cramPinName = `${id}.${pin.bpPin}[${id}.${slotNumber}]`;
const cd = cramDefs.bp[cramPinName];
if (cd) net = verilogify(cd.net);
}
if (!net) net = verilogify(canonicalize(evalExpr(pin.net, macroEnv, true)));
const pinName = logic.pinToName(chip.type, pin.pin, pin.dir);
if (!pinName) {
console.error(`ERROR: ${chip.name}: ${chip.type} pin ${pin.pin} is not ${pin.dir}`);
}
cur[pinName] = {
dir: astDirToDir(pin.dir),
net,
name: chip.name,
};
return cur;
}, {}),
}
};
});
});
if (options.dumpPins) {
fs.writeFileSync(`bp.wires`,
Object.keys(bp.vNetToPins)
.filter(vn => vn != '%NC%')
.sort()
.map(vn => {
const pins = bp.vNetToPins[vn];
return `\
${vn.padStart(40)}: ${Object.keys(pins).join(' ')}`;
})
.join('\n') + '\n');
}
if (options.dumpUndriven) {
fs.writeFileSync(`${bp.name}.undriven`,
Object.keys(bp.vNetToPins)
.filter(vn => vn != '%NC%')
.sort()
.filter(vn => !Object.keys(bp.vNetToPins[vn])
.some(e => e.match(/D[0-9]/)))
.map(vn => {
const pins = bp.vNetToPins[vn];
return `\
${vn.padStart(40)}: ${Object.keys(pins).join(' ')}`;
})
.join('\n') + '\n');
}
if (options.dumpAst) fs.writeFileSync(`${bp.name}.after.evaluation`, dumpThing(bp));
return bp;
}
function addSlotVNet(bp, sv, slotNumber, vnv) {
if (!bp.vNetToPins[sv.vNet]) bp.vNetToPins[sv.vNet] = {};
const d = sv.dirs.includes('D') ? 'D' : 'i';
bp.vNetToPins[sv.vNet][`${d}${slotNumber}.${sv.bpp}`] = vnv;
}
////////////////////////////////////////////////////////////////////////////////
// Complain if nets are not driven and not on the backplane connector
// or if driven by more than one pin.
function checkNetConnectivity(netByName) {
console.log(`Check nets for proper connectivity:`);
Object.keys(netByName).forEach(netName => {
if (netName === '%NC%') return;
if (netName == 0) return;
if (netName == 1) return;
const pins = netByName[netName];
if (pins.length === 0) {
console.log(`WARNING NOT CONNECTED: "${netName}" is not connected`);
} else {
const driving = pins.filter(pin => pin.dir === '~>');
if (driving.length > 1) {
if (options.dumpWireOr) {
console.log(`WARNING WIRE-OR: "${netName}" is wire-OR driven by ${driving.length} pins:`);
if (options.verboseErrors) console.log(` ${util.inspect(driving)}`);
}
} else if (driving.length === 0 && !pins.some(pin => pin.bpPin)) {
if (options.dumpUndriven) {
console.log(`WARNING UNDRIVEN: "${netName}" is not driven by any pin and is not backplane connected:`);
if (options.verboseErrors) console.log(` ${util.inspect(pins)}`);
}
}
}
});
}
////////////////////////////////////////////////////////////////////////////////
// Walk the entire AST. Under all 'Pin' nodes evaluate and expand all
// 'Macro' nodes and join any adjacent IDchunks with them to form a
// single 'ID' node with attribute 'name'. The `cx` is the context for
// all expansion, accumulating the nets as we work through them.
function expandMacros(ast, nets, macroEnv, cx = {}) {
if (!ast) return;
switch (ast.nodeType) {
case 'Chip':
cx.chip = ast;
cx.chip.page = cx.page;
cx.chip.board = cx.board;
cx.chip.logic = logic[cx.chip.type];
if (!cx.chip.logic) {
// Provide dummy entry just so we can go on
cx.chip.logic = {'~<': [], '~>': []};
console.log(`======> ${cx.page.name}.${cx.chip.name} undefined logic device '${cx.chip.type}'`);
}
cx.chip.pins.forEach(k => expandMacros(k, nets, macroEnv, cx));
break;
case 'Page':
cx.page = ast;
cx.page.board = cx.board;
cx.page.chips.forEach(k => expandMacros(k, nets, macroEnv, cx));
break;
case 'Board':
cx.board = ast;
ast.pages.forEach(k => expandMacros(k, nets, macroEnv, cx));
break;
case 'Stub':
console.log(`= = = STUB`);
cx.board = ast;
break;
case 'Pin':
cx.pin = ast;
cx.pin.chip = cx.chip;
cx.pin.fullName = cx.pin.chip.page.name + '.' + cx.pin.chip.name + '.' + cx.pin.pin;
cx.pin.symbol = Symbol(cx.pin.fullName);
cx.net = '';
switch (cx.pin.net.nodeType) {
case 'Macro':
cx.net += evalExpr(cx.pin.net, macroEnv, true); // Handles selectors and simple macros
break;
case 'Selector':
const selected = evalExpr(cx.pin.net.head, macroEnv, true);
cx.net += evalExpr(cx.pin.net.list[+selected - 1], macroEnv, false);
break;
case 'IDList':
cx.net = cx.pin.net.list.map(id => evalExpr(id, macroEnv, false)).join('');
break;
case 'IDChunk':
cx.net += cx.pin.net.name;
break;
case 'VerilogChunk':
cx.net += cx.pin.net.name.slice(1);
break;
case 'NoConnect':
cx.net += '%NC%';
break;
case 'Value':
cx.net += cx.pin.net.value;
break;
default:
console.log(`Unhandled AST type in evalExpr: ast=${util.inspect(ast, {depth: 99})}`);
break;
}
if (!cx.chip.logic[cx.pin.dir] || !cx.chip.logic[cx.pin.dir][cx.pin.pin]) {
console.log(`\
======> ${cx.chip.name} undefined pin ${cx.pin.pin} ${cx.pin.dir} for ${cx.chip.type}`);
}
cx.pin.netName = cx.net.trim();
if (cx.net === '')
console.log(`Pin ${cx.pin.fullName} net=${util.inspect(cx.pin.net, {depth: 9})}`);
// We want nets to be an object whose properties are the net
// names. Each property value is an object whose names are the pin
// directions: '~<' and '~>'. The value of this property is an
// object whose properties (and, to be complete here, its values
// as well) are the pins attached to the net for the associated
// direction.
if (!nets[cx.net]) nets[cx.net] = {};
if (!nets[cx.net][cx.pin.dir]) nets[cx.net][cx.pin.dir] = {};
nets[cx.net][cx.pin.dir][cx.pin.fullName] = cx.pin;
break;
default:
console.log(`Unrecognized AST node type '${ast.nodeType}'.`);
break;
}
}
// For the given AST subtree evaluate and expand any macro nodes
// with the corresponding value from 'macroEnv' and numerically
// evaluate any expression. Returns the full expansion of the
// resulting collapsed tree.
function evalExpr(t, macroEnv, macrosAllowed) {
let result;
if (!t || !t.nodeType) debugger;
switch (t.nodeType) {
case 'Macro':
result = evalExpr(t.head, macroEnv, true);
break;
case 'Selector':
result = evalExpr(t.head, macroEnv, true);
const selected = t.list[+result - 1]; // 1-origin indexing
if (result < 1 || selected === null) {
console.log(`ERROR: Selector produces undefined result=${result} selected=${selected}:
${util.inspect(t, {depth:99})}`);
result = '%NC%';
} else {
// Note that the selected value may contain a macro to be
// expanded, but only within its own set of []s. It is only
// the `t.head` inside these []s that should be expanded.
result = evalExpr(selected, macroEnv, false);
}
break;
case '+':
case '-':
case '/':
case '*':
// This is complicated by the need to keep the values as strings
// and to evaluate results to preserve the number of digits, which
// is the max of the length of each of the operands.
const L = evalExpr(t.l, macroEnv, macrosAllowed);
const R = evalExpr(t.r, macroEnv, macrosAllowed);
const resultStr = Math.trunc(eval(`${parseInt(L, 10)} ${t.nodeType} ${parseInt(R, 10)}`));
const digits = (t.nodeType === '-' || t.nodeType === '+') ? Math.max(L.length, R.length) : 0;
result = padValueToDigits(resultStr, digits)
break;
case 'IDList':
result = t.list.map(id => evalExpr(id, macroEnv, macrosAllowed)).join('');
break;
case 'IDChunk':
result = macrosAllowed ? macroEnv[t.name] : t.name;
if (result === undefined) result = t.name;
break;
case 'VerilogChunk':
result = t.name;
break;
case 'Value':
result = t.value;
break;
case 'NoConnect':
result = '%NC%';
break;
case 'Value':
result = t.value;
break;
default:
console.log(`\
Unhandled subtree node type in ${t.nodeType} macro: '${util.inspect(t, {depth: 999})}'.`);
result = '<coding error>';
break;
}
return result;
}
function compile(simOptions) {
options = simOptions;
// libreoffice --convert-to csv ./cram-backplane.ods
const cramDefs = readCRAMBackplane('cram-backplane.csv');
if (options.dumpCram) {
fs.writeFileSync('bp.cram-defs',
util.inspect(cramDefs, {
depth: 99,
breakLength: 90,
maxArrayLength: Infinity,
}));
}
const parser = PEG.generate(fs.readFileSync('netlist.pegjs', 'utf8'), {
output: 'parser',
trace: options.traceParse,
});
// Parse the backplane definition and collapse the board page
// substructure into a list of chips on the board.
const bp = parseBackplanes(parser);
// Bind each board into the slot(s) it fits into, assigning
// macro-expanded net names and pins.
bindSlots(bp, cramDefs);
if (options.dumpBackplane) fs.writeFileSync('bp.dump', dumpThing(bp));
if (options.dumpPins) dumpPins(bp);
if (options.dumpVerilog) dumpVerilogNames(bp);
if (options.dumpNets) dumpNets(bp);
if (options.genSV) genSV(bp);
if (options.genCram) genCram(bp);
if (options.genDram) genDram(bp);
if (options.dumpBadAnonymous) checkAnonymousNames(bp);
if (options.dumpMalformed) checkForMalformedSymbolNames(bp);
return bp;
}
function vDirForNets(nets) {
return nets.some(net => net.dir === 'D') ? 'output' : 'input';
}
function modNameForSlot(slot) {
const id = slot.module.id;
const slotNumber = slot.n.padStart(2, '0');
return id + slotNumber;
}
function genSV(bp) {
genBackplaneSV(bp);
// Accumulator indexed by vNet name of list of backplane pins
// attached to the signal.
bp.slots
.filter(s => s.module.id !== 'ignore')
.forEach(slot => {
const modName = modNameForSlot(slot);
// Build modPins list.
const modPins = Object.keys(slot.bpPins)
.filter(bpp => slot.bpPins[bpp].gNet !== '%NC%')
.sort((a, b) => {
const aSym = slot.bpPins[a].vNet;
const bSym = slot.bpPins[b].vNet;
return aSym < bSym ? -1 : aSym > bSym ? +1 : 0;
})
.reduce((cur, bpPin) => {
const p = slot.bpPins[bpPin];
const dir = p.dirs[0] === 'D' ? 'output' : 'input';
cur[bpPin] = {vNet: p.vNet, bpPin, dir};
return cur;
}, {});
const modParams = Object.values(Object.values(modPins)
// Remove duplicates
.reduce((cur, v) => {cur[v.vNet] = v; return cur}, {}))
.map(v => `\
${v.dir.padEnd(6)} ${v.vNet}`)
.join(',\n ');
const macros = genSlotMacros(bp, slot, modName);
const modV = bp.boards[slot.module.id].verilog;
const nets = genSlotNets(bp, slot, modName);
const chips = genSlotChips(bp, slot, modName);
fs.writeFileSync(`./rtl/gen/${modName}.sv`, `\
\`include "kl10pv.svh"
module ${modName} ${macros} (
${modParams}
${(modV || '').trimEnd()}
);
${nets}
${chips}
endmodule // ${modName}
`);
});
function vSort(a, b) {
return a[0].vNet > b[0].vNet ? +1 : a[0].vNet < b[0].vNet ? -1 : 0;
}
}
function genSlotMacros(bp, slot, modName) {
if (Object.keys(slot.macroEnv).length == 0) return ``;
return `#(
parameter ${Object.keys(slot.macroEnv)
.map(mac => `${mac} = ${slot.macroEnv[mac]}`)
.join(',\n ')})
`;
}
function genBackplaneSV(bp) {
// Define each net in the backplane.
const decls = Object.keys(bp.vNetToPins)
.filter(n => n !== '%NC%' && n !== 'top_clk')
.sort()
.map(n => ` bit ${untickify(n)};`)
.join('\n');
fs.writeFileSync(`./rtl/gen/kl-backplane.svh`, `
${decls}
`);
}
// Emit the board instances to represent the chips on the board in a slot.
function genSlotChips(bp, slot, modName) {
const allChips = Object.values(slot.chips)
.sort((a, b) => a.name > b.name ? +1 : a.name < b.name ? -1 : 0)
.map(chip => {
if (chip.type === 'verilog') {
return `
// Inline verilog
${chip.verilog}\
// End inline verilog
`;
} else {
return `\
${chipTypeToModName(chip)} ${chip.refDes}(
${genChipPins(bp, slot, chip)});
`;
}
}).join('\n');
return `
// Chips in ${modName} instance
${allChips}
`;
}
// Emit the wiring between chips within a slot.
function genSlotNets(bp, slot, modName) {
const wires = {}; // Indexed by verilogified signal name
Object.values(slot.chips)
.forEach(chip => {
// Gather in `wires[vNet]` a list of attached pins.
Object.values(chip.pins || {})
// Filter out constant value nets.
.filter(pin => pin.net != 0 && pin.net != 1 && pin.net !== '%NC%')
// Filter out backplane signals by vNet name since they will
// be declared for module input/output.
.filter(pin => {
const v = !Object.values(slot.bpPins)
.some(bpp => bpp.vNet === pin.net);
return v;
})
.filter(pin => pin.net != '1' && pin.net != '0')
.forEach(pin => wires[pin.net] = (wires[pin.net] || []).concat(pin));
});
// Walk through the nets in this slot and find multiple drivers of,
// e.g., `funky signal h`. Change drivers to drive new signals
// `funky signal h$1`, `funky signal h$2`, etc. (We use the index
// in `wires[]` + 1 as the uniquifier integer for the signal name.)
// OR these together producing `funky signal h`. Inputs continue to use
// `funky signal h`, which is bound to the output of the OR.
const bitDecls = Object.keys(wires)
.sort()
.map(w => {
const driving = wires[w].filter(v => v.dir === 'D');
if (driving.length > 1) { // Has two or more wire-ORed drivers
// Generate the list of new signal names, while replacing
// driving pin target wire names with the new ones. Must
// use wires[] and not driving[] because we are changing
// wires at specified index in wires[].
const drivers = wires[w].flatMap((pin, pinX) => {
if (pin.dir === 'D') {
const newName = w + '$' + (pinX+1);
wires[w][pinX].net = newName;
return newName;
} else {
return [];
}
});
return `\
bit ${drivers.join(', ')};
bit ${w};
always_comb ${w} = ${drivers.join(' | ')};`
} else if (!isTicked(w)) { // Just pass raw verilog expressions or names through
return `bit ${w};`
}
})
.join('\n ');
return `\
// Wires and wire-ORs in ${modName} instance
${bitDecls}
`;
}
function isTicked(s) {
if (!s || !s.slice) return false;
return s.slice(0, 1) === '`';
}
function untickify(s) {
return isTicked(s) ? s.slice(1) : s;
}
function genChipPins(bp, slot, chip) {
return Object.keys(chip.pins)
.map(pinName => {
const pin = chip.pins[pinName];
let value = pin.net;
if (value === '0') value = `0`;
else if (value === '%NC%') value = pin.dir === 'I' ? `0` : ``;
else if (value == 1) value = `1`;
return `.${verilogify(pinName)}(${untickify(value)})`;
})
.join(',\n ');
}
// For chip types that start with numbers, assume they are mcXXX.
// Substitute "_" for "-" in chip types to make valid identifiers.
function chipTypeToModName(chip) {
let n = chip.type.replace(/-/g, '_');
if (n === 'wire') n = 'just_a_wire';
return chip.type.match(/^[0-9].*/) ? `mc${n}` : n;
}
function genCram(bp) {
const fn = options.genCram;
console.log(`[generate ${fn}]`);
fs.writeFileSync(fn, `\
${CRAM.write()}
`);
}
function genDram(bp) {
const fn = options.genDram;
console.log(`[generate ${fn}]`);
fs.writeFileSync(fn, `\
${DRAM.write()}
`);
}
function readCRAMBackplane(fn) {
return fs.readFileSync(fn, 'utf8')
.split('\n')
.filter((line, x) => line && x != 0)
.reduce((cram, line) => {
const [netUC, offsetExpr, nExpr, bitExpr, pinFull, ucBitExpr] = line.split(',');
const net = netUC.toLowerCase();
const bit = +bitExpr;
const ucBit = +ucBitExpr;
const slot = pinFull.slice(2, 4);
const bpPinName = `${pinFull[1]}${pinFull.slice(4)}`.toLowerCase();
const srcPin = `crm.${bpPinName}[crm.${slot}]`;
if (isNaN(slot)) console.error(`${fn} bad slot number in line '${line}'`);
const pPin = cram.bp[srcPin];
if (pPin) {
console.log(`srcPin="${srcPin}" pPin=${util.inspect(pPin)}`);
const pb = pPin.bit.toString();
const pn = pPin.net;
console.error(`${fn} duplicate '${net}' srcPin '${srcPin}', was ${pb.padStart(3)} '${pn}'`);
}
if (cram.nets[net]) console.error(`${fn} defines net '${net}' more than once`);
cram.bp[srcPin] = {net, srcPin, bpp: bpPinName, slot, bit};
if (!cram.slot[slot]) cram.slot[slot] = {};
cram.slot[slot][srcPin] = cram.bp[srcPin];
cram.nets[net] = cram.bp[srcPin];
return cram;
}, {nets: {}, slot: {}, bp: {}, });
}
function astDirToDir(d) {
return (d === '~<') ? 'I' : (d === '~>') ? 'D' : `???${d}`;
}
// Convert DEC nomenclature name `n` to Verilog identifier.
// Use the following mappings and rules:
// * ` ` ==> _
// * `<-` ==> GETS
// * <digits>-<digits> ==> <digits>to<digits>
// * i/o ==> IO
// * xxx<digit>-e<digits>-<digits> ==> xxx<digits>_e<digits>_<digits>
// * [/,*.-+=#()%^<>&] ==> SYMBOLNAME
// * `-xxxx h` ==> `xxxx l`
// * `-xxxx l` ==> `xxxx h`
const charSymNames = {
'-': 'NG',
'/': 'SL',
',': 'CM',
'*': 'ST',
'.': 'DT',
'+': 'PL',
'=': 'EQ',
'#': 'NR',
'(': 'LP',
')': 'RP',
'%': 'PE',
'^': 'CT',
'<': 'LT',
'>': 'GT',
'&': 'AN',
'[': 'LB',
']': 'RB',
};
function verilogify(n) {
if (isTicked(n)) return n;
// First convert -xxxx [lh] to xxxx [hl].
n = canonicalize(n);
if (n === '%NC%' || n == 1 || n == 0) return n;
n = n.replace(/ /g, '_');
n = n.replace(/<-/g, 'GETS');
n = n.replace(/([a-z][a-z][a-z0-9][0-9]*)-([a-z]+\d+)-(\d+)/g, '$1_$2_$3');
n = n.replace(/(\d+)-(\d+)/g, '$1to$2');
n = n.replace(/i\/o/g, 'IO');
n = n.replace(/10\/11/g, '10_11');
n = n.split('').map(ch => charSymNames[ch] || ch).join('');
return n;
}
function checkForMalformedSymbolNames(bp) {
const malformed = Object.entries(bp.boards)
.map(([boardID, board]) => Object.keys(board.nets)
// Remove valid no connect symbol
.filter(n => n != '%NC%' && n != '0' && n != '1')
// Remove valid xxx [hl]
.filter(n => !n.slice(-2).match(/ [hl]/))
// Remove valid xxx hi for local logic 1 symbol used on some boards
.filter(n => n.slice(-3) != ' hi' && n != 'hi')
// Remove valid local anonymous net names mod-e99-99
.filter(n => !n.match(/([a-z][a-z][a-z0-9][0-9]*)-([a-z]+\d+)-(\d+)/))
.map(n => `${boardID}: '${n}'`)
.join('\n'));
if (malformed) {
console.error(`\
MALFORMED symbol names:\n
${malformed.join('\n')}
`);
} else {
console.log(`[no malformed symbol names found]`);
}
}
function checkAnonymousNames(bp) {
Object.entries(bp.boards)
.forEach(([boardID, board]) => Object.entries(board.nets)
.forEach(([n, boardNet]) => {
const m = n.match(`(?<id>[a-z]+[0-9]?)[0-9]-(?<chip>[a-z][0-9]+)-(?<pin>[0-9]+)`);
if (!m) return;
const {id, chip, pin} = m.groups;
if (!boardNet.some(bn => bn.dir === 'D')) {
console.error(`${boardID}: ${chip}.${pin} ${n} not driven`);
}
boardNet.forEach(bn => {
if (id !== boardID) {
console.error(`${boardID}: ${n}: '${id}' mismatches board ID '${boardID}'`);
}
if (bn.dir === 'D') { // Driving nets should match the chip/pin they attach to
// Unless they are part of a wired-OR
if (boardNet.some(wbn => wbn !== bn && wbn.dir === 'D')) return;
if (bn.chip.name !== chip) {
console.error(`${boardID}: ${n} chip '${chip}' mismatches '${bn.chip.name}'`);
}
if (bn.pin !== pin) {
console.error(`\
${boardID}: ${n} pin '${pin}' mismatches driving pin '${bn.chip.name}.${bn.pin}'`);
}
} else { // Find matching driving pin for this input pin
}
});
}));
}
function dumpVerilogNames(bp) {
fs.writeFileSync('bp.verilog-names',
Object.keys(bp.n2v)
.sort(netNameSort)
.map(nName => `${nName.padStart(50)}: ${bp.n2v[nName]}`).join("\n") + "\n")
}
function dumpPins(bp) {
if (false) {
fs.writeFileSync('bp.pins',
Object.keys(bp.allPins)
.sort(slotPinSort)
.map(bpPin => `\
${bpPin}:
${Object.values(bp.allPins[bpPin])
.map(pin => util.inspect(pin) /*`${pin.dir} ${pin.lNet.padEnd(35)}${pin.fullName}`*/)
.join("\n ")}`)
.join("\n") + "\n");
}
function slotPinSort(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
}
}
function dumpNets(bp) {
fs.writeFileSync('bp.nets',
Object.keys(bp.allNets)
.filter(k => k != '%NC%')
.sort(netNameSort)
.sort(netNameSort)
.map(netName => `\
${netName}:
${Object.keys(bp.allNets[netName])
.map(pinFullName => {
const pin = bp.allPins[pinFullName];
if (!pin) console.error(`pin==null for ${pinFullName}`);
return `${pin.dir} ${pinFullName.padEnd(20) + (pin.bpPin || '').padEnd(20)}${pin.pdfRef}`;
})
.join("\n ")}`)
.join("\n") + "\n");
// Sort e.g., "edp.aa1[38]" so the slot number
// "38" is primary, module "edp" is next,
// pin "aa1" is last.
function slotPinSort(a, b) {
a = bp.allPins[a];
b = bp.allPins[b];
const [aModule, aPin, aSlot] = [a.module, a.pin, a.slotName];
const [bModule, bPin, bSlot] = [b.module, b.pin, b.slotName];
return aSlot > bSlot ? 1 : aSlot < bSlot ? -1 :
aModule > bModule ? 1 : aModule < aModule ? -1 :
aPin > bPin ? 1 : aPin < bPin ? -1 : 0;
}
}
function netNameSort(a, b) {
a = a.replace(/^[^a-zA-Z]/g, '');
b = b.replace(/^[^a-zA-Z]/g, '');