-
Notifications
You must be signed in to change notification settings - Fork 5
/
firrtl-chipyard.patch
2288 lines (2279 loc) · 77.5 KB
/
firrtl-chipyard.patch
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
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
deleted file mode 100644
index e41a54f2..00000000
--- a/.github/CODEOWNERS
+++ /dev/null
@@ -1 +0,0 @@
-* @freechipsproject/firrtl-reviewers
diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md
deleted file mode 100644
index 8c41c685..00000000
--- a/.github/ISSUE_TEMPLATE/bug-report.md
+++ /dev/null
@@ -1,35 +0,0 @@
----
-name: Bug Report
-about: Report a problem you experienced with FIRRTL
-labels: improvement=BugFix
----
-
-### Checklist
-
-- [ ] Did you specify the current behavior?
-- [ ] Did you specify the expected behavior?
-- [ ] Did you provide a code example showing the problem?
-- [ ] Did you describe your environment?
-- [ ] Did you specify relevant external information?
-
-### What is the current behavior?
-
-### What is the expected behavior?
-
-### Steps to Reproduce
-
-<!-- How can someone else reproduce the problem you're seeing? -->
-<!-- It's very helpful to include a full example of a failing Chisel or FIRRTL program! -->
-<!-- Include a stack trace if you have it! -->
-
-### Your environment
-
-<!-- Please tell us a little about your environment -->
-
-- Chisel Verions: <!-- e.g., 3.2.0 -->
-- OS: <!-- e.g., Linux knight 4.4.0-92-generic #115-Ubuntu SMP Thu Aug 10 09:04:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux -->
-- Verilator version: <!-- e.g., 4.008 -->
-
-### External Information
-
-<!-- Was this discussed anywhere else, e.g., Twitter, Gitter, StackOverflow? Provide direct links if available! -->
diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md
deleted file mode 100644
index 9f84d41d..00000000
--- a/.github/ISSUE_TEMPLATE/feature-request.md
+++ /dev/null
@@ -1,32 +0,0 @@
----
-name: Feature Request
-about: Request a new feature to be added to FIRRTL
----
-
-### Checklist
-
-- [ ] Did you write out a description of the feature you want to see?
-- [ ] Did you look around for any related features?
-- [ ] Did you specify relevant external information?
-
-### Feature Description
-
-<!-- What type of behavior, API, or feature would you like FIRRTL to have? -->
-
-### Type of Feature
-
-<!-- Choose one or more from the following: -->
-<!-- - performance improvement -->
-<!-- - documentation -->
-<!-- - code refactoring -->
-<!-- - code cleanup -->
-<!-- - backend code generation -->
-<!-- - new feature/API -->
-
-### Related Features
-
-<!-- Is there anything in the codebase that can do this right now or is substantially related? -->
-
-### External Information
-
-<!-- Was this discussed anywhere else, e.g., Twitter, Gitter, StackOverflow? Provide direct links if available! -->
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
deleted file mode 100644
index 77abae1d..00000000
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ /dev/null
@@ -1,50 +0,0 @@
-### Contributor Checklist
-
-- [ ] Did you add Scaladoc to every public function/method?
-- [ ] Did you update the FIRRTL spec to include every new feature/behavior?
-- [ ] Did you add at least one test demonstrating the PR?
-- [ ] Did you delete any extraneous printlns/debugging code?
-- [ ] Did you specify the type of improvement?
-- [ ] Did you state the API impact?
-- [ ] Did you specify the code generation impact?
-- [ ] Did you request a desired merge strategy?
-- [ ] Did you add text to be included in the Release Notes for this change?
-
-#### Type of Improvement
-
-<!-- Choose one or more from the following: -->
-<!-- - bug fix -->
-<!-- - performance improvement -->
-<!-- - documentation -->
-<!-- - code refactoring -->
-<!-- - code cleanup -->
-<!-- - backend code generation -->
-<!-- - new feature/API -->
-
-#### API Impact
-
-<!-- How would this affect the current API? Does this add, extend, deprecate, remove, or break any existing API? -->
-
-#### Backend Code Generation Impact
-
-<!-- Does this change any generated Verilog? -->
-<!-- How does it change it or in what circumstances would it? -->
-
-#### Desired Merge Strategy
-
-<!-- If approved, how should this PR be merged? -->
-<!-- Options are: -->
-<!-- - Squash: The PR will be squashed and merged (choose this if you have no preference. -->
-<!-- - Rebase: You will rebase the PR onto master and it will be merged with a merge commit. -->
-
-#### Release Notes
-<!--
-Text from here to the end of the body will be considered for inclusion in the release notes for the version containing this pull request.
--->
-
-### Reviewer Checklist (only modified by reviewer)
-- [ ] Did you add the appropriate labels?
-- [ ] Did you mark the proper milestone (1.2.x, 1.3.0, 1.4.0) ?
-- [ ] Did you review?
-- [ ] Did you check whether all relevant Contributor checkboxes have been checked?
-- [ ] Did you mark as `Please Merge`?
diff --git a/.gitignore b/.gitignore
index f907e043..13fadcc9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,6 +40,7 @@ spec/spec.out
spec/spec.synctex.gz
notes/*.docx
test_run_dir
+regress/
.project
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index d965e680..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,97 +0,0 @@
-language: scala
-sudo: false
-
-cache:
- directories:
- $HOME/.ivy2
- $HOME/.sbt
- $INSTALL_DIR
-
-git:
- depth: 10
-
-env:
- global:
- INSTALL_DIR=$TRAVIS_BUILD_DIR/install
- VERILATOR_ROOT=$INSTALL_DIR
- PATH=$PATH:$VERILATOR_ROOT/bin:$TRAVIS_BUILD_DIR/utils/bin
- SBT_ARGS="-Dsbt.log.noformat=true"
-
-before_script:
- - OLDEST_SHARED=`git log --format=%H $TRAVIS_COMMIT_RANGE | tail -n1`
- - OLDEST_COMMIT=`git log --format=%H | tail -n1`
- - if [ $OLDEST_SHARED == $OLDEST_COMMIT ]; then git fetch --unshallow; fi
-
-stages:
- - prepare
- - test
-
-# We do not use the built-in tests as generated by using multiple Scala
-# versions because the cache is not shared between stages with any
-# environmental differences.
-# Instead, we specify the version of Scala manually for each test (or leave it
-# as the default as defined in FIRRTL's build.sbt).
-jobs:
- include:
- # Because these write to the same install directory, they must run in the
- # same script
- - stage: prepare
- name: "Install: [Verilator, Yosys]"
- script:
- - bash .install_verilator.sh
- - verilator --version
- - bash .install_yosys.sh
- - yosys -V
- - stage: test
- name: "Unidoc builds (no warnings)"
- script:
- - sbt $SBT_ARGS unidoc
- - stage: test
- name: "Tests: FIRRTL (2.12)"
- script:
- - verilator --version
- - sbt $SBT_ARGS test
- - stage: test
- name: "Tests: FIRRTL (2.11)"
- script:
- - verilator --version
- - sbt ++2.11.12 $SBT_ARGS test
- - stage: test
- name: "Tests: chisel3 (2.12)"
- script:
- - verilator --version
- - sbt $SBT_ARGS clean assembly publishLocal
- - bash .run_chisel_tests.sh
- - stage: test
- name: "Formal equivalence: RocketCore"
- script:
- - yosys -V
- - "travis_wait 30 sleep 1800 &"
- - ./.run_formal_checks.sh RocketCore
- - stage: test
- name: "Formal equivalence: FPU"
- script:
- - yosys -V
- - "travis_wait 30 sleep 1800 &"
- - ./.run_formal_checks.sh FPU
- - stage: test
- name: "Formal equivalence: ICache"
- script:
- - yosys -V
- - "travis_wait 30 sleep 1800 &"
- - ./.run_formal_checks.sh ICache
- - stage: test
- name: "Formal equivalence: small expression-tree stress tests"
- script:
- - yosys -V
- - "travis_wait 30 sleep 1800 &"
- - ./.run_formal_checks.sh Ops
- - ./.run_formal_checks.sh AddNot
- - stage: test
- script:
- - benchmark/scripts/benchmark_cold_compile.py -N 2 --designs regress/ICache.fir --versions HEAD
- - stage: test
- name: "[Release Branch] Check Binary-compatibility"
- script:
- - sbt compile
- - sbt +mimaReportBinaryIssues
diff --git a/covDump.py b/covDump.py
new file mode 100755
index 00000000..c0399135
--- /dev/null
+++ b/covDump.py
@@ -0,0 +1,155 @@
+#!/usr/bin/python3.6
+
+"""
+FIRRTL Compiler can not instrument system task
+To continue after fuzz end, coverage map has to be saved.
+Also, coverage map has to be restored.
+
+It simply instruments store, and restore coverage map to
+input verilog file using hierarchy.txt.
+"""
+
+import sys
+import argparse
+
+""" Recursively find paths to all covMap in module """
+def findCovPath(modInst, modCovSize, module):
+
+ if module not in list(modInst.keys()):
+ return []
+
+ covPaths = []
+ covSize = modCovSize[module]
+ if not modInst[module] and covSize == 0:
+ covPaths = []
+ elif not modInst[module]:
+ covPaths = [ module + '_cov']
+ else:
+ if covSize != 0:
+ covPaths.append(module + '_cov')
+ for (instance, instModule) in modInst[module]:
+ paths = findCovPath(modInst, modCovSize, instModule)
+ for path in paths:
+ covPaths.append(instance + '.' + path)
+
+ return covPaths
+
+def main():
+ parser = argparse.ArgumentParser(description='Argparser for save/restore coverage map instrument')
+
+ parser.add_argument('--vfile', required=True, help='Input verilog file')
+ parser.add_argument('--top', required=True, help='Top level module')
+ parser.add_argument('--hier', required=True, help='Hierarchy file')
+
+ args = parser.parse_args()
+
+ vfile = args.vfile
+ new_vfile = vfile[:-2] + '_tmp.v'
+ hierarchy = args.hier
+ toplevel = args.top
+
+ modInst = {}
+ modCovSize = {}
+
+ fd = open(hierarchy, 'r')
+ while True:
+ line = fd.readline()
+ if not line: break
+ splits = line.split('\t')
+ if splits[0] != '':
+ module = splits[0]
+ numInst = splits[1]
+ covSize = int(splits[2][:-1])
+ instances = []
+ for i in range(int(numInst)):
+ inLine = fd.readline()
+ if not inLine: break
+ inSplits = inLine.split('\t')
+
+ instance = inSplits[1]
+ instModule = inSplits[2][:-1]
+ instances.append((instance, instModule))
+
+ modInst[module] = instances
+ modCovSize[module] = covSize
+ fd.close()
+
+ covPaths = findCovPath(modInst, modCovSize, toplevel)
+
+ covSizes = []
+ for path in covPaths:
+ last = path.split('.')[-1]
+ lastModule = last[:-4]
+ covSizes.append(modCovSize[lastModule])
+
+ covPathSize = list(zip(covPaths, covSizes))
+
+ topPaths = []
+ for path in covPaths:
+ topPaths.append(toplevel + '.' + path)
+ print(toplevel + '.' + path)
+
+ fd = open(vfile, 'r')
+ nfd = open(new_vfile, 'w')
+
+ nfd.write('`define STRINGIFY(x) `"x`"\n')
+ nfd.write('`define CONCAT(x,y) x/y\n')
+ nfd.write('`define INDEX(x,y) x-y\n\n')
+ while True:
+ line = fd.readline()
+ if not line: break
+ if 'module ' + toplevel in line:
+ nfd.write(line)
+ nfd.write('`ifdef MULTICORE\n')
+ nfd.write(' input cov_store,\n')
+ nfd.write(' input cov_restore,\n')
+ nfd.write(' input [7:0] proc_num,\n')
+ nfd.write('`endif\n')
+ while True:
+ inLine = fd.readline()
+ if not inLine: break
+ if ');' in inLine:
+ nfd.write(');\n')
+
+ nfd.write('`ifdef MULTICORE\n')
+ nfd.write(' integer i;\n')
+ nfd.write(' integer fd;\n')
+ nfd.write(' integer c;\n')
+ nfd.write(' always @(posedge clock) begin\n')
+ nfd.write(' if (cov_restore) begin\n')
+
+ for (path, size) in covPathSize:
+ nfd.write(' fd = $fopen(`STRINGIFY(`CONCAT(`OUT,covmap/{}.dat)), "r");\n'.format(path))
+ nfd.write(' if (fd == 0)\n')
+ nfd.write(' $display("No saved %s, starting from zero", "{}");\n'.format(path))
+ nfd.write(' else begin\n')
+ nfd.write(' for (i=0; i<{}; i=i+1) begin\n'.format(size))
+ nfd.write(' c = $fgetc(fd);\n');
+ nfd.write(' {}[i] = c[0];\n'.format(path))
+ nfd.write(' end\n')
+ nfd.write(' $fclose(fd);\n')
+ nfd.write(' end\n')
+
+ nfd.write(' end\n')
+ nfd.write(' if (cov_store) begin\n')
+
+ for (path, size) in covPathSize:
+ nfd.write(' fd = $fopen($sformatf(`STRINGIFY(`CONCAT(`OUT,`INDEX(covmap,%0d/{}.dat))), proc_num), "w");\n'.format(path))
+ nfd.write(' for (i=0; i<{}; i=i+1)\n'.format(size))
+ nfd.write(' $fwrite(fd, "%0b", {}[i]);\n'.format(path))
+ nfd.write(' $fclose(fd);\n')
+ nfd.write(' end\n')
+ nfd.write(' end\n')
+ nfd.write('`endif\n')
+ break
+ else:
+ nfd.write(inLine)
+ else:
+ nfd.write(line)
+
+ fd.close()
+ nfd.close()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/regress/retop_firrtl.py b/regress/retop_firrtl.py
new file mode 100755
index 00000000..c4fe1ff9
--- /dev/null
+++ b/regress/retop_firrtl.py
@@ -0,0 +1,60 @@
+#!/usr/bin/python
+
+import sys
+import os
+import re
+from collections import defaultdict
+from split_firrtl import split_firrtl
+
+def get_submods(modules):
+ submods = defaultdict(list)
+ pattern = re.compile('\s*inst\s+\S+\s+of\s+(\S+)\s+.*')
+
+ for mod, lines in modules.iteritems():
+ for line in lines:
+ m = pattern.match(line)
+ if m:
+ submods[mod].append(m.group(1))
+ return submods
+
+def submods_of(submodules, top):
+ mods = [top]
+
+ to_visit = submodules[top]
+ while len(to_visit) > 0:
+ head = to_visit.pop(0)
+ if not head in mods:
+ mods.append(head)
+ to_visit.extend(submodules[head])
+ return mods
+
+if __name__ == "__main__":
+ def error_out():
+ usage = "Usage: {} newtop infile outfile".format(os.path.basename(sys.argv[0]))
+ print(usage)
+ sys.exit(-1)
+ # Check number of arguments
+ if len(sys.argv) != 4:
+ error_out()
+ newtop = sys.argv[1]
+ infile = sys.argv[2]
+ outfile = sys.argv[3]
+ if not(os.path.isfile(infile)) :
+ print("infile must be a valid file!")
+ error_out()
+
+ with open(infile, "r") as f:
+ modules = split_firrtl(f.readlines())
+
+ if not(newtop in modules):
+ print("newtop must actually be a module!")
+ error_out()
+
+ submods = get_submods(modules)
+ new_mods = submods_of(submods, newtop)
+
+ with open(outfile, "w") as f:
+ f.write('circuit {} :\n'.format(newtop))
+ for mod in new_mods:
+ for line in modules[mod]:
+ f.write(line)
diff --git a/regress/split_firrtl.py b/regress/split_firrtl.py
new file mode 100755
index 00000000..3b8945b3
--- /dev/null
+++ b/regress/split_firrtl.py
@@ -0,0 +1,44 @@
+#!/usr/bin/python
+
+import sys
+import os
+import re
+from collections import defaultdict
+
+# Takes firrtl text, returns a dict from module name to module definition
+def split_firrtl(firrtl_lines):
+ modules = defaultdict(list)
+ current_mod = ""
+
+ pattern = re.compile('\s*(?:ext)?module\s+(\S+)\s*:\s*')
+ for line in firrtl_lines:
+ m = pattern.match(line)
+ if m:
+ current_mod = m.group(1)
+ if current_mod:
+ modules[current_mod].append(line)
+ return modules
+
+if __name__ == "__main__":
+ def error_out():
+ usage = "Usage: {} infile outdir".format(os.path.basename(sys.argv[0]))
+ print(usage)
+ sys.exit(-1)
+ # Check number of arguments
+ if len(sys.argv) != 3:
+ error_out()
+ infile = sys.argv[1]
+ outdir = sys.argv[2]
+ if not(os.path.isfile(infile)) :
+ print("infile must be a valid file!")
+ error_out()
+ if not(os.path.isdir(outdir)) :
+ print("outdir must be a valid directory!")
+ error_out()
+
+ with open(infile, "r") as f:
+ modules = split_firrtl(f.readlines())
+ for name, body in modules.iteritems():
+ with open(os.path.join(outdir, name + ".fir"), 'w') as w:
+ for line in body:
+ w.write(line)
diff --git a/src/main/scala/firrtl/Visitor.scala b/src/main/scala/firrtl/Visitor.scala
index 084a3006..092aa234 100644
--- a/src/main/scala/firrtl/Visitor.scala
+++ b/src/main/scala/firrtl/Visitor.scala
@@ -301,16 +301,17 @@ class Visitor(infoMode: InfoMode) extends AbstractParseTreeVisitor[FirrtlNode] w
case "reg" =>
val name = ctx.id(0).getText
val tpe = visitType(ctx.`type`())
- val (reset, init) = {
+ val (reset, init, rinfo) = {
val rb = ctx.reset_block()
if (rb != null) {
val sr = rb.simple_reset.simple_reset0()
- (visitExp(sr.exp(0)), visitExp(sr.exp(1)))
+ val innerInfo = if (info == NoInfo) visitInfo(Option(rb.info), ctx) else info
+ (visitExp(sr.exp(0)), visitExp(sr.exp(1)), innerInfo)
}
else
- (UIntLiteral(0, IntWidth(1)), Reference(name, tpe))
+ (UIntLiteral(0, IntWidth(1)), Reference(name, tpe), info)
}
- DefRegister(info, name, tpe, visitExp(ctx_exp(0)), reset, init)
+ DefRegister(rinfo, name, tpe, visitExp(ctx_exp(0)), reset, init)
case "mem" => visitMem(ctx)
case "cmem" =>
val (tpe, size) = visitCMemType(ctx.`type`())
diff --git a/src/main/scala/specdoctor/graphLedger.scala b/src/main/scala/specdoctor/graphLedger.scala
new file mode 100644
index 00000000..bda16000
--- /dev/null
+++ b/src/main/scala/specdoctor/graphLedger.scala
@@ -0,0 +1,670 @@
+// Copyright (C) 2011-2012 the original author or authors.
+// See the LICENCE.txt file distributed with this work for additional
+// information regarding copyright ownership.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// TODO: Fill in
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package specdoctor
+
+import firrtl._
+import firrtl.ir._
+
+import scala.reflect.ClassTag
+import scala.collection.mutable.ListBuffer
+import scala.collection.mutable
+
+
+// graphLedger sweeps fir file, build graphs of elements
+object Node {
+ val types = Set("Port", "DefWire", "DefRegister", "DefNode", "DefMemory", "WDefInstance")
+
+ def apply(node: FirrtlNode): Node = {
+ assert(Node.types.contains(node.getClass.getSimpleName),
+ s"${node.serialize} is not an instance of Port/DefStatement\n")
+
+ val name = node match {
+ case port: Port => port.name
+ case wire: DefWire => wire.name
+ case reg: DefRegister => reg.name
+ case nod: DefNode => nod.name
+ case mem: DefMemory => mem.name
+ case winst: WDefInstance => winst.name
+ case _ =>
+ throw new Exception(s"${node.serialize} does not have name")
+ }
+ new Node(node, name)
+ }
+
+ def hasType(n: FirrtlNode): Boolean = types.contains(n.getClass.getSimpleName)
+
+ def findName(expr: Expression): String = expr match {
+ case WRef(refName, _, _, _) => refName
+ case WSubField(e, _, _, _) => findName(e)
+ case WSubIndex(e, _, _, _) => findName(e)
+ case WSubAccess(e, _, _, _) => findName(e)
+ case Reference(refName, _) => refName
+ case SubField(e, _, _) => findName(e)
+ case SubIndex(e, _, _) => findName(e)
+ case SubAccess(e, _, _) => findName(e)
+ case _ => // Mux, DoPrim, etc
+ throw new Exception(s"${expr.serialize} does not have statement")
+ }
+
+ //noinspection ScalaStyle
+ def findNames(expr: Expression): Set[String] = expr match {
+ case WRef(refName, _, _, _) => Set(refName)
+ case WSubField(e, _, _, _) => findNames(e)
+ case WSubIndex(e, _, _, _) => findNames(e)
+ case WSubAccess(e, _, _, _) => findNames(e)
+ case Reference(refName, _) => Set(refName)
+ case SubField(e, _, _) => findNames(e)
+ case SubIndex(e, _, _) => findNames(e)
+ case SubAccess(e, _, _) => findNames(e)
+ case Mux(_, tval, fval, _) => findNames(tval) ++ findNames(fval)
+ case DoPrim(_, args, _, _) => {
+ var set = Set[String]()
+ for (arg <- args) {
+ set = set ++ findNames(arg)
+ }
+ set
+ }
+ case _ => Set[String]()
+ }
+
+}
+
+class Node(val node: FirrtlNode, val name: String) {
+
+ def serialize: String = this.node.serialize
+
+ def get[T <: FirrtlNode : ClassTag]: T = node match {
+ case t: T => t
+ case _ =>
+ throw new Exception(s"${node.serialize} mismatch")
+ }
+
+ def c: String = this.node.getClass.getSimpleName
+
+ //noinspection ScalaStyle
+ /* Check if Node is used for explicit data flow */
+ def usedIn(expr: Expression, imp: Boolean = true): Boolean = expr match {
+ case WRef(refName, _, _, _) => refName == name
+ case WSubField(e, _, _, _) => usedIn(e)
+ case WSubIndex(e, _, _, _) => usedIn(e) // Actually, it is not used in loFirrtl
+ case WSubAccess(e, _, _, _) => usedIn(e) // This too
+ case Reference(refName, _) => refName == name
+ case SubField(e, _, _) => usedIn(e)
+ case SubIndex(e, _, _) => usedIn(e)
+ case SubAccess(e, _, _) => usedIn(e)
+ case Mux(cond, tval, fval, _) =>
+ if (imp) usedIn(cond) || usedIn(tval) || usedIn(fval) // Catch implicit data flow
+ else usedIn(tval) || usedIn(fval)
+ case DoPrim(_, args, _, _) => {
+ var used = false
+ for (arg <- args) {
+ used = used | usedIn(arg)
+ }
+ used
+ }
+ case _ => false
+ }
+
+ /* Get port name of the expression for this node */
+ def portIn(expr: Expression): Set[(String, Seq[String])] = {
+ val ret = _getPort(expr).map((name, _))
+ // Connected WDefInstance should have at lead one connected port
+ assert(ret.nonEmpty, s"Does not have port: [${expr.serialize}]")
+
+ ret
+ }
+
+ //noinspection ScalaStyle
+ def _getPort(expr: Expression): Set[Seq[String]] = expr match {
+ // WDefInstance
+ case WSubField(e, n, _, _) => e match {
+ case ref: WRef if (ref.name == name) => Set(Seq(n))
+ case _ => _getPort(e).map(_ :+ n)
+ }
+ case WSubAccess(e, i, _, _) => e match {
+ case ref: WRef if (ref.name == name) =>
+ throw new NotImplementedError(s"_getPort: ${expr.serialize}")
+ case _ => _getPort(e)
+ }
+ case wsa: WSubAccess => _getPort(wsa.expr)
+ case wsi: WSubIndex => _getPort(wsi.expr)
+ case Mux(cond, tval, fval, _) => _getPort(cond) ++ _getPort(tval) ++ _getPort(fval)
+ case DoPrim(_, args, _, _) => args.map(_getPort(_)).reduce(_++_)
+ case _ => Set()
+ }
+}
+
+// graphLedger
+// 1) Generate graph which consists of Statement (DefRegister, DefNode
+// WDefInstance, Port)
+// 2) Find all memory related to the 'Valid' io signals
+// TODO: 3) Find all components controlling the memory related to the 'Valid' io signals
+// TODO: 4) Continue over module boundary
+class graphLedger(val module: DefModule) {
+ val mName = module.name
+ val mPorts = module.ports.toSet
+
+ private val Nodes = mutable.Map[String, Node]()
+ private val G = mutable.Map[String, Set[String]]()
+ private val R = mutable.Map[String, Set[String]]()
+ private val expG = mutable.Map[String, Set[String]]()
+
+ // r: reverse, N: node, E: Expression, M: mem, I: instance, P: port, 2: (sink) -> (source)
+ private val rN2IP = mutable.Map[String, Set[(String, String)]]()
+ private val rN2MP = mutable.Map[String, Set[(String, String)]]()
+ private val rMP2N = mutable.Map[(String, String), Map[String, String]]()
+ // We use IP2E instead of IP2N because Expression preserves the connection info
+ private val rIP2E = mutable.Map[(String, String), Expression]()
+
+ val N2E = mutable.Map[String, Expression]()
+
+ private lazy val memorys: Set[DefMemory] = getNodes[DefMemory]
+ private lazy val instances: Set[WDefInstance] = getNodes[WDefInstance]
+
+ private val visited: mutable.Set[String] = mutable.Set()
+
+ def getNodes[T <: FirrtlNode : ClassTag]: Set[T] = {
+ Nodes.map(_._2.node).flatMap {
+ case e: T => Some(e)
+ case _ => None
+ }.toSet
+ }
+
+ def IP2E: Map[(String, String), Expression] = rIP2E.toMap
+
+ def parse: Unit = {
+ this.module match {
+ case ext: ExtModule =>
+ print(s"$mName is external module\n")
+ case mod: Module =>
+ buildG
+ reverseG
+ }
+ }
+
+ def clear: Unit = {
+ visited.clear
+ }
+
+ private def buildG: Unit = {
+ this.module foreachPort findNode
+ this.module foreachStmt findNode
+
+ for ((n, _) <- G) {
+ val sinks = ListBuffer[String]()
+ this.module foreachStmt findEdge(Nodes(n), sinks)
+ G(n) = sinks.toSet
+
+ expG(n) = Set[String]()
+ }
+
+ for ((n, _) <- expG) {
+ val sinks = ListBuffer[String]()
+ this.module foreachStmt findEdgeExp(Nodes(n), sinks)
+ expG(n) = sinks.toSet
+ }
+ }
+
+ private def reverseG: Unit = {
+ for ((n, _) <- G) {
+ val sources = ListBuffer[String]()
+ for ((m, sinks) <- G) {
+ if (sinks.contains(n)) {
+ sources.append(m)
+ }
+ }
+ R(n) = sources.toSet
+ }
+ }
+
+ private def findNode(s: FirrtlNode): Unit = {
+ if (Node.hasType(s)) {
+ val n = Node(s)
+ Nodes(n.name) = n
+ G(n.name) = Set[String]()
+ }
+
+ s match {
+ case stmt: Statement =>
+ stmt foreachStmt findNode
+ case other => Unit
+ }
+ }
+
+ private def findEdgeExp(n: Node, sinks: ListBuffer[String])(s: Statement): Unit = {
+ s match {
+ case reg: DefRegister if (n.usedIn(reg.reset, false)) =>
+ sinks.append(reg.name)
+ case nod: DefNode if (n.usedIn(nod.value, false)) =>
+ sinks.append(nod.name)
+ case Connect(_, l, e) if (n.usedIn(e, false)) =>
+ sinks.append(Node.findName(l))
+ case _ => Unit
+ }
+
+ s foreachStmt findEdgeExp(n, sinks)
+ }
+
+ //noinspection ScalaStyle
+ /* Find explicit data flow edges */
+ private def findEdge(n: Node, sinks: ListBuffer[String])(s: Statement): Unit = {
+ s match {
+ case reg: DefRegister =>
+ if (n.usedIn(reg.reset)) {
+ sinks.append(reg.name)
+ }
+ case nod: DefNode =>
+ if (n.usedIn(nod.value)) {
+ sinks.append(nod.name)
+
+ updateN2XP(nod.name, nod.value, n)
+ }
+ updateN2E(nod.name, nod.value)
+ case Connect(_, l, e) =>
+ val lName = Node.findName(l)
+ if (n.usedIn(e)) {
+ sinks.append(lName)
+
+ updateN2XP(lName, e, n)
+ updateXP2X(lName, l, e, n)
+ // updateP2E(lName, e)
+ }
+ updateN2E(lName, e)
+ case _ => Unit // Port, DefWire, DefMemory, WDefInstance
+ }
+
+ s foreachStmt findEdge(n, sinks)
+ }
+
+ // rN2IP, rN2MP update
+ private def updateN2XP(sink: String, srcE: Expression, node: Node): Unit = {
+ node.c match {
+ case "WDefInstance" =>
+ rN2IP(sink) = rN2IP.getOrElse(sink, Set()) ++
+ node.portIn(srcE).map(x => (x._1, x._2.head))
+ case "DefMemory" =>
+ rN2MP(sink) = rN2MP.getOrElse(sink, Set()) ++
+ node.portIn(srcE).map(x => (x._1, x._2.head))
+ case _ => Unit
+ }
+ }
+
+ // rIP2E, rMP2N update
+ private def updateXP2X(sink: String, sinkE: Expression, srcE: Expression, node: Node): Unit = {
+ Seq(instances, memorys).map(_.exists(_.name == sink)) match {
+ case Seq(true, true) =>
+ throw new Exception(s"${sink} contains in both instances and memorys")
+ case Seq(true, false) =>
+ val IP = Nodes(sink).portIn(sinkE).head // Only one port is connected at once
+ rIP2E((IP._1, IP._2.head)) = srcE
+ case Seq(false, true) =>
+ val MPF = Nodes(sink).portIn(sinkE).head // Only one port is connected at once
+ val MP = (MPF._1, MPF._2.head)
+ rMP2N(MP) = rMP2N.getOrElse(MP, Map()) + (MPF._2.last -> node.name)
+ case _ => Unit
+ }
+ }
+
+ // N2E
+ private def updateN2E(sink: String, srcE: Expression): Unit = {
+ if (Set("WDefInstance", "DefMemory").contains(Nodes(sink).c))
+ return
+ if (N2E.keySet.contains(sink))
+ return
+
+ N2E(sink) = srcE
+ }
+
+ def getInstanceMap: Map[String, (String, Set[(String, Set[String])])] = {
+ val I2IP = instances.flatMap(i => {
+ visited.clear
+ val (srcs, ips) = findNodeSrcs(Set(i.name))
+ srcs("WDefInstance").map(x =>
+ (x, i.name, ips(x.get[WDefInstance])))
+ })
+
+ instances.map(i => {
+ val sink_srcPs = I2IP.flatMap{ case (srcN, sink, ports) =>
+ if (srcN.get[WDefInstance] == i)
+ Some((sink, ports.filter(_.contains("valid"))))
+ else
+ None
+ }
+ (i.name , (i.module, sink_srcPs))
+ }).toMap
+ }
+
+ def findPortSrcs(ports: Set[String]):
+ (Map[String, Set[Node]], Map[WDefInstance, Set[String]]) = {
+ /* ports should be subset of outward ports of module *
+ * Current design cannot discriminate outward ports and inward ports,
+ * so just select only outward */
+ assert(ports.subsetOf(mPorts.map(_.name)),
+ s"$mName does not have ports: {${ports.diff(mPorts.map(_.name))}}")
+
+ val oPorts = ports.intersect(mPorts.filter(_.direction == Output).map(_.name))
+
+ findNodeSrcs(oPorts)
+ }
+
+ def findExprSrcs(exprs: Set[Expression]):
+ (Map[String, Set[Node]], Map[WDefInstance, Set[String]]) = {
+ val exprNodes = exprs.flatMap(Node.findNames)
+
+ // Select exact (input) ports
+ val inPorts = mPorts.filter(_.direction == Input).map(_.name)
+ val inputs = exprNodes.intersect(inPorts).diff(visited)
+ visited ++= inputs
+
+ // Select memorys (TODO: continue over the ports connected to the memory)
+ val mems = exprNodes.intersect(memorys.map(_.name)).diff(visited)
+ visited ++= mems
+
+ // Select instances (and its port)
+ val insts = exprNodes.intersect(instances.map(_.name)).map(Nodes)
+ val iPorts = insts.map(i =>
+ (i.get[WDefInstance], exprs.filter(i.usedIn(_)).flatMap(i.portIn).map(_._2.head))
+ ).toMap
+
+ val (iNodes, oIPorts, iMems) = findOutPortsConnected(iPorts)
+
+ val nodes = exprNodes.diff(insts.map(_.name) ++ mems) ++ iNodes
+ val (nodeSrcs, instPorts) = findNodeSrcs(nodes)
+
+ val retNodeSrcs = Map(
+ "DefRegister" -> nodeSrcs("DefRegister"),
+ "DefMemory" -> (nodeSrcs("DefMemory") ++ mems.map(Nodes) ++ iMems.map(Nodes)),
+ "WDefInstance" -> (nodeSrcs("WDefInstance") ++ oIPorts.keySet.map(i => Nodes(i.name))),
+ "Port" -> (nodeSrcs("Port") ++ inputs.map(Nodes))
+ )
+ val retInstPorts = (oIPorts.keySet ++ instPorts.keySet).map(key =>
+ (key, oIPorts.getOrElse(key, Set()) ++ instPorts.getOrElse(key, Set()))
+ ).toMap
+
+ (retNodeSrcs, retInstPorts)
+ }
+
+ /* If instance and port (i.e., (inst, port)) is found,
+ it can be an input port which still needs backward slicing further.
+ We find all Nodes and 'real' output ports which are sources
+ */
+ private def findOutPortsConnected(ips: Map[WDefInstance, Set[String]]):
+ (Set[String], Map[WDefInstance, Set[String]], Set[String]) = {
+ val oIPorts = ips.map{
+ case (wdi, s) => (wdi, s.filter(p => !rIP2E.keySet.contains((wdi.name, p))))
+ }.filter(_._2.nonEmpty)
+
+ val exprs = rIP2E.filterKeys(ips.map{
+ case (wdi, s) => s.map(p => (wdi.name, p))
+ }.flatten.toSet.contains).values.toSet
+ val exprNodes = exprs.flatMap(Node.findNames)
+
+ val insts = exprNodes.intersect(instances.map(_.name))
+ val mems = exprNodes.intersect(memorys.map(_.name))
+ val nodes = exprNodes.diff(insts ++ mems)
+
+ val iPorts = insts.map(i => {
+ val n = Nodes(i)
+ (n.get[WDefInstance], exprs.filter(n.usedIn(_)).flatMap(n.portIn).map(_._2.head))
+ }).toMap.filter(_._2.nonEmpty)
+
+ if (iPorts.isEmpty) {
+ (nodes, oIPorts, mems)
+ } else {
+ val cont = findOutPortsConnected(iPorts)
+ val retOIPorts = (oIPorts.keySet ++ cont._2.keySet).map(key =>
+ (key, oIPorts.getOrElse(key, Set()) ++ cont._2.getOrElse(key, Set()))
+ ).toMap
+ (nodes ++ cont._1, retOIPorts, mems ++ cont._3)
+ }
+ }