STAR-future commited on
Commit
107d124
·
verified ·
1 Parent(s): 649fefb

add chips/yosys (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. chips/yosys/passes/CMakeLists.txt +11 -0
  2. chips/yosys/passes/cmds/CMakeLists.txt +224 -0
  3. chips/yosys/passes/cmds/abstract.cc +535 -0
  4. chips/yosys/passes/cmds/add.cc +232 -0
  5. chips/yosys/passes/cmds/autoname.cc +295 -0
  6. chips/yosys/passes/cmds/blackbox.cc +58 -0
  7. chips/yosys/passes/cmds/box_derive.cc +130 -0
  8. chips/yosys/passes/cmds/bugpoint.cc +681 -0
  9. chips/yosys/passes/cmds/check.cc +605 -0
  10. chips/yosys/passes/cmds/chformal.cc +448 -0
  11. chips/yosys/passes/cmds/chtype.cc +117 -0
  12. chips/yosys/passes/cmds/clean_zerowidth.cc +210 -0
  13. chips/yosys/passes/cmds/connect.cc +210 -0
  14. chips/yosys/passes/cmds/connwrappers.cc +203 -0
  15. chips/yosys/passes/cmds/copy.cc +58 -0
  16. chips/yosys/passes/cmds/delete.cc +137 -0
  17. chips/yosys/passes/cmds/design.cc +339 -0
  18. chips/yosys/passes/cmds/design_equal.cc +396 -0
  19. chips/yosys/passes/cmds/dft_tag.cc +1031 -0
  20. chips/yosys/passes/cmds/edgetypes.cc +112 -0
  21. chips/yosys/passes/cmds/example_dt.cc +271 -0
  22. chips/yosys/passes/cmds/exec.cc +209 -0
  23. chips/yosys/passes/cmds/future.cc +146 -0
  24. chips/yosys/passes/cmds/glift.cc +609 -0
  25. chips/yosys/passes/cmds/icell_liberty.cc +209 -0
  26. chips/yosys/passes/cmds/internal_stats.cc +124 -0
  27. chips/yosys/passes/cmds/linecoverage.cc +152 -0
  28. chips/yosys/passes/cmds/linux_perf.cc +102 -0
  29. chips/yosys/passes/cmds/logcmd.cc +115 -0
  30. chips/yosys/passes/cmds/logger.cc +185 -0
  31. chips/yosys/passes/cmds/ltp.cc +235 -0
  32. chips/yosys/passes/cmds/optbarriers.cc +549 -0
  33. chips/yosys/passes/cmds/plugin.cc +233 -0
  34. chips/yosys/passes/cmds/portarcs.cc +322 -0
  35. chips/yosys/passes/cmds/portlist.cc +101 -0
  36. chips/yosys/passes/cmds/printattrs.cc +96 -0
  37. chips/yosys/passes/cmds/rename.cc +647 -0
  38. chips/yosys/passes/cmds/scatter.cc +67 -0
  39. chips/yosys/passes/cmds/scc.cc +400 -0
  40. chips/yosys/passes/cmds/scratchpad.cc +146 -0
  41. chips/yosys/passes/cmds/sdc/CMakeLists.txt +9 -0
  42. chips/yosys/passes/cmds/sdc/graph-stubs.sdc +42 -0
  43. chips/yosys/passes/cmds/sdc/sdc.cc +796 -0
  44. chips/yosys/passes/cmds/select.cc +1851 -0
  45. chips/yosys/passes/cmds/setattr.cc +281 -0
  46. chips/yosys/passes/cmds/setenv.cc +61 -0
  47. chips/yosys/passes/cmds/setundef.cc +566 -0
  48. chips/yosys/passes/cmds/show.cc +1008 -0
  49. chips/yosys/passes/cmds/shuffle.cc +72 -0
  50. chips/yosys/passes/cmds/sort.cc +26 -0
chips/yosys/passes/CMakeLists.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ add_subdirectory(cmds)
2
+ add_subdirectory(equiv)
3
+ add_subdirectory(fsm)
4
+ add_subdirectory(hierarchy)
5
+ add_subdirectory(memory)
6
+ add_subdirectory(opt)
7
+ add_subdirectory(pmgen)
8
+ add_subdirectory(proc)
9
+ add_subdirectory(sat)
10
+ add_subdirectory(techmap)
11
+ add_subdirectory(tests)
chips/yosys/passes/cmds/CMakeLists.txt ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ add_subdirectory(sdc)
2
+
3
+ yosys_pass(exec
4
+ exec.cc
5
+ ENABLE_IF
6
+ YOSYS_ENABLE_SPAWN
7
+ )
8
+ yosys_pass(add
9
+ add.cc
10
+ )
11
+ yosys_pass(delete
12
+ delete.cc
13
+ )
14
+ yosys_pass(design
15
+ design.cc
16
+ ESSENTIAL
17
+ )
18
+ yosys_pass(design_equal
19
+ design_equal.cc
20
+ )
21
+ yosys_pass(select
22
+ select.cc
23
+ PROVIDES
24
+ cd
25
+ ls
26
+ ESSENTIAL
27
+ )
28
+ yosys_pass(show
29
+ show.cc
30
+ LIBRARIES
31
+ $<${YOSYS_ENABLE_READLINE}:PkgConfig::readline>
32
+ $<${YOSYS_ENABLE_EDITLINE}:PkgConfig::editline>
33
+ REQUIRES
34
+ read_rtlil
35
+ read_verilog
36
+ )
37
+ yosys_pass(viz
38
+ viz.cc
39
+ )
40
+ yosys_pass(rename
41
+ rename.cc
42
+ REQUIRES
43
+ write_verilog
44
+ )
45
+ yosys_pass(autoname
46
+ autoname.cc
47
+ )
48
+ yosys_pass(connect
49
+ connect.cc
50
+ )
51
+ yosys_pass(optbarriers
52
+ optbarriers.cc
53
+ )
54
+ yosys_pass(scatter
55
+ scatter.cc
56
+ )
57
+ yosys_pass(setundef
58
+ setundef.cc
59
+ )
60
+ yosys_pass(splitnets
61
+ splitnets.cc
62
+ )
63
+ yosys_pass(splitcells
64
+ splitcells.cc
65
+ )
66
+ yosys_pass(stat
67
+ stat.cc
68
+ REQUIRES
69
+ libparse
70
+ )
71
+ yosys_pass(internal_stats
72
+ internal_stats.cc
73
+ REQUIRES
74
+ libparse
75
+ )
76
+ yosys_pass(setattr
77
+ setattr.cc
78
+ PROVIDES
79
+ wbflip
80
+ setparam
81
+ chparam
82
+ )
83
+ yosys_pass(copy
84
+ copy.cc
85
+ )
86
+ yosys_pass(splice
87
+ splice.cc
88
+ )
89
+ yosys_pass(shuffle
90
+ shuffle.cc
91
+ )
92
+ yosys_pass(scc
93
+ scc.cc
94
+ )
95
+ yosys_pass(glift
96
+ glift.cc
97
+ )
98
+ yosys_pass(torder
99
+ torder.cc
100
+ )
101
+ yosys_pass(logcmd
102
+ logcmd.cc
103
+ )
104
+ yosys_pass(tee
105
+ tee.cc
106
+ )
107
+ yosys_pass(write_file
108
+ write_file.cc
109
+ )
110
+ yosys_pass(connwrappers
111
+ connwrappers.cc
112
+ )
113
+ yosys_pass(trace
114
+ trace.cc
115
+ PROVIDES
116
+ debug
117
+ )
118
+ yosys_pass(plugin
119
+ plugin.cc
120
+ INCLUDE_DIRS
121
+ ${pybind11_INCLUDE_DIR}
122
+ LIBRARIES
123
+ $<${YOSYS_ENABLE_PLUGINS}:${Dlfcn_LIBRARIES}>
124
+ $<${YOSYS_ENABLE_PYTHON}:Python3::Module>
125
+ ESSENTIAL
126
+ )
127
+ yosys_pass(check
128
+ check.cc
129
+ )
130
+ yosys_pass(edgetypes
131
+ edgetypes.cc
132
+ )
133
+ yosys_pass(portlist
134
+ portlist.cc
135
+ )
136
+ yosys_pass(chformal
137
+ chformal.cc
138
+ )
139
+ yosys_pass(chtype
140
+ chtype.cc
141
+ )
142
+ yosys_pass(blackbox
143
+ blackbox.cc
144
+ )
145
+ yosys_pass(ltp
146
+ ltp.cc
147
+ )
148
+ yosys_pass(linux_perf
149
+ linux_perf.cc
150
+ )
151
+ yosys_pass(bugpoint
152
+ bugpoint.cc
153
+ REQUIRES
154
+ proc_clean
155
+ opt_clean
156
+ design
157
+ ENABLE_IF
158
+ YOSYS_ENABLE_SPAWN
159
+ )
160
+ yosys_pass(scratchpad
161
+ scratchpad.cc
162
+ )
163
+ yosys_pass(logger
164
+ logger.cc
165
+ )
166
+ yosys_pass(printattrs
167
+ printattrs.cc
168
+ )
169
+ yosys_pass(sta
170
+ sta.cc
171
+ )
172
+ yosys_pass(clean_zerowidth
173
+ clean_zerowidth.cc
174
+ )
175
+ yosys_pass(xprop
176
+ xprop.cc
177
+ REQUIRES
178
+ bmuxmap
179
+ demuxmap
180
+ )
181
+ yosys_pass(dft_tag
182
+ dft_tag.cc
183
+ )
184
+ yosys_pass(future
185
+ future.cc
186
+ )
187
+ yosys_pass(box_derive
188
+ box_derive.cc
189
+ )
190
+ yosys_pass(example_dt
191
+ example_dt.cc
192
+ )
193
+ yosys_pass(portarcs
194
+ portarcs.cc
195
+ )
196
+ yosys_pass(wrapcell
197
+ wrapcell.cc
198
+ )
199
+ yosys_pass(setenv
200
+ setenv.cc
201
+ )
202
+ yosys_pass(abstract
203
+ abstract.cc
204
+ )
205
+ yosys_pass(test_select
206
+ test_select.cc
207
+ )
208
+ yosys_pass(timeest
209
+ timeest.cc
210
+ )
211
+ yosys_pass(linecoverage
212
+ linecoverage.cc
213
+ )
214
+ yosys_pass(sort
215
+ sort.cc
216
+ )
217
+ yosys_pass(icell_liberty
218
+ icell_liberty.cc
219
+ )
220
+ yosys_pass(symfpu
221
+ symfpu.cc
222
+ LIBRARIES
223
+ symfpu
224
+ )
chips/yosys/passes/cmds/abstract.cc ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "kernel/yosys.h"
2
+ #include "kernel/celltypes.h"
3
+ #include "kernel/ff.h"
4
+ #include "kernel/ffinit.h"
5
+ #include <variant>
6
+ #include <charconv>
7
+
8
+ USING_YOSYS_NAMESPACE
9
+ PRIVATE_NAMESPACE_BEGIN
10
+
11
+ struct EnableLogic {
12
+ SigBit bit;
13
+ bool pol;
14
+ };
15
+
16
+ enum SliceIndices {
17
+ RtlilSlice,
18
+ HdlSlice,
19
+ };
20
+
21
+ struct Slice {
22
+ SliceIndices indices;
23
+ int first;
24
+ int last;
25
+
26
+ Slice(SliceIndices indices, const std::string &slice) :
27
+ indices(indices)
28
+ {
29
+ if (slice.empty())
30
+ syntax_error(slice);
31
+ auto sep = slice.find(':');
32
+ const char *first_begin, *first_end, *last_begin, *last_end;
33
+ if (sep == std::string::npos) {
34
+ first_begin = last_begin = slice.c_str();
35
+ first_end = last_end = slice.c_str() + slice.length();
36
+ } else {
37
+ first_begin = slice.c_str();
38
+ first_end = first_begin + sep;
39
+
40
+ last_begin = first_end + 1;
41
+ last_end = slice.c_str() + slice.length();
42
+ }
43
+ first = parse_index(first_begin, first_end, slice);
44
+ last = parse_index(last_begin, last_end, slice);
45
+ }
46
+
47
+ static int parse_index(const char *begin, const char *end, const std::string &slice) {
48
+ int value = 0;
49
+ auto result = std::from_chars(begin, end, value, 10);
50
+ if (result.ptr != end || result.ptr == begin)
51
+ syntax_error(slice);
52
+ return value;
53
+ }
54
+
55
+ static void syntax_error(const std::string &slice) {
56
+ log_cmd_error("Invalid slice '%s', expected '<first>:<last>' or '<single>'\n", slice);
57
+ }
58
+
59
+ std::string to_string() const {
60
+ const char *option = indices == RtlilSlice ? "-rtlilslice" : "-slice";
61
+ if (first == last)
62
+ return stringf("%s %d", option, first);
63
+ else
64
+ return stringf("%s %d:%d", option, first, last);
65
+ }
66
+
67
+ int wire_offset(RTLIL::Wire *wire, int index) const {
68
+ int rtl_offset = indices == RtlilSlice ? index : wire->from_hdl_index(index);
69
+ if (rtl_offset < 0 || rtl_offset >= wire->width) {
70
+ log_error("Slice %s is out of bounds for wire %s in module %s\n", to_string(), wire, wire->module);
71
+ }
72
+ return rtl_offset;
73
+ }
74
+
75
+ std::pair<int, int> wire_range(RTLIL::Wire *wire) const {
76
+ int rtl_first = wire_offset(wire, first);
77
+ int rtl_last = wire_offset(wire, last);
78
+ if (rtl_first > rtl_last)
79
+ std::swap(rtl_first, rtl_last);
80
+ return {rtl_first, rtl_last + 1};
81
+ }
82
+ };
83
+
84
+ void emit_mux_anyseq(Module* mod, const SigSpec& mux_input, const SigSpec& mux_output, EnableLogic enable) {
85
+ auto anyseq = mod->Anyseq(NEW_ID, mux_input.size());
86
+ if (enable.bit == (enable.pol ? State::S1 : State::S0)) {
87
+ mod->connect(mux_output, anyseq);
88
+ }
89
+ SigSpec mux_a, mux_b;
90
+ if (enable.pol) {
91
+ mux_a = mux_input;
92
+ mux_b = anyseq;
93
+ } else {
94
+ mux_a = anyseq;
95
+ mux_b = mux_input;
96
+ }
97
+ (void)mod->addMux(NEW_ID,
98
+ mux_a,
99
+ mux_b,
100
+ enable.bit,
101
+ mux_output);
102
+ }
103
+
104
+ bool abstract_state_port(FfData& ff, SigSpec& port_sig, std::set<int> offsets, EnableLogic enable) {
105
+ Wire* abstracted = ff.module->addWire(NEW_ID, offsets.size());
106
+ SigSpec mux_input;
107
+ int abstracted_idx = 0;
108
+ for (int d_idx = 0; d_idx < ff.width; d_idx++) {
109
+ if (offsets.count(d_idx)) {
110
+ mux_input.append(port_sig[d_idx]);
111
+ port_sig[d_idx].wire = abstracted;
112
+ port_sig[d_idx].offset = abstracted_idx;
113
+ log_assert(abstracted_idx < abstracted->width);
114
+ abstracted_idx++;
115
+ }
116
+ }
117
+ emit_mux_anyseq(ff.module, mux_input, abstracted, enable);
118
+ (void)ff.emit();
119
+ return true;
120
+ }
121
+
122
+ using SelReason=std::variant<Wire*, Cell*>;
123
+
124
+ dict<SigBit, std::vector<SelReason>> gather_selected_reps(Module* mod, const std::vector<Slice> &slices, SigMap& sigmap) {
125
+ dict<SigBit, std::vector<SelReason>> selected_reps;
126
+
127
+ if (slices.empty()) {
128
+ // Collect reps for all wire bits of selected wires
129
+ for (auto wire : mod->selected_wires())
130
+ for (auto bit : sigmap(wire))
131
+ selected_reps.insert(bit).first->second.push_back(wire);
132
+
133
+ // Collect reps for all output wire bits of selected cells
134
+ for (auto cell : mod->selected_cells())
135
+ for (auto conn : cell->connections())
136
+ if (cell->output(conn.first))
137
+ for (auto bit : conn.second.bits())
138
+ selected_reps.insert(sigmap(bit)).first->second.push_back(cell);
139
+ } else {
140
+ if (mod->selected_wires().size() != 1 || !mod->selected_cells().empty())
141
+ log_error("Slices are only supported for single-wire selections\n");
142
+
143
+ auto wire = mod->selected_wires()[0];
144
+
145
+ for (auto slice : slices) {
146
+ auto [begin, end] = slice.wire_range(wire);
147
+ for (int i = begin; i < end; i++) {
148
+ selected_reps.insert(sigmap(SigBit(wire, i))).first->second.push_back(wire);
149
+ }
150
+ }
151
+
152
+ }
153
+ return selected_reps;
154
+ }
155
+
156
+ void explain_selections(const std::vector<SelReason>& reasons) {
157
+ for (std::variant<Wire*, Cell*> reason : reasons) {
158
+ if (Cell** cell_reason = std::get_if<Cell*>(&reason))
159
+ log_debug("\tcell %s\n", (*cell_reason)->name);
160
+ else if (Wire** wire_reason = std::get_if<Wire*>(&reason))
161
+ log_debug("\twire %s\n", (*wire_reason)->name);
162
+ else
163
+ log_assert(false && "insane reason variant\n");
164
+ }
165
+ }
166
+
167
+ unsigned int abstract_state(Module* mod, EnableLogic enable, const std::vector<Slice> &slices) {
168
+ CellTypes ct;
169
+ ct.setup_internals_ff();
170
+ SigMap sigmap(mod);
171
+ dict<SigBit, std::vector<SelReason>> selected_reps = gather_selected_reps(mod, slices, sigmap);
172
+
173
+ unsigned int changed = 0;
174
+ std::vector<FfData> ffs;
175
+ // Abstract flop inputs if they're driving a selected output rep
176
+ for (auto cell : mod->cells()) {
177
+ if (!ct.cell_types.count(cell->type))
178
+ continue;
179
+ FfData ff(nullptr, cell);
180
+ if (ff.has_sr)
181
+ log_cmd_error("SR not supported\n");
182
+ ffs.push_back(ff);
183
+ }
184
+ for (auto ff : ffs) {
185
+ // A bit inefficient
186
+ std::set<int> offsets_to_abstract;
187
+ for (int i = 0; i < GetSize(ff.sig_q); i++) {
188
+ SigBit bit = ff.sig_q[i];
189
+ if (selected_reps.count(sigmap(bit))) {
190
+ log_debug("Abstracting state for %s.Q[%i] in module %s due to selections:\n", ff.cell, i, mod);
191
+ explain_selections(selected_reps.at(sigmap(bit)));
192
+ offsets_to_abstract.insert(i);
193
+ }
194
+ }
195
+
196
+ if (offsets_to_abstract.empty())
197
+ continue;
198
+
199
+ // Normalize to simpler FF
200
+ ff.unmap_ce();
201
+ ff.unmap_srst();
202
+ if (ff.has_arst)
203
+ ff.arst_to_aload();
204
+
205
+ bool cell_changed = false;
206
+
207
+ if (ff.has_aload)
208
+ cell_changed = abstract_state_port(ff, ff.sig_ad, offsets_to_abstract, enable);
209
+ cell_changed |= abstract_state_port(ff, ff.sig_d, offsets_to_abstract, enable);
210
+ changed += cell_changed;
211
+ }
212
+ return changed;
213
+ }
214
+
215
+ bool abstract_value_cell_port(Module* mod, Cell* cell, std::set<int> offsets, IdString port_name, EnableLogic enable) {
216
+ Wire* to_abstract = mod->addWire(NEW_ID, offsets.size());
217
+ SigSpec mux_input;
218
+ SigSpec mux_output;
219
+ const SigSpec& old_port = cell->getPort(port_name);
220
+ SigSpec new_port = old_port;
221
+ int to_abstract_idx = 0;
222
+ for (int port_idx = 0; port_idx < old_port.size(); port_idx++) {
223
+ if (offsets.count(port_idx)) {
224
+ mux_output.append(old_port[port_idx]);
225
+ SigBit in_bit {to_abstract, to_abstract_idx};
226
+ new_port.replace(port_idx, in_bit);
227
+ mux_input.append(in_bit);
228
+ log_assert(to_abstract_idx < to_abstract->width);
229
+ to_abstract_idx++;
230
+ }
231
+ }
232
+ cell->setPort(port_name, new_port);
233
+ emit_mux_anyseq(mod, mux_input, mux_output, enable);
234
+ return true;
235
+ }
236
+
237
+ bool abstract_value_mod_port(Module* mod, Wire* wire, std::set<int> offsets, EnableLogic enable) {
238
+ Wire* to_abstract = mod->addWire(NEW_ID, wire);
239
+ to_abstract->port_input = true;
240
+ to_abstract->port_id = wire->port_id;
241
+ wire->port_input = false;
242
+ wire->port_id = 0;
243
+ mod->swap_names(wire, to_abstract);
244
+ SigSpec mux_input;
245
+ SigSpec mux_output;
246
+ SigSpec direct_lhs;
247
+ SigSpec direct_rhs;
248
+ for (int port_idx = 0; port_idx < wire->width; port_idx++) {
249
+ if (offsets.count(port_idx)) {
250
+ mux_output.append(SigBit(wire, port_idx));
251
+ mux_input.append(SigBit(to_abstract, port_idx));
252
+ } else {
253
+ direct_lhs.append(SigBit(wire, port_idx));
254
+ direct_rhs.append(SigBit(to_abstract, port_idx));
255
+ }
256
+ }
257
+ mod->connections_.push_back(SigSig(direct_lhs, direct_rhs));
258
+ emit_mux_anyseq(mod, mux_input, mux_output, enable);
259
+ return true;
260
+ }
261
+
262
+ unsigned int abstract_value(Module* mod, EnableLogic enable, const std::vector<Slice> &slices) {
263
+ SigMap sigmap(mod);
264
+ dict<SigBit, std::vector<SelReason>> selected_reps = gather_selected_reps(mod, slices, sigmap);
265
+ unsigned int changed = 0;
266
+ std::vector<Cell*> cells_snapshot = mod->cells();
267
+ for (auto cell : cells_snapshot) {
268
+ for (auto conn : cell->connections())
269
+ if (cell->output(conn.first)) {
270
+ std::set<int> offsets_to_abstract;
271
+ for (int i = 0; i < conn.second.size(); i++) {
272
+ if (selected_reps.count(sigmap(conn.second[i]))) {
273
+ log_debug("Abstracting value for %s.%s[%i] in module %s due to selections:\n",
274
+ cell, PooledName(cell->module, conn.first).unescape(), i, mod);
275
+ explain_selections(selected_reps.at(sigmap(conn.second[i])));
276
+ offsets_to_abstract.insert(i);
277
+ }
278
+ }
279
+ if (offsets_to_abstract.empty())
280
+ continue;
281
+
282
+ changed += abstract_value_cell_port(mod, cell, offsets_to_abstract, conn.first, enable);
283
+ }
284
+ }
285
+ std::vector<Wire*> wires_snapshot = mod->wires();
286
+ for (auto wire : wires_snapshot)
287
+ if (wire->port_input) {
288
+ std::set<int> offsets_to_abstract;
289
+ for (auto bit : SigSpec(wire))
290
+ if (selected_reps.count(sigmap(bit))) {
291
+ log_debug("Abstracting value for module input port bit %s in module %s due to selections:\n",
292
+ log_signal(bit), mod);
293
+ explain_selections(selected_reps.at(sigmap(bit)));
294
+ offsets_to_abstract.insert(bit.offset);
295
+ }
296
+ if (offsets_to_abstract.empty())
297
+ continue;
298
+
299
+ changed += abstract_value_mod_port(mod, wire, offsets_to_abstract, enable);
300
+ }
301
+ return changed;
302
+ }
303
+
304
+ unsigned int abstract_init(Module* mod, const std::vector<Slice> &slices) {
305
+ unsigned int changed = 0;
306
+ FfInitVals initvals;
307
+ SigMap sigmap(mod);
308
+ dict<SigBit, std::vector<SelReason>> selected_reps = gather_selected_reps(mod, slices, sigmap);
309
+ initvals.set(&sigmap, mod);
310
+ for (auto bit : selected_reps) {
311
+ log_debug("Removing init bit on %s due to selections:\n", log_signal(bit.first));
312
+ explain_selections(bit.second);
313
+ initvals.remove_init(bit.first);
314
+ changed++;
315
+ }
316
+ return changed;
317
+ }
318
+
319
+ struct AbstractPass : public Pass {
320
+ AbstractPass() : Pass("abstract", "replace signals with abstract values during formal verification") { }
321
+ void help() override {
322
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
323
+ log("\n");
324
+ log(" abstract [mode] [options] [selection]\n");
325
+ log("\n");
326
+ log("Perform abstraction of signals within the design. Abstraction replaces a signal\n");
327
+ log("with an unconstrained abstract value that can take an arbitrary concrete value\n");
328
+ log("during formal verification. The mode and options control when a signal should\n");
329
+ log("be abstracted and how it should affect FFs present in the design.\n");
330
+ log("\n");
331
+ log("Modes:\n");
332
+ log("\n");
333
+ log(" -state\n");
334
+ log(" The selected FFs will be modified to load a new abstract value on every\n");
335
+ log(" active clock edge, async reset or async load. This is independent of any\n");
336
+ log(" clock enable that may be present on the FF cell. Conditional abstraction\n");
337
+ log(" is supported with the -enable/-enabeln options. If present, the condition\n");
338
+ log(" is sampled at the same time as the FF would smaple the correspnding data\n");
339
+ log(" or async-data input whose value will be replaced with an abstract value.\n");
340
+ log("\n");
341
+ log(" The selection can be used to specify which state bits to abstract. For\n");
342
+ log(" each selected wire, any state bits that the wire is driven by will be\n");
343
+ log(" abstracted. For a selected FF cell, all of its state is abstracted.\n");
344
+ log(" Individual bits of a single wire can be abtracted using the -slice and\n");
345
+ log(" -rtlilslice options.\n");
346
+ log("\n");
347
+ log(" -init\n");
348
+ log(" The selected FFs will be modified to have an abstract initial value.\n");
349
+ log(" The -enable/-enablen options are not supported in this mode.\n");
350
+ log(" \n");
351
+ log(" The selection is used in the same way as it is for the -state mode.\n");
352
+ log("\n");
353
+ log(" -value\n");
354
+ log(" The drivers of the selected signals will be replaced with an abstract\n");
355
+ log(" value. In this mode, the abstract value can change at any time and is\n");
356
+ log(" not synchronized to any clock or other signal. Conditional abstraction\n");
357
+ log(" is supported with the -enable/-enablen options. The condition will\n");
358
+ log(" combinationally select between the original driver and the abstract\n");
359
+ log(" value.\n");
360
+ log("\n");
361
+ log(" The selection can be used to specify which output bits of which drivers\n");
362
+ log(" to abtract. For a selected cell, all its output bits will be abstracted.\n");
363
+ log(" For a selected wire, every output bit that is driving the wire will be\n");
364
+ log(" abstracted. Individual bits of a single wire can be abstracted using the\n");
365
+ log(" -slice and -rtlilslice options.\n");
366
+ log("\n");
367
+ log(" -enable <wire-name>\n");
368
+ log(" -enablen <wire-name>\n");
369
+ log(" Perform conditional abstraction with a named single bit wire as\n");
370
+ log(" condition. For -enable the wire is used as an active-high condition and\n");
371
+ log(" for -enablen as an active-low condition. See the description of the\n");
372
+ log(" -state and -value modes for details on how the condition affects the\n");
373
+ log(" abstractions performed by either mode. This option is not supported in\n");
374
+ log(" the -init mode.\n");
375
+ log("\n");
376
+ log(" -initstates <n>\n");
377
+ log(" Perform conditional abstraction for the first <n> time steps. See the\n");
378
+ log(" description of the -state and -value modes for details on how the\n");
379
+ log(" condition affects the abstractions performed by either mode. This option\n");
380
+ log(" is not supported in the -init mode.\n");
381
+ log("\n");
382
+ log(" -slice <lhs>:<rhs>\n");
383
+ log(" -slice <index>\n");
384
+ log(" -rtlilslice <lhs>:<rhs>\n");
385
+ log(" -rtlilslice <index>\n");
386
+ log(" Limit the abstraction to a slice of a single selected wire. The targeted\n");
387
+ log(" bits of the wire can be given as an inclusive range of indices or as a\n");
388
+ log(" single index. When using the -slice option, the indices are interpreted\n");
389
+ log(" following the source level declaration of the wire. This means the\n");
390
+ log(" -slice option will respect declarations with a non-zero-based index range\n");
391
+ log(" or with reversed bitorder. The -rtlilslice options will always use\n");
392
+ log(" zero-based indexing where index 0 corresponds to the least significant\n");
393
+ log(" bit of the wire.\n");
394
+ log("\n");
395
+ }
396
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override {
397
+ log_header(design, "Executing ABSTRACT pass.\n");
398
+
399
+ size_t argidx;
400
+ enum Mode {
401
+ None,
402
+ State,
403
+ Initial,
404
+ Value,
405
+ };
406
+ Mode mode = Mode::None;
407
+ enum Enable {
408
+ Always = -1,
409
+ ActiveLow = false, // ensuring we can use bool(enable)
410
+ ActiveHigh = true,
411
+ Initstates = 2,
412
+ };
413
+ Enable enable = Enable::Always;
414
+ int initstates = 0;
415
+ std::string enable_name;
416
+ std::vector<Slice> slices;
417
+ for (argidx = 1; argidx < args.size(); argidx++)
418
+ {
419
+ std::string arg = args[argidx];
420
+ if (arg == "-state") {
421
+ mode = State;
422
+ continue;
423
+ }
424
+ if (arg == "-init") {
425
+ mode = Initial;
426
+ continue;
427
+ }
428
+ if (arg == "-value") {
429
+ mode = Value;
430
+ continue;
431
+ }
432
+ if (arg == "-enable" && argidx + 1 < args.size()) {
433
+ if (enable != Enable::Always)
434
+ log_cmd_error("Multiple enable condition are not supported\n");
435
+ enable_name = args[++argidx];
436
+ enable = Enable::ActiveHigh;
437
+ continue;
438
+ }
439
+ if (arg == "-enablen" && argidx + 1 < args.size()) {
440
+ if (enable != Enable::Always)
441
+ log_cmd_error("Multiple enable condition are not supported\n");
442
+ enable_name = args[++argidx];
443
+ enable = Enable::ActiveLow;
444
+ continue;
445
+ }
446
+ if (arg == "-initstates" && argidx + 1 < args.size()) {
447
+ if (enable != Enable::Always)
448
+ log_cmd_error("Multiple enable condition are not supported\n");
449
+ initstates = atoi(args[++argidx].c_str());
450
+ enable = Enable::Initstates;
451
+ continue;
452
+ }
453
+ if (arg == "-slice" && argidx + 1 < args.size()) {
454
+ slices.emplace_back(SliceIndices::HdlSlice, args[++argidx]);
455
+ continue;
456
+ }
457
+ if (arg == "-rtlilslice" && argidx + 1 < args.size()) {
458
+ slices.emplace_back(SliceIndices::RtlilSlice, args[++argidx]);
459
+ continue;
460
+ }
461
+ break;
462
+ }
463
+ extra_args(args, argidx, design);
464
+
465
+ if (enable != Enable::Always) {
466
+ if (mode == Mode::Initial)
467
+ log_cmd_error("Conditional initial value abstraction is not supported\n");
468
+
469
+ switch (enable) {
470
+ case Enable::Always:
471
+ log_assert(false);
472
+ YS_FALLTHROUGH
473
+ case Enable::ActiveLow:
474
+ case Enable::ActiveHigh: {
475
+ if (enable_name.empty())
476
+ log_cmd_error("Unspecified enable wire\n");
477
+ } break;
478
+ case Enable::Initstates: {
479
+ if (initstates <= 0)
480
+ log_cmd_error("Number of initial time steps must be positive\n");
481
+ } break;
482
+ }
483
+ }
484
+
485
+ unsigned int changed = 0;
486
+ if ((mode == State) || (mode == Value)) {
487
+ for (auto mod : design->selected_modules()) {
488
+ EnableLogic enable_logic;
489
+
490
+ switch (enable) {
491
+ case Enable::Always: {
492
+ enable_logic = { State::S1, true };
493
+ } break;
494
+ case Enable::ActiveLow:
495
+ case Enable::ActiveHigh: {
496
+ Wire *enable_wire = mod->wire("\\" + enable_name);
497
+ if (!enable_wire)
498
+ log_cmd_error("Enable wire %s not found in module %s\n", enable_name, mod->name);
499
+ if (GetSize(enable_wire) != 1)
500
+ log_cmd_error("Enable wire %s must have width 1 but has width %d in module %s\n",
501
+ enable_name, GetSize(enable_wire), mod->name);
502
+ enable_logic = { enable_wire, enable == Enable::ActiveHigh };
503
+ } break;
504
+ case Enable::Initstates: {
505
+ SigBit in_init_states = mod->Initstate(NEW_ID);
506
+ for (int i = 1; i < initstates; i++) {
507
+ Wire *in_init_states_q = mod->addWire(NEW_ID);
508
+ mod->addFf(NEW_ID, in_init_states, in_init_states_q);
509
+ in_init_states_q->attributes[ID::init] = State::S1;
510
+ in_init_states = in_init_states_q;
511
+ }
512
+ enable_logic = { in_init_states, true };
513
+ } break;
514
+ }
515
+ if (mode == State)
516
+ changed += abstract_state(mod, enable_logic, slices);
517
+ else
518
+ changed += abstract_value(mod, enable_logic, slices);
519
+ }
520
+ if (mode == State)
521
+ log("Abstracted %d stateful cells.\n", changed);
522
+ else
523
+ log("Abstracted %d driver ports.\n", changed);
524
+ } else if (mode == Initial) {
525
+ for (auto mod : design->selected_modules()) {
526
+ changed += abstract_init(mod, slices);
527
+ }
528
+ log("Abstracted %d init bits.\n", changed);
529
+ } else {
530
+ log_cmd_error("No mode selected, see help message\n");
531
+ }
532
+ }
533
+ } AbstractPass;
534
+
535
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/add.cc ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+
22
+ USING_YOSYS_NAMESPACE
23
+ PRIVATE_NAMESPACE_BEGIN
24
+
25
+ static bool is_formal_celltype(const std::string &celltype)
26
+ {
27
+ if(celltype == "assert" || celltype == "assume" || celltype == "live" || celltype == "fair" || celltype == "cover")
28
+ return true;
29
+ else
30
+ return false;
31
+ }
32
+
33
+ static void add_formal(RTLIL::Module *module, const std::string &celltype, const std::string &name, const std::string &enable_name)
34
+ {
35
+ std::string escaped_name = RTLIL::escape_id(name);
36
+ std::string escaped_enable_name = (enable_name != "") ? RTLIL::escape_id(enable_name) : "";
37
+ RTLIL::Wire *wire = module->wire(escaped_name);
38
+ log_assert(is_formal_celltype(celltype));
39
+
40
+ if (wire == nullptr) {
41
+ log_error("Could not find wire with name \"%s\".\n", name);
42
+ }
43
+ else {
44
+ RTLIL::Cell *formal_cell = module->addCell(NEW_ID, "$" + celltype);
45
+ formal_cell->setPort(ID::A, wire);
46
+ if(enable_name == "") {
47
+ formal_cell->setPort(ID::EN, State::S1);
48
+ log("Added $%s cell for wire \"%s.%s\"\n", celltype, module->name.str(), name);
49
+ }
50
+ else {
51
+ RTLIL::Wire *enable_wire = module->wire(escaped_enable_name);
52
+ if(enable_wire == nullptr)
53
+ log_error("Could not find enable wire with name \"%s\".\n", enable_name);
54
+
55
+ formal_cell->setPort(ID::EN, enable_wire);
56
+ log("Added $%s cell for wire \"%s.%s\" enabled by wire \"%s.%s\".\n", celltype, module->name.str(), name, module->name.str(), enable_name);
57
+ }
58
+ }
59
+ }
60
+
61
+ static void add_wire(RTLIL::Design *design, RTLIL::Module *module, std::string name, int width, bool flag_input, bool flag_output, bool flag_global)
62
+ {
63
+ RTLIL::Wire *wire = nullptr;
64
+ name = RTLIL::escape_id(name);
65
+ IdString name_ref = design->twines().find(name);
66
+
67
+ if (module->count_id(name_ref) != 0)
68
+ {
69
+ wire = module->wire(name_ref);
70
+
71
+ if (wire != nullptr && wire->width != width)
72
+ wire = nullptr;
73
+
74
+ if (wire != nullptr && wire->port_input != flag_input)
75
+ wire = nullptr;
76
+
77
+ if (wire != nullptr && wire->port_output != flag_output)
78
+ wire = nullptr;
79
+
80
+ if (wire == nullptr)
81
+ log_cmd_error("Found incompatible object with same name in module %s!\n", module->name);
82
+
83
+ log("Module %s already has such an object.\n", module->name);
84
+ }
85
+ else
86
+ {
87
+ wire = module->addWire(name, width);
88
+ wire->port_input = flag_input;
89
+ wire->port_output = flag_output;
90
+
91
+ if (flag_input || flag_output) {
92
+ module->fixup_ports();
93
+ }
94
+
95
+ log("Added wire %s to module %s.\n", name, module->name);
96
+ }
97
+
98
+ if (!flag_global)
99
+ return;
100
+
101
+ IdString port_id = design->twines().add(name);
102
+
103
+ for (auto cell : module->cells())
104
+ {
105
+ RTLIL::Module *mod = design->module(cell->type);
106
+ if (mod == nullptr)
107
+ continue;
108
+ if (!mod->is_selected_whole())
109
+ continue;
110
+ if (mod->get_blackbox_attribute())
111
+ continue;
112
+ if (cell->hasPort(port_id))
113
+ continue;
114
+
115
+ cell->setPort(port_id, wire);
116
+ log("Added connection %s to cell %s.%s (%s).\n", name, module->name, cell->name, cell->type);
117
+ }
118
+ }
119
+
120
+ struct AddPass : public Pass {
121
+ AddPass() : Pass("add", "add objects to the design") { }
122
+ void help() override
123
+ {
124
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
125
+ log("\n");
126
+ log(" add <command> [selection]\n");
127
+ log("\n");
128
+ log("This command adds objects to the design. It operates on all fully selected\n");
129
+ log("modules. So e.g. 'add -wire foo' will add a wire foo to all selected modules.\n");
130
+ log("\n");
131
+ log("\n");
132
+ log(" add {-wire|-input|-inout|-output} <name> <width> [selection]\n");
133
+ log("\n");
134
+ log("Add a wire (input, inout, output port) with the given name and width. The\n");
135
+ log("command will fail if the object exists already and has different properties\n");
136
+ log("than the object to be created.\n");
137
+ log("\n");
138
+ log("\n");
139
+ log(" add -global_input <name> <width> [selection]\n");
140
+ log("\n");
141
+ log("Like 'add -input', but also connect the signal between instances of the\n");
142
+ log("selected modules.\n");
143
+ log("\n");
144
+ log("\n");
145
+ log(" add {-assert|-assume|-live|-fair|-cover} <name1> [-if <name2>]\n");
146
+ log("\n");
147
+ log("Add an $assert, $assume, etc. cell connected to a wire named name1, with its\n");
148
+ log("enable signal optionally connected to a wire named name2 (default: 1'b1).\n");
149
+ log("\n");
150
+ log("\n");
151
+ log(" add -mod <name[s]>\n");
152
+ log("\n");
153
+ log("Add module[s] with the specified name[s].\n");
154
+ log("\n");
155
+ }
156
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
157
+ {
158
+ std::string command;
159
+ std::string arg_name;
160
+ std::string enable_name = "";
161
+ bool arg_flag_input = false;
162
+ bool arg_flag_output = false;
163
+ bool arg_flag_global = false;
164
+ bool mod_mode = false;
165
+ int arg_width = 0;
166
+
167
+ size_t argidx;
168
+ for (argidx = 1; argidx < args.size(); argidx++)
169
+ {
170
+ std::string arg = args[argidx];
171
+ if (arg == "-wire" || arg == "-input" || arg == "-inout" || arg == "-output" || arg == "-global_input") {
172
+ if (argidx+2 >= args.size())
173
+ break;
174
+ command = "wire";
175
+ if (arg == "-input" || arg == "-inout" || arg == "-global_input")
176
+ arg_flag_input = true;
177
+ if (arg == "-output" || arg == "-inout")
178
+ arg_flag_output = true;
179
+ if (arg == "-global_input")
180
+ arg_flag_global = true;
181
+ arg_name = args[++argidx];
182
+ arg_width = atoi(args[++argidx].c_str());
183
+ continue;
184
+ }
185
+ if (arg == "-mod") {
186
+ mod_mode = true;
187
+ argidx++;
188
+ break;
189
+ }
190
+ if (arg.length() > 0 && arg[0] == '-' && is_formal_celltype(arg.substr(1))) {
191
+ if (argidx + 1 >= args.size())
192
+ break;
193
+ command = arg.substr(1);
194
+ arg_name = args[++argidx];
195
+ if (argidx + 2 < args.size() && args[argidx + 1] == "-if") {
196
+ enable_name = args[argidx + 2];
197
+ argidx += 2;
198
+ }
199
+ continue;
200
+ }
201
+ break;
202
+ }
203
+
204
+ if (mod_mode) {
205
+ for (; argidx < args.size(); argidx++)
206
+ design->addModule(RTLIL::escape_id(args[argidx]));
207
+ return;
208
+ }
209
+
210
+ extra_args(args, argidx, design);
211
+
212
+ bool selected_anything = false;
213
+ for (auto module : design->modules())
214
+ {
215
+ log_assert(module != nullptr);
216
+ if (!design->selected_whole_module(module->name))
217
+ continue;
218
+ if (module->get_bool_attribute(ID::blackbox))
219
+ continue;
220
+
221
+ selected_anything = true;
222
+ if (is_formal_celltype(command))
223
+ add_formal(module, command, arg_name, enable_name);
224
+ else if (command == "wire")
225
+ add_wire(design, module, arg_name, arg_width, arg_flag_input, arg_flag_output, arg_flag_global);
226
+ }
227
+ if (!selected_anything)
228
+ log_warning("No modules selected, or only blackboxes. Nothing was added.\n");
229
+ }
230
+ } AddPass;
231
+
232
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/autoname.cc ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+
21
+ #include "kernel/yosys.h"
22
+ #include <functional>
23
+ #include <queue>
24
+ #include <ranges>
25
+
26
+ USING_YOSYS_NAMESPACE
27
+ PRIVATE_NAMESPACE_BEGIN
28
+
29
+ // An "object" is a cell or a wire.
30
+ // An object is "private" if its name starts with a '$'.
31
+ //
32
+ // The "autoname" pass renames private objects based on public object names,
33
+ // with suffixes added to show the relationship to the public objects.
34
+ // The pass chooses the "best" names based on minimizing their "cost".
35
+
36
+ // The cost of a new name for a private object is the cost along a path
37
+ // to a publicly named object.
38
+ struct cost {
39
+ // score is a property of one "edge", not of the entire path.
40
+ // 0 if the neighbour drives the object, and the wire's fanout otherwise
41
+ unsigned int score = UINT_MAX;
42
+ // New name length
43
+ size_t length = SIZE_MAX;
44
+ // Earlier discovered connection wins
45
+ int edge_pos = 0;
46
+
47
+ auto operator<=>(const cost &) const = default;
48
+ };
49
+
50
+ // Endpoints of an "edge" are always a cell index and a wire index. Goofy, I know.
51
+ // SigSig connections (module->connections()) don't count
52
+ // as neighbors. This means that the equivalent of `assign $w1 = \w2;` won't lead
53
+ // to $w1 being renamed.
54
+ struct Edge {
55
+ // Cell port name at which the wire connects to the cell
56
+ IdString port;
57
+ int cell;
58
+ int wire;
59
+ bool cell_is_output;
60
+ unsigned int score;
61
+ // Edge's position in the edge list
62
+ int pos_in_cell;
63
+ int pos_in_wire;
64
+ };
65
+
66
+ // decide() finds shortest names for every object reachable from a public name,
67
+ // cheapest-first. It doesn't apply the renames to the objects yet.
68
+ //
69
+ // commit() then renames in decide() order, which is topological, so a source
70
+ // neighbour always already carries its final uniquify()d name.
71
+
72
+ // A selected cell or wire
73
+ struct node {
74
+ // Exactly one of cell/wire is set
75
+ Cell *cell = nullptr;
76
+ Wire *wire = nullptr;
77
+ vector<Edge> edges;
78
+ // Ignores module->connections() just as the rest of the code
79
+ unsigned int fanout = 0;
80
+ bool is_public = false;
81
+ bool renameable = false;
82
+ bool selected = false;
83
+
84
+ size_t name_length = 0;
85
+ // Node index from which we want to construct the rename
86
+ int from_node = -1;
87
+ // Cost for the edge from that node
88
+ cost c;
89
+ // Suffix to append to the name of that node
90
+ string suffix;
91
+ // Is this name final?
92
+ bool decided = false;
93
+
94
+ IdString name() const { return cell ? IdString(cell->name) : IdString(wire->name); }
95
+ };
96
+
97
+ // Decides the order of exploring neighbors
98
+ struct queue_item {
99
+ unsigned int score;
100
+ size_t length;
101
+ int index;
102
+
103
+ auto operator<=>(const queue_item &) const = default;
104
+ };
105
+
106
+ struct ModuleAutonamer
107
+ {
108
+ Module *module;
109
+
110
+ // Cells in module order, then wires in the order that they're seen from cells.
111
+ // The index doubles as the tie-break between equally good
112
+ // proposals for different nodes
113
+ vector<node> nodes;
114
+ vector<int> decided;
115
+ std::priority_queue<queue_item, std::vector<queue_item>, std::greater<>> queue;
116
+ int renamed = 0;
117
+
118
+ ModuleAutonamer(Module *module) : module(module) { build_adjacency(); }
119
+
120
+ void build_adjacency()
121
+ {
122
+ vector<Cell*> cells(module->cells().begin(), module->cells().end());
123
+ // Arbitrary. Kinda just for passing tests without modifying them
124
+ for (auto cell : cells | std::views::reverse)
125
+ nodes.emplace_back().cell = cell;
126
+ int ncells = GetSize(nodes);
127
+
128
+ idict<Wire*> wire_ids;
129
+
130
+ for (int ci = 0; ci < ncells; ci++) {
131
+ Cell *cell = nodes[ci].cell;
132
+ for (auto &conn : cell->connections()) {
133
+ bool cell_is_output = cell->output(conn.first);
134
+ pool<Wire*> seen_in_this_port;
135
+ for (auto bit : conn.second) {
136
+ if (bit.wire == nullptr)
137
+ continue;
138
+ int wi = ncells + wire_ids(bit.wire);
139
+ if (wi == GetSize(nodes))
140
+ nodes.emplace_back().wire = bit.wire;
141
+ nodes[wi].fanout++;
142
+ if (!seen_in_this_port.insert(bit.wire).second)
143
+ continue;
144
+ Edge edge{
145
+ .port = conn.first,
146
+ .cell = ci,
147
+ .wire = wi,
148
+ .cell_is_output = cell_is_output,
149
+ .score = 0, // no fanouts are final yet
150
+ .pos_in_cell = GetSize(nodes[ci].edges),
151
+ .pos_in_wire = GetSize(nodes[wi].edges),
152
+ };
153
+ nodes[ci].edges.push_back(edge);
154
+ nodes[wi].edges.push_back(edge);
155
+ }
156
+ }
157
+ }
158
+
159
+ // Resolve selection before renaming
160
+ for (auto &nd : nodes) {
161
+ nd.selected = nd.cell ? module->selected(nd.cell) : module->selected(nd.wire);
162
+ nd.is_public = nd.name().isPublic();
163
+ nd.renameable = !nd.is_public && (nd.cell || nd.wire->port_id == 0);
164
+ if (nd.is_public)
165
+ nd.name_length = module->twines().str(nd.name()).size();
166
+ }
167
+
168
+ // Only possible once every fanout is known
169
+ for (auto &nd : nodes)
170
+ for (auto &edge : nd.edges)
171
+ edge.score = edge.cell_is_output ? 0 : nodes[edge.wire].fanout;
172
+ }
173
+
174
+ void offer(int from, int to, const Edge &edge, int edge_pos)
175
+ {
176
+ node &nd = nodes[to];
177
+ if (!nd.renameable || nd.decided)
178
+ return;
179
+ std::string port = module->twines().unescaped_str(edge.port);
180
+ string suffix = nd.cell
181
+ ? stringf("_%s_%s", nd.cell->type.unescape(), port)
182
+ : stringf("_%s", port);
183
+ cost c{edge.score, nodes[from].name_length + suffix.length(), edge_pos};
184
+ if (c >= nd.c)
185
+ return;
186
+ nd.c = c;
187
+ nd.from_node = from;
188
+ nd.name_length = c.length;
189
+ nd.suffix = std::move(suffix);
190
+ queue.push(queue_item{c.score, c.length, to});
191
+ }
192
+
193
+ // Expand a public (or newly decided) node. The name it lends
194
+ // is already settled and the neighbour can keep what offer() built
195
+ void expand(int n)
196
+ {
197
+ const node &nd = nodes[n];
198
+ for (auto &edge : nd.edges)
199
+ if (nd.cell)
200
+ offer(n, edge.wire, edge, edge.pos_in_wire);
201
+ else
202
+ offer(n, edge.cell, edge, edge.pos_in_cell);
203
+ }
204
+
205
+ void decide()
206
+ {
207
+ for (int n = 0; n < GetSize(nodes); n++)
208
+ if (nodes[n].is_public)
209
+ expand(n);
210
+
211
+ while (!queue.empty()) {
212
+ int n = queue.top().index;
213
+ queue.pop();
214
+ if (nodes[n].decided)
215
+ continue;
216
+ nodes[n].decided = true;
217
+ decided.push_back(n);
218
+ expand(n);
219
+ }
220
+ }
221
+
222
+ void append_name(int n, string &out)
223
+ {
224
+ const node &nd = nodes[n];
225
+ if (nd.is_public || nd.selected) {
226
+ out += module->twines().str(nd.name());
227
+ return;
228
+ }
229
+ append_name(nd.from_node, out);
230
+ out += nd.suffix;
231
+ }
232
+
233
+ void commit(int n)
234
+ {
235
+ node &nd = nodes[n];
236
+ if (!nd.selected)
237
+ return;
238
+ string full;
239
+ full.reserve(nd.name_length);
240
+ append_name(nd.from_node, full);
241
+ full += nd.suffix;
242
+ IdString name = module->uniquify(full);
243
+ if (nd.cell) {
244
+ log_debug("Rename cell %s in %s to %s.\n", nd.cell, module, PooledName(module, name).unescape());
245
+ module->rename(nd.cell, name);
246
+ } else {
247
+ log_debug("Rename wire %s in %s to %s.\n", nd.wire, module, PooledName(module, name).unescape());
248
+ module->rename(nd.wire, name);
249
+ }
250
+ renamed++;
251
+ }
252
+
253
+ void run()
254
+ {
255
+ decide();
256
+ for (int n : decided)
257
+ commit(n);
258
+ if (renamed > 0)
259
+ log("Renamed %d objects in module %s.\n", renamed, module);
260
+ }
261
+ };
262
+
263
+ struct AutonamePass : public Pass {
264
+ AutonamePass() : Pass("autoname", "automatically assign names to objects") { }
265
+ void help() override
266
+ {
267
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
268
+ log("\n");
269
+ log(" autoname [selection]\n");
270
+ log("\n");
271
+ log("Assign auto-generated public names to objects with private names (the ones\n");
272
+ log("with $-prefix).\n");
273
+ log("\n");
274
+ }
275
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
276
+ {
277
+ size_t argidx;
278
+ for (argidx = 1; argidx < args.size(); argidx++)
279
+ {
280
+ // if (args[argidx] == "-foo") {
281
+ // foo = true;
282
+ // continue;
283
+ // }
284
+ break;
285
+ }
286
+ extra_args(args, argidx, design);
287
+
288
+ log_header(design, "Executing AUTONAME pass.\n");
289
+
290
+ for (auto module : design->selected_modules())
291
+ ModuleAutonamer(module).run();
292
+ }
293
+ } AutonamePass;
294
+
295
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/blackbox.cc ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+
22
+ USING_YOSYS_NAMESPACE
23
+ PRIVATE_NAMESPACE_BEGIN
24
+
25
+ struct BlackboxPass : public Pass {
26
+ BlackboxPass() : Pass("blackbox", "convert modules into blackbox modules") { }
27
+ void help() override
28
+ {
29
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
30
+ log("\n");
31
+ log(" blackbox [options] [selection]\n");
32
+ log("\n");
33
+ log("Convert modules into blackbox modules (remove contents and set the blackbox\n");
34
+ log("module attribute).\n");
35
+ log("\n");
36
+ }
37
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
38
+ {
39
+ size_t argidx;
40
+ for (argidx = 1; argidx < args.size(); argidx++)
41
+ {
42
+ // if (args[argidx] == "-???") {
43
+ // continue;
44
+ // }
45
+ break;
46
+ }
47
+ extra_args(args, argidx, design);
48
+
49
+ for (auto module : design->selected_whole_modules_warn(true))
50
+ {
51
+ module->makeblackbox();
52
+ module->set_bool_attribute(ID::blackbox);
53
+ module->set_bool_attribute(ID::whitebox, false);
54
+ }
55
+ }
56
+ } BlackboxPass;
57
+
58
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/box_derive.cc ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2024 Martin Povišer <povik@cutebit.org>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+ #include "kernel/yosys.h"
20
+
21
+ USING_YOSYS_NAMESPACE
22
+ PRIVATE_NAMESPACE_BEGIN
23
+
24
+ struct BoxDerivePass : Pass {
25
+ BoxDerivePass() : Pass("box_derive", "derive box modules") {}
26
+ void help() override
27
+ {
28
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
29
+ log("\n");
30
+ log(" box_derive [-base <base_module>] [-naming_attr <attr>] [selection]\n");
31
+ log("\n");
32
+ log("As part of the assembly of the design hierarchy done by the 'hierarchy' command,\n");
33
+ log("specializations of parametric modules are derived on demand: for each choice of\n");
34
+ log("parameter values appearing in the design, a copy of the parametric module is\n");
35
+ log("derived which is specialized to that choice.\n");
36
+ log("\n");
37
+ log("This derivation process ignores blackboxes and whiteboxes (boxes). To supplement,\n");
38
+ log("this 'box_derive' command can be used to request the derivation of modules based\n");
39
+ log("on box instances appearing in the design, which is desirable in certain use\n");
40
+ log("cases. Only the selected cells are considered as the instances that steer the\n");
41
+ log("derivation process.\n");
42
+ log("\n");
43
+ log(" -base <base_module>\n");
44
+ log(" instead of deriving the module that directly corresponds to each box\n");
45
+ log(" instance, derive a specialization of <base_module> (this option applies\n");
46
+ log(" to all selected box cells)\n");
47
+ log("\n");
48
+ log(" -naming_attr <attr>\n");
49
+ log(" once a specialization is derived, use the value of the module attribute\n");
50
+ log(" <attr> for a name which should be used for the derived module (this\n");
51
+ log(" replaces the internal Yosys naming scheme in which the names of derived\n");
52
+ log(" modules start with '$paramod$')\n");
53
+ log("\n");
54
+ log(" -apply_derived_type\n");
55
+ log(" use the derived modules\n");
56
+ log("\n");
57
+ }
58
+ void execute(std::vector<std::string> args, RTLIL::Design *d) override
59
+ {
60
+ log_header(d, "Executing BOX_DERIVE pass. (derive modules for boxes)\n");
61
+
62
+ size_t argidx;
63
+ std::string naming_attr;
64
+ std::string base_name;
65
+ bool apply_mode = false;
66
+ for (argidx = 1; argidx < args.size(); argidx++) {
67
+ if (args[argidx] == "-naming_attr" && argidx + 1 < args.size())
68
+ naming_attr = RTLIL::escape_id(args[++argidx]);
69
+ else if (args[argidx] == "-base" && argidx + 1 < args.size())
70
+ base_name = RTLIL::escape_id(args[++argidx]);
71
+ else if (args[argidx] == "-apply_derived_type")
72
+ apply_mode = true;
73
+ else
74
+ break;
75
+ }
76
+ extra_args(args, argidx, d);
77
+
78
+ IdString naming_attr_ref = naming_attr.empty() ? IdString::Null : d->twines().find(naming_attr);
79
+
80
+ Module *base_override = nullptr;
81
+ if (!base_name.empty()) {
82
+ IdString base_ref = d->twines().find(base_name);
83
+ base_override = base_ref == IdString::Null ? nullptr : d->module(base_ref);
84
+ if (!base_override)
85
+ log_cmd_error("Base module %s not found.\n", RTLIL::unescape_id(base_name));
86
+ }
87
+
88
+ dict<std::pair<RTLIL::IdString, dict<RTLIL::IdString, RTLIL::Const>>, Module*> done;
89
+
90
+ for (auto module : d->selected_modules()) {
91
+ for (auto cell : module->selected_cells()) {
92
+ Module *inst_module = d->module(cell->type);
93
+ if (!inst_module || !inst_module->get_blackbox_attribute())
94
+ continue;
95
+
96
+ Module *base = inst_module;
97
+ if (base_override)
98
+ base = base_override;
99
+
100
+ auto index = std::make_pair(IdString(base->name), cell->parameters);
101
+
102
+ if (cell->parameters.empty())
103
+ continue;
104
+
105
+ if (!done.count(index)) {
106
+ IdString derived_type = base->derive(d, cell->parameters);
107
+ Module *derived = d->module(derived_type);
108
+ log_assert(derived && "Failed to derive module\n");
109
+ log("derived %s\n", d->twines().str(derived_type));
110
+
111
+ if (naming_attr_ref != IdString::Null && derived->has_attribute(naming_attr_ref)) {
112
+ std::string new_name = RTLIL::escape_id(derived->get_string_attribute(naming_attr_ref));
113
+ if (new_name.empty() || new_name[0] != '\\')
114
+ log_error("Derived module %s cannot be renamed to private name %s.\n",
115
+ derived, RTLIL::unescape_id(new_name));
116
+ derived->attributes.erase(naming_attr_ref);
117
+ d->rename(derived, std::move(new_name));
118
+ }
119
+
120
+ done[index] = derived;
121
+ }
122
+
123
+ if (apply_mode)
124
+ cell->type = cell->twines().copy_from(done[index]->twines(), done[index]->name);
125
+ }
126
+ }
127
+ }
128
+ } BoxDerivePass;
129
+
130
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/bugpoint.cc ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2018 whitequark <whitequark@whitequark.org>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "backends/rtlil/rtlil_backend.h"
22
+
23
+ #if defined(_WIN32)
24
+ # include <csignal>
25
+ # define WIFEXITED(x) 1
26
+ # define WIFSIGNALED(x) 0
27
+ # define WIFSTOPPED(x) 0
28
+ # define WEXITSTATUS(x) ((x) & 0xff)
29
+ # define WTERMSIG(x) SIGTERM
30
+ # define WSTOPSIG(x) 0
31
+ #else
32
+ #include <sys/wait.h>
33
+ #endif
34
+
35
+ USING_YOSYS_NAMESPACE
36
+ using namespace RTLIL_BACKEND;
37
+ PRIVATE_NAMESPACE_BEGIN
38
+
39
+ struct BugpointPass : public Pass {
40
+ BugpointPass() : Pass("bugpoint", "minimize testcases") { }
41
+ void help() override
42
+ {
43
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
44
+ log("\n");
45
+ log(" bugpoint [options] [-script <filename> | -command \"<command>\"]\n");
46
+ log("\n");
47
+ log("This command minimizes the current design that is known to crash Yosys with the\n");
48
+ log("given script into a smaller testcase. It does this by removing an arbitrary part\n");
49
+ log("of the design and recursively invokes a new Yosys process with this modified\n");
50
+ log("design and the same script, repeating these steps while it can find a smaller\n");
51
+ log("design that still causes a crash. Once this command finishes, it replaces the\n");
52
+ log("current design with the smallest testcase it was able to produce.\n");
53
+ log("In order to save the reduced testcase you must write this out to a file with\n");
54
+ log("another command after `bugpoint` like `write_rtlil` or `write_verilog`.\n");
55
+ log("\n");
56
+ log(" -script <filename> | -command \"<command>\"\n");
57
+ log(" use this script file or command to crash Yosys. required.\n");
58
+ log("\n");
59
+ log(" -yosys <filename>\n");
60
+ log(" use this Yosys binary. if not specified, `yosys` is used.\n");
61
+ log("\n");
62
+ log(" -grep \"<string>\"\n");
63
+ log(" only consider crashes that place this string in the log file.\n");
64
+ log("\n");
65
+ log(" -expect-return <int>\n");
66
+ log(" only consider crashes that return the specified value. e.g. SEGFAULT\n");
67
+ log(" returns a value of 139.\n");
68
+ log("\n");
69
+ log(" -fast\n");
70
+ log(" run `proc_clean; clean -purge` after each minimization step. converges\n");
71
+ log(" faster, but produces larger testcases, and may fail to produce any\n");
72
+ log(" testcase at all if the crash is related to dangling wires.\n");
73
+ log("\n");
74
+ log(" -clean\n");
75
+ log(" run `proc_clean; clean -purge` before checking testcase and after\n");
76
+ log(" finishing. produces smaller and more useful testcases, but may fail to\n");
77
+ log(" produce any testcase at all if the crash is related to dangling wires.\n");
78
+ log("\n");
79
+ log(" -runner \"<prefix>\"\n");
80
+ log(" child process wrapping command, e.g., \"timeout 30\", or valgrind.\n");
81
+ log("\n");
82
+ log(" -err-grep \"<string>\"\n");
83
+ log(" only consider crashes that print this string on stderr. useful for\n");
84
+ log(" errors outside of yosys.\n");
85
+ log("\n");
86
+ log(" -suffix \"<string>\"\n");
87
+ log(" add suffix to generated file names. useful when running more than one\n");
88
+ log(" instance of bugpoint in the same directory. limited to 8 characters.\n");
89
+ log("\n");
90
+ log("It is possible to constrain which parts of the design will be considered for\n");
91
+ log("removal. Unless one or more of the following options are specified, all parts\n");
92
+ log("will be considered.\n");
93
+ log("\n");
94
+ log(" -modules\n");
95
+ log(" try to remove modules. modules with a (* bugpoint_keep *) attribute\n");
96
+ log(" will be skipped.\n");
97
+ log("\n");
98
+ log(" -ports\n");
99
+ log(" try to remove module ports. ports with a (* bugpoint_keep *) attribute\n");
100
+ log(" will be skipped (useful for clocks, resets, etc.)\n");
101
+ log("\n");
102
+ log(" -cells\n");
103
+ log(" try to remove cells. cells with a (* bugpoint_keep *) attribute will\n");
104
+ log(" be skipped.\n");
105
+ log("\n");
106
+ log(" -connections\n");
107
+ log(" try to reconnect ports to 'x.\n");
108
+ log("\n");
109
+ log(" -processes\n");
110
+ log(" try to remove processes. processes with a (* bugpoint_keep *) attribute\n");
111
+ log(" will be skipped.\n");
112
+ log("\n");
113
+ log(" -assigns\n");
114
+ log(" try to remove process assigns from cases.\n");
115
+ log("\n");
116
+ log(" -updates\n");
117
+ log(" try to remove process updates from syncs.\n");
118
+ log("\n");
119
+ log(" -wires\n");
120
+ log(" try to remove wires. wires with a (* bugpoint_keep *) attribute will be\n");
121
+ log(" skipped.\n");
122
+ log("\n");
123
+ }
124
+
125
+ int run_yosys(RTLIL::Design *design, string runner, string yosys_cmd, string yosys_arg, string suffix, bool catch_err)
126
+ {
127
+ string bugpoint_file = "bugpoint-case";
128
+ if (suffix.size())
129
+ bugpoint_file += stringf(".%.8s", suffix);
130
+
131
+ std::ofstream f(bugpoint_file + ".il");
132
+ RTLIL_BACKEND::dump_design(f, design, /*only_selected=*/false, /*flag_m=*/true, /*flag_n=*/false);
133
+ f.close();
134
+
135
+ string yosys_cmdline = stringf("%s %s -qq -L %s.log %s %s.il", runner, yosys_cmd, bugpoint_file, yosys_arg, bugpoint_file);
136
+ if (catch_err) yosys_cmdline += stringf(" 2>%s.err", bugpoint_file);
137
+ auto status = run_command(yosys_cmdline);
138
+ // we're not processing lines, which means we're getting raw system() returns
139
+ if(WIFEXITED(status))
140
+ return WEXITSTATUS(status);
141
+ else if(WIFSIGNALED(status))
142
+ return WTERMSIG(status);
143
+ else if(WIFSTOPPED(status))
144
+ return WSTOPSIG(status);
145
+ else
146
+ return 0;
147
+ }
148
+
149
+ bool check_logfile(string grep, string suffix, bool err=false)
150
+ {
151
+ if (grep.empty())
152
+ return true;
153
+
154
+ if (grep.size() > 2 && grep.front() == '"' && grep.back() == '"')
155
+ grep = grep.substr(1, grep.size() - 2);
156
+
157
+ string bugpoint_file = "bugpoint-case";
158
+ if (suffix.size())
159
+ bugpoint_file += stringf(".%.8s", suffix);
160
+ bugpoint_file += err ? ".err" : ".log";
161
+
162
+ std::ifstream f(bugpoint_file);
163
+
164
+ while (!f.eof())
165
+ {
166
+ string line;
167
+ getline(f, line);
168
+ if (line.find(grep) != std::string::npos)
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+
174
+ bool check_logfiles(string grep, string err_grep, string suffix)
175
+ {
176
+ return check_logfile(grep, suffix) && check_logfile(err_grep, suffix, true);
177
+ }
178
+
179
+ std::unique_ptr<RTLIL::Design> clean_design(RTLIL::Design *design)
180
+ {
181
+ auto design_copy = std::make_unique<RTLIL::Design>();
182
+ for (auto module : design->modules())
183
+ module->clone(design_copy.get());
184
+ Pass::call(design_copy.get(), "proc_clean -quiet");
185
+ Pass::call(design_copy.get(), "clean -purge");
186
+ return design_copy;
187
+ }
188
+
189
+ std::unique_ptr<RTLIL::Design> simplify_something(RTLIL::Design *design, int &seed, bool stage2, bool modules, bool ports, bool cells, bool connections, bool processes, bool assigns, bool updates, bool wires)
190
+ {
191
+ auto design_copy = std::make_unique<RTLIL::Design>();
192
+ for (auto module : design->modules())
193
+ module->clone(design_copy.get());
194
+
195
+ int index = 0;
196
+ if (modules)
197
+ {
198
+ Module *removed_module = nullptr;
199
+ for (auto module : design_copy->modules())
200
+ {
201
+ if (module->get_blackbox_attribute())
202
+ continue;
203
+
204
+ if (module->get_bool_attribute(ID::bugpoint_keep))
205
+ continue;
206
+
207
+ if (index++ == seed)
208
+ {
209
+ log_header(design, "Trying to remove module %s.\n", module);
210
+ removed_module = module;
211
+ break;
212
+ }
213
+ }
214
+ if (removed_module) {
215
+ design_copy->remove(removed_module);
216
+ return design_copy;
217
+ }
218
+ }
219
+ if (ports)
220
+ {
221
+ for (auto mod : design_copy->modules())
222
+ {
223
+ if (mod->get_blackbox_attribute())
224
+ continue;
225
+
226
+ for (auto wire : mod->wires())
227
+ {
228
+ if (!wire->port_id)
229
+ continue;
230
+
231
+ if (!stage2 && wire->get_bool_attribute(ID($bugpoint)))
232
+ continue;
233
+
234
+ if (wire->get_bool_attribute(ID::bugpoint_keep))
235
+ continue;
236
+
237
+ if (index++ == seed)
238
+ {
239
+ log_header(design, "Trying to remove module port %s.\n", wire);
240
+ wire->port_input = wire->port_output = false;
241
+ mod->fixup_ports();
242
+ return design_copy;
243
+ }
244
+ }
245
+ }
246
+ }
247
+ if (cells)
248
+ {
249
+ for (auto mod : design_copy->modules())
250
+ {
251
+ if (mod->get_blackbox_attribute())
252
+ continue;
253
+
254
+ Cell *removed_cell = nullptr;
255
+ for (auto cell : mod->cells())
256
+ {
257
+ if (cell->get_bool_attribute(ID::bugpoint_keep))
258
+ continue;
259
+
260
+ if (index++ == seed)
261
+ {
262
+ log_header(design, "Trying to remove cell %s.%s.\n", mod, cell);
263
+ removed_cell = cell;
264
+ break;
265
+ }
266
+ }
267
+ if (removed_cell) {
268
+ mod->remove(removed_cell);
269
+ return design_copy;
270
+ }
271
+ }
272
+ }
273
+ if (connections)
274
+ {
275
+ for (auto mod : design_copy->modules())
276
+ {
277
+ if (mod->get_blackbox_attribute())
278
+ continue;
279
+
280
+ for (auto cell : mod->cells())
281
+ {
282
+ for (auto it : cell->connections_)
283
+ {
284
+ RTLIL::SigSpec port = cell->getPort(it.first);
285
+ bool is_undef = port.is_fully_undef();
286
+ bool is_port = port.is_wire() && (port.as_wire()->port_input || port.as_wire()->port_output);
287
+
288
+ if(is_undef || (!stage2 && is_port))
289
+ continue;
290
+
291
+ if (index++ == seed)
292
+ {
293
+ log_header(design, "Trying to remove cell port %s.%s.%s.\n", mod, cell, PooledName(design_copy.get(), it.first).unescape());
294
+ RTLIL::SigSpec port_x(State::Sx, port.size());
295
+ cell->unsetPort(it.first);
296
+ cell->setPort(it.first, port_x);
297
+ return design_copy;
298
+ }
299
+
300
+ if (!stage2 && (cell->input(it.first) || cell->output(it.first)) && index++ == seed)
301
+ {
302
+ log_header(design, "Trying to expose cell port %s.%s.%s as module port.\n", mod, cell, PooledName(design_copy.get(), it.first).unescape());
303
+ RTLIL::Wire *wire = mod->addWire(NEW_ID, port.size());
304
+ wire->set_bool_attribute(ID($bugpoint));
305
+ wire->port_input = cell->input(it.first);
306
+ wire->port_output = cell->output(it.first);
307
+ cell->unsetPort(it.first);
308
+ cell->setPort(it.first, wire);
309
+ mod->fixup_ports();
310
+ return design_copy;
311
+ }
312
+ }
313
+ }
314
+ }
315
+ }
316
+ if (processes)
317
+ {
318
+ for (auto mod : design_copy->modules())
319
+ {
320
+ if (mod->get_blackbox_attribute())
321
+ continue;
322
+
323
+ RTLIL::Process *removed_process = nullptr;
324
+ for (auto process : mod->processes)
325
+ {
326
+ if (process.second->get_bool_attribute(ID::bugpoint_keep))
327
+ continue;
328
+
329
+ if (index++ == seed)
330
+ {
331
+ log_header(design, "Trying to remove process %s.%s.\n", mod, PooledName(design_copy.get(), process.first).unescape());
332
+ removed_process = process.second;
333
+ break;
334
+ }
335
+ }
336
+ if (removed_process) {
337
+ mod->remove(removed_process);
338
+ return design_copy;
339
+ }
340
+ }
341
+ }
342
+ if (assigns)
343
+ {
344
+ for (auto mod : design_copy->modules())
345
+ {
346
+ if (mod->get_blackbox_attribute())
347
+ continue;
348
+
349
+ for (auto &pr : mod->processes)
350
+ {
351
+ vector<RTLIL::CaseRule*> cases = {&pr.second->root_case};
352
+ while (!cases.empty())
353
+ {
354
+ RTLIL::CaseRule *cs = cases[0];
355
+ cases.erase(cases.begin());
356
+ for (auto it = cs->actions.begin(); it != cs->actions.end(); ++it)
357
+ {
358
+ if (index++ == seed)
359
+ {
360
+ log_header(design, "Trying to remove assign %s %s in %s.%s.\n", log_signal(it->first), log_signal(it->second), mod, PooledName(design_copy.get(), pr.first).unescape());
361
+ cs->actions.erase(it);
362
+ return design_copy;
363
+ }
364
+ }
365
+ for (auto &sw : cs->switches)
366
+ cases.insert(cases.end(), sw->cases.begin(), sw->cases.end());
367
+ }
368
+ }
369
+ }
370
+ }
371
+ if (updates)
372
+ {
373
+ for (auto mod : design_copy->modules())
374
+ {
375
+ if (mod->get_blackbox_attribute())
376
+ continue;
377
+
378
+ for (auto &pr : mod->processes)
379
+ {
380
+ for (auto &sy : pr.second->syncs)
381
+ {
382
+ for (auto it = sy->actions.begin(); it != sy->actions.end(); ++it)
383
+ {
384
+ if (index++ == seed)
385
+ {
386
+ log_header(design, "Trying to remove sync %s update %s %s in %s.%s.\n", log_signal(sy->signal), log_signal(it->first), log_signal(it->second), mod, PooledName(design_copy.get(), pr.first).unescape());
387
+ sy->actions.erase(it);
388
+ return design_copy;
389
+ }
390
+ }
391
+ int i = 0;
392
+ for (auto it = sy->mem_write_actions.begin(); it != sy->mem_write_actions.end(); ++it, ++i)
393
+ {
394
+ if (index++ == seed)
395
+ {
396
+ log_header(design, "Trying to remove sync %s memwr %s %s %s %s in %s.%s.\n", log_signal(sy->signal), PooledName(design_copy.get(), it->memid).unescape(), log_signal(it->address), log_signal(it->data), log_signal(it->enable), mod, PooledName(design_copy.get(), pr.first).unescape());
397
+ sy->mem_write_actions.erase(it);
398
+ // Remove the bit for removed action from other actions' priority masks.
399
+ for (auto it2 = sy->mem_write_actions.begin(); it2 != sy->mem_write_actions.end(); ++it2) {
400
+ auto &mask = it2->priority_mask;
401
+ if (GetSize(mask) > i) {
402
+ RTLIL::Const::Builder new_mask_builder(GetSize(mask) - 1);
403
+ for (int k = 0; k < GetSize(mask); k++)
404
+ if (k != i)
405
+ new_mask_builder.push_back(mask[k]);
406
+ mask = new_mask_builder.build();
407
+ }
408
+ }
409
+ return design_copy;
410
+ }
411
+ }
412
+ }
413
+ }
414
+ }
415
+ }
416
+ if (wires)
417
+ {
418
+ for (auto mod : design_copy->modules())
419
+ {
420
+ if (mod->get_blackbox_attribute())
421
+ continue;
422
+
423
+ Wire *removed_wire = nullptr;
424
+ for (auto wire : mod->wires())
425
+ {
426
+ if (wire->get_bool_attribute(ID::bugpoint_keep))
427
+ continue;
428
+
429
+ if (wire->name.begins_with("$delete_wire") || wire->name.begins_with("$auto$bugpoint"))
430
+ continue;
431
+
432
+ if (index++ == seed)
433
+ {
434
+ log_header(design, "Trying to remove wire %s.%s.\n", mod, wire);
435
+ removed_wire = wire;
436
+ break;
437
+ }
438
+ }
439
+ if (removed_wire) {
440
+ mod->remove({removed_wire});
441
+ return design_copy;
442
+ }
443
+ }
444
+ }
445
+ return nullptr;
446
+ }
447
+
448
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
449
+ {
450
+ string yosys_cmd = "yosys", yosys_arg, grep, err_grep, runner, suffix;
451
+ bool flag_expect_return = false, has_check = false, check_err = false;
452
+ int expect_return_value = 0;
453
+ bool fast = false, clean = false;
454
+ bool modules = false, ports = false, cells = false, connections = false, processes = false, assigns = false, updates = false, wires = false, has_part = false;
455
+
456
+ log_header(design, "Executing BUGPOINT pass (minimize testcases).\n");
457
+ log_push();
458
+
459
+ size_t argidx;
460
+ for (argidx = 1; argidx < args.size(); argidx++)
461
+ {
462
+ if (args[argidx] == "-yosys" && argidx + 1 < args.size()) {
463
+ yosys_cmd = args[++argidx];
464
+ continue;
465
+ }
466
+ if (args[argidx] == "-script" && argidx + 1 < args.size()) {
467
+ if (!yosys_arg.empty())
468
+ log_cmd_error("A -script or -command option can be only provided once!\n");
469
+ yosys_arg = stringf("-s %s", args[++argidx]);
470
+ continue;
471
+ }
472
+ if (args[argidx] == "-command" && argidx + 1 < args.size()) {
473
+ if (!yosys_arg.empty())
474
+ log_cmd_error("A -script or -command option can be only provided once!\n");
475
+ yosys_arg = stringf("-p %s", args[++argidx]);
476
+ continue;
477
+ }
478
+ if (args[argidx] == "-grep" && argidx + 1 < args.size()) {
479
+ has_check = true;
480
+ grep = args[++argidx];
481
+ continue;
482
+ }
483
+ if (args[argidx] == "-err-grep" && argidx + 1 < args.size()) {
484
+ has_check = true;
485
+ check_err = true;
486
+ err_grep = args[++argidx];
487
+ continue;
488
+ }
489
+ if (args[argidx] == "-expect-return") {
490
+ flag_expect_return = true;
491
+ ++argidx;
492
+ if (argidx >= args.size())
493
+ log_cmd_error("No expected return value specified.\n");
494
+
495
+ expect_return_value = atoi(args[argidx].c_str());
496
+ continue;
497
+ }
498
+ if (args[argidx] == "-fast") {
499
+ fast = true;
500
+ continue;
501
+ }
502
+ if (args[argidx] == "-clean") {
503
+ clean = true;
504
+ continue;
505
+ }
506
+ if (args[argidx] == "-modules") {
507
+ modules = true;
508
+ has_part = true;
509
+ continue;
510
+ }
511
+ if (args[argidx] == "-ports") {
512
+ ports = true;
513
+ has_part = true;
514
+ continue;
515
+ }
516
+ if (args[argidx] == "-cells") {
517
+ cells = true;
518
+ has_part = true;
519
+ continue;
520
+ }
521
+ if (args[argidx] == "-connections") {
522
+ connections = true;
523
+ has_part = true;
524
+ continue;
525
+ }
526
+ if (args[argidx] == "-processes") {
527
+ processes = true;
528
+ has_part = true;
529
+ continue;
530
+ }
531
+ if (args[argidx] == "-assigns") {
532
+ assigns = true;
533
+ has_part = true;
534
+ continue;
535
+ }
536
+ if (args[argidx] == "-updates") {
537
+ updates = true;
538
+ has_part = true;
539
+ continue;
540
+ }
541
+ if (args[argidx] == "-wires") {
542
+ wires = true;
543
+ has_part = true;
544
+ continue;
545
+ }
546
+ if (args[argidx] == "-runner" && argidx + 1 < args.size()) {
547
+ runner = args[++argidx];
548
+ if (runner.size() && runner.at(0) == '"') {
549
+ log_assert(runner.back() == '"');
550
+ runner = runner.substr(1, runner.size() - 2);
551
+ }
552
+ continue;
553
+ }
554
+ if (args[argidx] == "-suffix" && argidx + 1 < args.size()) {
555
+ suffix = args[++argidx];
556
+ if (suffix.size() && suffix.at(0) == '"') {
557
+ log_assert(suffix.back() == '"');
558
+ suffix = suffix.substr(1, suffix.size() - 2);
559
+ }
560
+ continue;
561
+ }
562
+ break;
563
+ }
564
+ extra_args(args, argidx, design);
565
+
566
+ if (yosys_arg.empty())
567
+ log_cmd_error("Missing -script or -command option.\n");
568
+
569
+ if (flag_expect_return && expect_return_value == 0 && !has_check)
570
+ log_cmd_error("Nothing to match on for -expect-return 0; change value or use -grep.\n");
571
+
572
+ if (!has_part)
573
+ {
574
+ modules = true;
575
+ ports = true;
576
+ cells = true;
577
+ connections = true;
578
+ processes = true;
579
+ assigns = true;
580
+ updates = true;
581
+ wires = true;
582
+ }
583
+
584
+ if (!design->full_selection())
585
+ log_cmd_error("This command only operates on fully selected designs!\n");
586
+
587
+ std::unique_ptr<RTLIL::Design> crashing_design;
588
+ if (clean)
589
+ crashing_design = clean_design(design);
590
+ int retval = run_yosys(crashing_design ? crashing_design.get() : design, runner, yosys_cmd, yosys_arg, suffix, check_err);
591
+ if (flag_expect_return && retval != expect_return_value)
592
+ log_cmd_error("The provided script file or command and Yosys binary returned value %d instead of expected %d on this design!\n", retval, expect_return_value);
593
+ if (!flag_expect_return && retval == 0)
594
+ log_cmd_error("The provided script file or command and Yosys binary do not crash on this design!\n");
595
+ if (!check_logfile(grep, suffix))
596
+ log_cmd_error("The provided grep string is not found in the log file!\n");
597
+ if (!check_logfile(err_grep, suffix, true))
598
+ log_cmd_error("The provided grep string is not found in stderr log!\n");
599
+
600
+ int seed = 0;
601
+ bool found_something = false, stage2 = false;
602
+ while (true)
603
+ {
604
+ if (auto simplified = simplify_something(crashing_design ? crashing_design.get() : design, seed, stage2, modules, ports, cells, connections, processes, assigns, updates, wires))
605
+ {
606
+ if (fast)
607
+ simplified = clean_design(simplified.get());
608
+
609
+ if (clean)
610
+ {
611
+ auto testcase = clean_design(simplified.get());
612
+ retval = run_yosys(testcase.get(), runner, yosys_cmd, yosys_arg, suffix, check_err);
613
+ }
614
+ else
615
+ {
616
+ retval = run_yosys(simplified.get(), runner, yosys_cmd, yosys_arg, suffix, check_err);
617
+ }
618
+
619
+ bool crashes = false;
620
+ if (flag_expect_return && retval == expect_return_value && check_logfiles(grep, err_grep, suffix))
621
+ {
622
+ log("Testcase matches expected crash.\n");
623
+ crashes = true;
624
+ }
625
+ else if (!flag_expect_return && retval == 0)
626
+ log("Testcase does not crash.\n");
627
+ else if (!flag_expect_return && check_logfiles(grep, err_grep, suffix))
628
+ {
629
+ log("Testcase crashes.\n");
630
+ crashes = true;
631
+ }
632
+ else
633
+ // flag_expect_return && !(retval == expect_return_value && check_logfiles(grep, err_grep, suffix))
634
+ // !flag_expect_return && !(retval == 0 && check_logfiles(grep, err_grep, suffix))
635
+ log("Testcase does not match expected crash.\n");
636
+
637
+ if (crashes)
638
+ {
639
+ crashing_design = std::move(simplified);
640
+ found_something = true;
641
+ }
642
+ else
643
+ {
644
+ seed++;
645
+ }
646
+ }
647
+ else
648
+ {
649
+ seed = 0;
650
+ if (found_something)
651
+ found_something = false;
652
+ else
653
+ {
654
+ if (!stage2)
655
+ {
656
+ log("Demoting introduced module ports.\n");
657
+ stage2 = true;
658
+ }
659
+ else
660
+ {
661
+ log("Simplifications exhausted.\n");
662
+ break;
663
+ }
664
+ }
665
+ }
666
+ }
667
+
668
+ if (crashing_design)
669
+ {
670
+ Pass::call(design, "design -reset");
671
+ if (clean)
672
+ crashing_design = clean_design(crashing_design.get());
673
+ for (auto module : crashing_design->modules())
674
+ module->clone(design);
675
+ }
676
+
677
+ log_pop();
678
+ }
679
+ } BugpointPass;
680
+
681
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/check.cc ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/celledges.h"
23
+ #include "kernel/newcelltypes.h"
24
+ #include "kernel/utils.h"
25
+ #include "kernel/log_help.h"
26
+ #include "kernel/mem.h"
27
+
28
+ USING_YOSYS_NAMESPACE
29
+ PRIVATE_NAMESPACE_BEGIN
30
+
31
+ struct CheckPass : public Pass {
32
+ CheckPass() : Pass("check", "check for obvious problems in the design") { }
33
+ bool formatted_help() override {
34
+ auto *help = PrettyHelp::get_current();
35
+ help->set_group("passes/status");
36
+ return false;
37
+ }
38
+ void help() override
39
+ {
40
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
41
+ log("\n");
42
+ log(" check [options] [selection]\n");
43
+ log("\n");
44
+ log("This pass identifies the following problems in the current design:\n");
45
+ log("\n");
46
+ log(" - combinatorial loops\n");
47
+ log(" - two or more conflicting drivers for one wire\n");
48
+ log(" - used wires that do not have a driver\n");
49
+ log(" - cells of an internal ($-prefixed) type that is neither a known cell type\n");
50
+ log(" nor a module in the design\n");
51
+ log("\n");
52
+ log("Options:\n");
53
+ log("\n");
54
+ log(" -noinit\n");
55
+ log(" also check for wires which have the 'init' attribute set\n");
56
+ log("\n");
57
+ log(" -initdrv\n");
58
+ log(" also check for wires that have the 'init' attribute set and are not\n");
59
+ log(" driven by an FF cell type\n");
60
+ log("\n");
61
+ log(" -mapped\n");
62
+ log(" also check for internal cells that have not been mapped to cells of the\n");
63
+ log(" target architecture\n");
64
+ log("\n");
65
+ log(" -nolatches\n");
66
+ log(" also check for latch cells ($dlatch, $adlatch, $dlatchsr and their\n");
67
+ log(" $_DLATCH_*/$_DLATCHSR_* mappings) remaining in the design. Use this\n");
68
+ log(" before techmapping in flows that must not emit latches. Cells marked\n");
69
+ log(" with the 'always_latch' attribute are not reported.\n");
70
+ log("\n");
71
+ log(" -latchonly\n");
72
+ log(" check only for latch cells (as listed under -nolatches), skipping all\n");
73
+ log(" other checks.\n");
74
+ log("\n");
75
+ log(" -allow-tbuf\n");
76
+ log(" modify the -mapped behavior to still allow $_TBUF_ cells\n");
77
+ log("\n");
78
+ log(" -assert\n");
79
+ log(" produce a runtime error if any problems are found in the current design\n");
80
+ log("\n");
81
+ log(" -force-detailed-loop-check\n");
82
+ log(" for the detection of combinatorial loops, use a detailed connectivity\n");
83
+ log(" model for all internal cells for which it is available. This disables\n");
84
+ log(" falling back to a simpler overapproximating model for those cells for\n");
85
+ log(" which the detailed model is expected costly.\n");
86
+ log("\n");
87
+ }
88
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
89
+ {
90
+ int counter = 0;
91
+ bool noinit = false;
92
+ bool initdrv = false;
93
+ bool mapped = false;
94
+ bool nolatches = false;
95
+ bool latchonly = false;
96
+ bool allow_tbuf = false;
97
+ bool assert_mode = false;
98
+ bool force_detailed_loop_check = false;
99
+ bool suggest_detail = false;
100
+
101
+ size_t argidx;
102
+ for (argidx = 1; argidx < args.size(); argidx++) {
103
+ if (args[argidx] == "-noinit") {
104
+ noinit = true;
105
+ continue;
106
+ }
107
+ if (args[argidx] == "-initdrv") {
108
+ initdrv = true;
109
+ continue;
110
+ }
111
+ if (args[argidx] == "-mapped") {
112
+ mapped = true;
113
+ continue;
114
+ }
115
+ if (args[argidx] == "-nolatches") {
116
+ nolatches = true;
117
+ continue;
118
+ }
119
+ if (args[argidx] == "-latchonly") {
120
+ latchonly = true;
121
+ continue;
122
+ }
123
+ if (args[argidx] == "-allow-tbuf") {
124
+ allow_tbuf = true;
125
+ continue;
126
+ }
127
+ if (args[argidx] == "-assert") {
128
+ assert_mode = true;
129
+ continue;
130
+ }
131
+ if (args[argidx] == "-force-detailed-loop-check") {
132
+ force_detailed_loop_check = true;
133
+ continue;
134
+ }
135
+ break;
136
+ }
137
+ extra_args(args, argidx, design);
138
+
139
+ log_header(design, "Executing CHECK pass (checking for obvious problems).\n");
140
+
141
+ for (auto module : design->selected_whole_modules_warn())
142
+ {
143
+ log("Checking module %s...\n", module);
144
+
145
+ // latch-only mode only flags latches, skipping the (potentially false-positive mid-flow) undriven/driver/loop checks below
146
+ if (latchonly) {
147
+ for (auto cell : module->cells())
148
+ if (!cell->get_bool_attribute(ID::always_latch) && (
149
+ cell->type.in(ID($dlatch), ID($adlatch), ID($dlatchsr)) ||
150
+ cell->type.begins_with("$_DLATCH_") || cell->type.begins_with("$_DLATCHSR_"))) {
151
+ log_warning("Cell %s.%s is a latch of type %s.\n", module, cell, cell->type.unescape());
152
+ counter++;
153
+ }
154
+ continue;
155
+ }
156
+
157
+ SigMap sigmap(module);
158
+ dict<SigBit, vector<string>> wire_drivers;
159
+ dict<SigBit, Cell *> driver_cells;
160
+ dict<SigBit, int> wire_drivers_count;
161
+ pool<SigBit> used_wires;
162
+ TopoSort<std::pair<RTLIL::IdString, int>> topo;
163
+ for (auto &proc_it : module->processes)
164
+ {
165
+ pool<SigBit> proc_driven_bits;
166
+ std::vector<RTLIL::CaseRule*> all_cases = {&proc_it.second->root_case};
167
+ for (size_t i = 0; i < all_cases.size(); i++) {
168
+ for (auto action : all_cases[i]->actions) {
169
+ for (auto bit : sigmap(action.first)) {
170
+ wire_drivers[bit].push_back(
171
+ stringf("action %s <= %s (case rule) in process %s",
172
+ log_signal(action.first), log_signal(action.second), module->twines().unescaped_str(proc_it.first)));
173
+ if (bit.wire)
174
+ proc_driven_bits.insert(bit);
175
+ }
176
+
177
+ for (auto bit : sigmap(action.second))
178
+ if (bit.wire) used_wires.insert(bit);
179
+ }
180
+ for (auto switch_ : all_cases[i]->switches) {
181
+ for (auto case_ : switch_->cases) {
182
+ all_cases.push_back(case_);
183
+ for (auto compare : case_->compare)
184
+ for (auto bit : sigmap(compare))
185
+ if (bit.wire) used_wires.insert(bit);
186
+ }
187
+ }
188
+ }
189
+ for (auto &sync : proc_it.second->syncs) {
190
+ for (auto bit : sigmap(sync->signal))
191
+ if (bit.wire) used_wires.insert(bit);
192
+ for (auto action : sync->actions) {
193
+ for (auto bit : sigmap(action.first)) {
194
+ wire_drivers[bit].push_back(
195
+ stringf("action %s <= %s (sync rule) in process %s",
196
+ log_signal(action.first), log_signal(action.second), module->twines().unescaped_str(proc_it.first)));
197
+ if (bit.wire && sync->type != RTLIL::SyncType::STi)
198
+ proc_driven_bits.insert(bit);
199
+ }
200
+ for (auto bit : sigmap(action.second))
201
+ if (bit.wire) used_wires.insert(bit);
202
+ }
203
+ for (auto memwr : sync->mem_write_actions) {
204
+ for (auto bit : sigmap(memwr.address))
205
+ if (bit.wire) used_wires.insert(bit);
206
+ for (auto bit : sigmap(memwr.data))
207
+ if (bit.wire) used_wires.insert(bit);
208
+ for (auto bit : sigmap(memwr.enable))
209
+ if (bit.wire) used_wires.insert(bit);
210
+ }
211
+ }
212
+ for (auto bit : proc_driven_bits)
213
+ wire_drivers_count[bit]++;
214
+ }
215
+
216
+ struct CircuitEdgesDatabase : AbstractCellEdgesDatabase {
217
+ TopoSort<std::pair<RTLIL::IdString, int>> &topo;
218
+ SigMap sigmap;
219
+ bool force_detail;
220
+
221
+ CircuitEdgesDatabase(TopoSort<std::pair<RTLIL::IdString, int>> &topo, SigMap &sigmap, bool force_detail)
222
+ : topo(topo), sigmap(sigmap), force_detail(force_detail) {}
223
+
224
+ void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit,
225
+ RTLIL::IdString to_port, int to_bit, int) override {
226
+ SigSpec from_portsig = cell->getPort(from_port);
227
+ SigSpec to_portsig = cell->getPort(to_port);
228
+ log_assert(from_bit >= 0 && from_bit < from_portsig.size());
229
+ log_assert(to_bit >= 0 && to_bit < to_portsig.size());
230
+ SigBit from = sigmap(from_portsig[from_bit]);
231
+ SigBit to = sigmap(to_portsig[to_bit]);
232
+
233
+ if (from.wire && to.wire)
234
+ topo.edge(std::make_pair(IdString(from.wire->name), from.offset), std::make_pair(IdString(to.wire->name), to.offset));
235
+ }
236
+
237
+ bool detail_costly(Cell *cell) {
238
+ // Only those cell types for which the edge data can expode quadratically
239
+ // in port widths are those for us to check.
240
+ if (!cell->type.in(
241
+ ID($add), ID($sub),
242
+ ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx),
243
+ ID($pmux), ID($bmux)))
244
+ return false;
245
+
246
+ int in_widths = 0, out_widths = 0;
247
+
248
+ if (cell->type.in(ID($pmux), ID($bmux))) {
249
+ // We're skipping inputs A and B, since each of their bits contributes only one edge
250
+ in_widths = GetSize(cell->getPort(ID::S));
251
+ out_widths = GetSize(cell->getPort(ID::Y));
252
+ } else {
253
+ for (auto &conn : cell->connections()) {
254
+ if (cell->input(conn.first))
255
+ in_widths += conn.second.size();
256
+ if (cell->output(conn.first))
257
+ out_widths += conn.second.size();
258
+ }
259
+ }
260
+
261
+ const int threshold = 1024;
262
+
263
+ // if the multiplication may overflow we will catch it here
264
+ if (in_widths + out_widths >= threshold)
265
+ return true;
266
+
267
+ if (in_widths * out_widths >= threshold)
268
+ return true;
269
+
270
+ return false;
271
+ }
272
+
273
+ bool add_edges_from_cell(Cell *cell) {
274
+ if (force_detail || !detail_costly(cell)) {
275
+ if (AbstractCellEdgesDatabase::add_edges_from_cell(cell))
276
+ return true;
277
+ }
278
+
279
+ // We don't have accurate cell edges, do the fallback of all input-output pairs
280
+ for (auto &conn : cell->connections()) {
281
+ if (cell->input(conn.first))
282
+ for (auto bit : sigmap(conn.second))
283
+ if (bit.wire)
284
+ topo.edge(std::make_pair(IdString(bit.wire->name), bit.offset),
285
+ std::make_pair(IdString(cell->name), -1));
286
+
287
+ if (cell->output(conn.first))
288
+ for (auto bit : sigmap(conn.second))
289
+ if (bit.wire)
290
+ topo.edge(std::make_pair(IdString(cell->name), -1),
291
+ std::make_pair(IdString(bit.wire->name), bit.offset));
292
+ }
293
+
294
+ // Return false to signify the fallback
295
+ return false;
296
+ }
297
+ };
298
+
299
+ CircuitEdgesDatabase edges_db(topo, sigmap, force_detailed_loop_check);
300
+
301
+ pool<Cell *> coarsened_cells;
302
+ for (auto cell : module->cells())
303
+ {
304
+ if (cell->type.begins_with("$") && !yosys_celltypes.cell_known(cell->type) && design->module(cell->type) == nullptr) {
305
+ log_warning("Cell %s.%s has unknown internal type %s.\n", module, cell, cell->type.unescape());
306
+ counter++;
307
+ }
308
+
309
+ if (mapped && cell->type.begins_with("$") && design->module(cell->type) == nullptr) {
310
+ if (allow_tbuf && cell->type == ID($_TBUF_)) goto cell_allowed;
311
+ log_warning("Cell %s.%s is an unmapped internal cell of type %s.\n", module, cell, cell->type.unescape());
312
+ counter++;
313
+ cell_allowed:;
314
+ }
315
+
316
+ if (
317
+ nolatches && !cell->get_bool_attribute(ID::always_latch) && (
318
+ cell->type.in(ID($dlatch), ID($adlatch), ID($dlatchsr)) ||
319
+ cell->type.begins_with("$_DLATCH_") || cell->type.begins_with("$_DLATCHSR_"))
320
+ ) {
321
+ log_warning("Cell %s.%s is a latch of type %s.\n", module, cell, cell->type.unescape());
322
+ counter++;
323
+ }
324
+
325
+ for (auto &conn : cell->connections()) {
326
+ bool input = cell->input(conn.first);
327
+ bool output = cell->output(conn.first);
328
+
329
+ SigSpec sig = sigmap(conn.second);
330
+ for (int i = 0; i < sig.size(); i++) {
331
+ SigBit bit = sig[i];
332
+
333
+ if (input && bit.wire)
334
+ used_wires.insert(bit);
335
+ if (output && !input && bit.wire)
336
+ wire_drivers_count[bit]++;
337
+ if (output && (bit.wire || !input))
338
+ wire_drivers[bit].push_back(stringf("port %s[%d] of cell %s (%s)", cell->twines().unescaped_str(conn.first), i,
339
+ cell, cell->type.unescape()));
340
+ if (output)
341
+ driver_cells[bit] = cell;
342
+ }
343
+ }
344
+
345
+ if (yosys_celltypes.cell_evaluable(cell->type) || cell->type.in(ID($mem_v2), ID($memrd), ID($memrd_v2), ID($barrier)) \
346
+ || cell->is_builtin_ff()) {
347
+ if (!edges_db.add_edges_from_cell(cell))
348
+ coarsened_cells.insert(cell);
349
+ }
350
+ }
351
+
352
+ pool<SigBit> init_bits;
353
+
354
+ for (auto wire : module->wires()) {
355
+ if (wire->port_input) {
356
+ SigSpec sig = sigmap(wire);
357
+ for (int i = 0; i < GetSize(sig); i++)
358
+ if (sig[i].wire || !wire->port_output)
359
+ wire_drivers[sig[i]].push_back(stringf("module input %s[%d]", wire, i));
360
+ }
361
+ if (wire->port_output)
362
+ for (auto bit : sigmap(wire))
363
+ if (bit.wire) used_wires.insert(bit);
364
+ if (wire->port_input && !wire->port_output)
365
+ for (auto bit : sigmap(wire))
366
+ if (bit.wire) wire_drivers_count[bit]++;
367
+ if (wire->attributes.count(ID::init)) {
368
+ Const initval = wire->attributes.at(ID::init);
369
+ for (int i = 0; i < GetSize(initval) && i < GetSize(wire); i++)
370
+ if (initval[i] == State::S0 || initval[i] == State::S1)
371
+ init_bits.insert(sigmap(SigBit(wire, i)));
372
+ if (noinit) {
373
+ log_warning("Wire %s.%s has an unprocessed 'init' attribute.\n", module, wire);
374
+ counter++;
375
+ }
376
+ }
377
+ }
378
+
379
+ for (auto state : {State::S0, State::S1, State::Sx})
380
+ if (wire_drivers.count(state)) {
381
+ string message = stringf("Drivers conflicting with a constant %s driver:\n", log_signal(state));
382
+ for (auto str : wire_drivers[state])
383
+ message += stringf(" %s\n", str);
384
+ log_warning("%s", message);
385
+ counter++;
386
+ }
387
+
388
+ for (auto it : wire_drivers)
389
+ if (wire_drivers_count[it.first] > 1) {
390
+ string message = stringf("multiple conflicting drivers for %s.%s:\n", module, log_signal(it.first));
391
+ for (auto str : it.second)
392
+ message += stringf(" %s\n", str);
393
+ log_warning("%s", message);
394
+ counter++;
395
+ }
396
+
397
+ for (auto bit : used_wires)
398
+ if (!wire_drivers.count(bit)) {
399
+ log_warning("Wire %s.%s is used but has no driver.\n", module, log_signal(bit));
400
+ counter++;
401
+ }
402
+
403
+ topo.sort();
404
+ for (auto &loop : topo.loops) {
405
+ string message = stringf("found logic loop in module %s:\n", module);
406
+
407
+ // `loop` only contains wire bits, or an occasional special helper node for cells for
408
+ // which we have done the edges fallback. The cell and its ports that led to an edge are
409
+ // a piece of information we need to recover now. For that we need to have the previous
410
+ // wire bit of the loop at hand.
411
+ SigBit prev;
412
+ for (auto it = loop.rbegin(); it != loop.rend(); it++)
413
+ if (it->second != -1) { // skip the fallback helper nodes
414
+ prev = SigBit(module->wire(it->first), it->second);
415
+ break;
416
+ }
417
+ log_assert(prev != SigBit());
418
+
419
+ for (auto &pair : loop) {
420
+ if (pair.second == -1)
421
+ continue; // helper node for edges fallback, we can ignore it
422
+
423
+ struct MatchingEdgePrinter : AbstractCellEdgesDatabase {
424
+ std::string &message;
425
+ SigMap &sigmap;
426
+ SigBit from, to;
427
+ int nhits;
428
+ const int HITS_LIMIT = 3;
429
+
430
+ MatchingEdgePrinter(std::string &message, SigMap &sigmap, SigBit from, SigBit to)
431
+ : message(message), sigmap(sigmap), from(from), to(to), nhits(0) {}
432
+
433
+ void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit,
434
+ RTLIL::IdString to_port, int to_bit, int) override {
435
+ SigBit edge_from = sigmap(cell->getPort(from_port))[from_bit];
436
+ SigBit edge_to = sigmap(cell->getPort(to_port))[to_bit];
437
+
438
+ if (edge_from == from && edge_to == to && nhits++ < HITS_LIMIT)
439
+ message += stringf(" %s[%d] --> %s[%d]\n", cell->twines().unescaped_str(from_port), from_bit,
440
+ cell->twines().unescaped_str(to_port), to_bit);
441
+ if (nhits == HITS_LIMIT)
442
+ message += " ...\n";
443
+ }
444
+ };
445
+
446
+ Wire *wire = module->wire(pair.first);
447
+ log_assert(wire);
448
+ SigBit bit(wire, pair.second);
449
+ log_assert(driver_cells.count(bit));
450
+ Cell *driver = driver_cells.at(bit);
451
+
452
+ std::string driver_src;
453
+ if (driver->has_attribute(ID::src)) {
454
+ std::string src_attr = driver->get_src_attribute();
455
+ driver_src = stringf(" source: %s", src_attr);
456
+ }
457
+
458
+ message += stringf(" cell %s (%s)%s\n", driver, driver->type.unescape(), driver_src);
459
+
460
+ if (!coarsened_cells.count(driver)) {
461
+ MatchingEdgePrinter printer(message, sigmap, prev, bit);
462
+ printer.add_edges_from_cell(driver);
463
+ } else {
464
+ message += " (cell's internal connectivity overapproximated; loop may be a false positive)\n";
465
+ suggest_detail = true;
466
+ }
467
+
468
+ if (wire->name.isPublic()) {
469
+ std::string wire_src;
470
+ if (wire->has_attribute(ID::src)) {
471
+ std::string src_attr = wire->get_src_attribute();
472
+ wire_src = stringf(" source: %s", src_attr);
473
+ }
474
+ message += stringf(" wire %s%s\n", log_signal(SigBit(wire, pair.second)), wire_src);
475
+ }
476
+
477
+ prev = bit;
478
+ }
479
+ log_warning("%s", message);
480
+ counter++;
481
+ }
482
+
483
+ if (initdrv)
484
+ {
485
+ for (auto cell : module->cells())
486
+ {
487
+ if (cell->is_builtin_ff() == 0)
488
+ continue;
489
+
490
+ for (auto bit : sigmap(cell->getPort(ID::Q)))
491
+ init_bits.erase(bit);
492
+ }
493
+
494
+ SigSpec init_sig(init_bits);
495
+ init_sig.sort_and_unify();
496
+
497
+ for (auto chunk : init_sig.chunks()) {
498
+ log_warning("Wire %s.%s has 'init' attribute and is not driven by an FF cell.\n", module, log_signal(chunk));
499
+ counter++;
500
+ }
501
+ }
502
+ }
503
+
504
+ log("Found and reported %d problems.\n", counter);
505
+
506
+ if (suggest_detail)
507
+ log("Consider re-running with '-force-detailed-loop-check' to rule out false positives.\n");
508
+
509
+ if (assert_mode && counter > 0)
510
+ log_error("Found %d problems in 'check -assert'.\n", counter);
511
+ }
512
+ } CheckPass;
513
+
514
+ struct CheckMemPass : public Pass {
515
+ CheckMemPass() : Pass("check_mem", "check for obvious memory problems in the design") { }
516
+ bool formatted_help() override {
517
+ auto *help = PrettyHelp::get_current();
518
+ help->set_group("passes/status");
519
+
520
+ auto content_root = help->get_root();
521
+
522
+ content_root->usage("check_mem [selection]");
523
+ content_root->paragraph(
524
+ "This pass identifies the following problems in the current design: "
525
+ "addressing invalid memory."
526
+ );
527
+
528
+ content_root->option("-non-const", "also check non-const address signals (may produce false-positives)");
529
+ content_root->option("-assert", "produce a runtime error if any problems are found in the current design");
530
+
531
+ return true;
532
+ }
533
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
534
+ {
535
+ int counter = 0;
536
+ bool assert_mode = false;
537
+ bool nonconst_mode = false;
538
+ size_t argidx;
539
+ for (argidx = 1; argidx < args.size(); argidx++) {
540
+ if (args[argidx] == "-assert") {
541
+ assert_mode = true;
542
+ continue;
543
+ }
544
+ if (args[argidx] == "-non-const") {
545
+ nonconst_mode = true;
546
+ continue;
547
+ }
548
+ break;
549
+ }
550
+
551
+ extra_args(args, argidx, design);
552
+
553
+ log_header(design, "Executing CHECK_MEM pass.\n");
554
+
555
+ for (auto *module : design->selected_unboxed_modules_warn()) {
556
+ for (auto mem : Mem::get_selected_memories(module)) {
557
+ int min_addr = mem.mem->start_offset;
558
+ int max_addr = mem.mem->size + min_addr - 1;
559
+ for (auto &init : mem.inits) {
560
+ int start = init.addr.as_int();
561
+ if (start < min_addr) {
562
+ log_warning("Mem %s.%s starts at %d but initializes address %d.\n", module, mem.mem, min_addr, start);
563
+ counter++;
564
+ }
565
+ int end = start + (GetSize(init.data) / mem.width) - 1;
566
+ if (end > max_addr) {
567
+ log_warning("Mem %s.%s ends at %d but initializes address %d.\n", module, mem.mem, max_addr, end);
568
+ counter++;
569
+ }
570
+ }
571
+
572
+ auto check_addr = [min_addr, max_addr, &counter, module, &mem, &nonconst_mode](SigSpec &addr_sig, const char* access) {
573
+ if (addr_sig.is_fully_const()) {
574
+ auto addr = addr_sig.as_int();
575
+ if (addr < min_addr || addr > max_addr) {
576
+ log_warning("Mem %s.%s contains entries for addresses %d..%d but %s address %d.\n", module, mem.mem, min_addr, max_addr, access, addr);
577
+ counter++;
578
+ }
579
+ } else if (nonconst_mode) {
580
+ // TODO check addr_sig.has_const() for constant MSb/LSb that may change effective min/max
581
+ // TODO consider sat solver for variable addresses
582
+ int addr_sig_min = 0;
583
+ int addr_sig_max = (1 << addr_sig.size()) - 1;
584
+ if (min_addr > addr_sig_min || max_addr < addr_sig_max) {
585
+ log_warning("Mem %s.%s contains entries for addresses %d..%d but has a potentially dangerous non-const input %s\n", module, mem.mem, min_addr, max_addr, log_signal(addr_sig));
586
+ counter++;
587
+ }
588
+ }
589
+ };
590
+
591
+ // TODO test ABITS and WIDTH?
592
+ // TODO can we limit ports via selection?
593
+ for (auto &rd_port : mem.rd_ports)
594
+ check_addr(rd_port.addr, "reads");
595
+ for (auto &wr_port : mem.wr_ports)
596
+ check_addr(wr_port.addr, "writes");
597
+ }
598
+ }
599
+
600
+ if (assert_mode && counter > 0)
601
+ log_error("Found %d problems in 'check_mem -assert'.\n", counter);
602
+ }
603
+ } CheckMemPass;
604
+
605
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/chformal.cc ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ static RTLIL::IdString formal_flavor(RTLIL::Cell *cell)
28
+ {
29
+ if (cell->type != ID($check))
30
+ return cell->type;
31
+
32
+ std::string flavor_param = cell->getParam(ID(FLAVOR)).decode_string();
33
+ if (flavor_param == "assert")
34
+ return ID($assert);
35
+ else if (flavor_param == "assume")
36
+ return ID($assume);
37
+ else if (flavor_param == "cover")
38
+ return ID($cover);
39
+ else if (flavor_param == "live")
40
+ return ID($live);
41
+ else if (flavor_param == "fair")
42
+ return ID($fair);
43
+ else
44
+ log_abort();
45
+ }
46
+
47
+ static void set_formal_flavor(RTLIL::Cell *cell, RTLIL::IdString flavor)
48
+ {
49
+ if (cell->type != ID($check)) {
50
+ cell->type = flavor;
51
+ return;
52
+ }
53
+
54
+ if (flavor == ID($assert))
55
+ cell->setParam(ID(FLAVOR), std::string("assert"));
56
+ else if (flavor == ID($assume))
57
+ cell->setParam(ID(FLAVOR), std::string("assume"));
58
+ else if (flavor == ID($cover))
59
+ cell->setParam(ID(FLAVOR), std::string("cover"));
60
+ else if (flavor == ID($live))
61
+ cell->setParam(ID(FLAVOR), std::string("live"));
62
+ else if (flavor == ID($fair))
63
+ cell->setParam(ID(FLAVOR), std::string("fair"));
64
+ else
65
+ log_abort();
66
+ }
67
+
68
+ static bool is_triggered_check_cell(RTLIL::Cell * cell)
69
+ {
70
+ return cell->type == ID($check) && cell->getParam(ID(TRG_ENABLE)).as_bool();
71
+ }
72
+
73
+ struct ChformalPass : public Pass {
74
+ ChformalPass() : Pass("chformal", "change formal constraints of the design") {}
75
+
76
+ bool formatted_help() override {
77
+ auto *help = PrettyHelp::get_current();
78
+ help->set_group("formal");
79
+
80
+ auto content_root = help->get_root();
81
+
82
+ content_root->usage("chformal [types] [mode] [options] [selection]");
83
+ content_root->paragraph(
84
+ "Make changes to the formal constraints of the design. The [types] options "
85
+ "the type of constraint to operate on. If none of the following options are "
86
+ "given, the command will operate on all constraint types:"
87
+ );
88
+
89
+ content_root->option("-assert", "`$assert` cells, representing ``assert(...)`` constraints");
90
+ content_root->option("-assume", "`$assume` cells, representing ``assume(...)`` constraints");
91
+ content_root->option("-live", "`$live` cells, representing ``assert(s_eventually ...)``");
92
+ content_root->option("-fair", "`$fair` cells, representing ``assume(s_eventually ...)``");
93
+ content_root->option("-cover", "`$cover` cells, representing ``cover()`` statements");
94
+ content_root->paragraph(
95
+ "Additionally chformal will operate on `$check` cells corresponding to the "
96
+ "selected constraint types."
97
+ );
98
+
99
+ content_root->paragraph("Exactly one of the following modes must be specified:");
100
+
101
+ content_root->option("-remove", "remove the cells and thus constraints from the design");
102
+ content_root->option("-early",
103
+ "bypass FFs that only delay the activation of a constraint. When inputs "
104
+ "of the bypassed FFs do not remain stable between clock edges, this may "
105
+ "result in unexpected behavior."
106
+ );
107
+ content_root->option("-delay <N>", "delay activation of the constraint by <N> clock cycles");
108
+ content_root->option("-skip <N>", "ignore activation of the constraint in the first <N> clock cycles");
109
+ auto cover_option = content_root->open_option("-coverenable");
110
+ cover_option->paragraph(
111
+ "add cover statements for the enable signals of the constraints"
112
+ );
113
+ #ifdef YOSYS_ENABLE_VERIFIC
114
+ cover_option->paragraph(
115
+ "Note: For the Verific frontend it is currently not guaranteed that a "
116
+ "reachable SVA statement corresponds to an active enable signal."
117
+ );
118
+ #endif
119
+ content_root->option("-assert2assume");
120
+ content_root->option("-assert2cover");
121
+ content_root->option("-assume2assert");
122
+ content_root->option("-live2fair");
123
+ content_root->option("-fair2live", "change the roles of cells as indicated. these options can be combined");
124
+ content_root->option("-lower",
125
+ "convert each $check cell into an $assert, $assume, $live, $fair or "
126
+ "$cover cell. If the $check cell contains a message, also produce a "
127
+ "$print cell."
128
+ );
129
+ return true;
130
+ }
131
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
132
+ {
133
+ bool assert2assume = false;
134
+ bool assert2cover = false;
135
+ bool assume2assert = false;
136
+ bool live2fair = false;
137
+ bool fair2live = false;
138
+
139
+ pool<IdString> constr_types;
140
+ char mode = 0;
141
+ int mode_arg = 0;
142
+
143
+ size_t argidx;
144
+ for (argidx = 1; argidx < args.size(); argidx++)
145
+ {
146
+ if (args[argidx] == "-assert") {
147
+ constr_types.insert(ID($assert));
148
+ continue;
149
+ }
150
+ if (args[argidx] == "-assume") {
151
+ constr_types.insert(ID($assume));
152
+ continue;
153
+ }
154
+ if (args[argidx] == "-live") {
155
+ constr_types.insert(ID($live));
156
+ continue;
157
+ }
158
+ if (args[argidx] == "-fair") {
159
+ constr_types.insert(ID($fair));
160
+ continue;
161
+ }
162
+ if (args[argidx] == "-cover") {
163
+ constr_types.insert(ID($cover));
164
+ continue;
165
+ }
166
+ if (mode == 0 && args[argidx] == "-remove") {
167
+ mode = 'r';
168
+ continue;
169
+ }
170
+ if (mode == 0 && args[argidx] == "-early") {
171
+ mode = 'e';
172
+ continue;
173
+ }
174
+ if (mode == 0 && args[argidx] == "-delay" && argidx+1 < args.size()) {
175
+ mode = 'd';
176
+ mode_arg = atoi(args[++argidx].c_str());
177
+ continue;
178
+ }
179
+ if (mode == 0 && args[argidx] == "-skip" && argidx+1 < args.size()) {
180
+ mode = 's';
181
+ mode_arg = atoi(args[++argidx].c_str());
182
+ continue;
183
+ }
184
+ if (mode == 0 && args[argidx] == "-coverenable") {
185
+ mode = 'p';
186
+ continue;
187
+ }
188
+ if ((mode == 0 || mode == 'c') && args[argidx] == "-assert2assume") {
189
+ assert2assume = true;
190
+ mode = 'c';
191
+ continue;
192
+ }
193
+ if ((mode == 0 || mode == 'c') && args[argidx] == "-assert2cover") {
194
+ assert2cover = true;
195
+ mode = 'c';
196
+ continue;
197
+ }
198
+ if ((mode == 0 || mode == 'c') && args[argidx] == "-assume2assert") {
199
+ assume2assert = true;
200
+ mode = 'c';
201
+ continue;
202
+ }
203
+ if ((mode == 0 || mode == 'c') && args[argidx] == "-live2fair") {
204
+ live2fair = true;
205
+ mode = 'c';
206
+ continue;
207
+ }
208
+ if ((mode == 0 || mode == 'c') && args[argidx] == "-fair2live") {
209
+ fair2live = true;
210
+ mode = 'c';
211
+ continue;
212
+ }
213
+ if (mode == 0 && args[argidx] == "-lower") {
214
+ mode = 'l';
215
+ continue;
216
+ }
217
+ break;
218
+ }
219
+ extra_args(args, argidx, design);
220
+
221
+ if (constr_types.empty()) {
222
+ constr_types.insert(ID($assert));
223
+ constr_types.insert(ID($assume));
224
+ constr_types.insert(ID($live));
225
+ constr_types.insert(ID($fair));
226
+ constr_types.insert(ID($cover));
227
+ }
228
+
229
+ if (assert2assume && assert2cover) {
230
+ log_cmd_error("Cannot use both -assert2assume and -assert2cover.\n");
231
+ }
232
+
233
+ if (mode == 0)
234
+ log_cmd_error("Mode option is missing.\n");
235
+
236
+ for (auto module : design->selected_modules())
237
+ {
238
+ vector<Cell*> constr_cells;
239
+
240
+ for (auto cell : module->selected_cells())
241
+ if (constr_types.count(formal_flavor(cell)))
242
+ constr_cells.push_back(cell);
243
+
244
+ if (mode == 'r')
245
+ {
246
+ for (auto cell : constr_cells)
247
+ module->remove(cell);
248
+ }
249
+ else
250
+ if (mode == 'e')
251
+ {
252
+ SigMap sigmap(module);
253
+ dict<SigBit, pair<SigBit, pair<SigBit, bool>>> ffmap;
254
+ pool<SigBit> init_zero, init_one;
255
+
256
+ for (auto wire : module->wires())
257
+ {
258
+ if (wire->attributes.count(ID::init) == 0)
259
+ continue;
260
+
261
+ SigSpec initsig = sigmap(wire);
262
+ Const initval = wire->attributes.at(ID::init);
263
+
264
+ for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++) {
265
+ if (initval[i] == State::S0)
266
+ init_zero.insert(initsig[i]);
267
+ if (initval[i] == State::S1)
268
+ init_one.insert(initsig[i]);
269
+ }
270
+ }
271
+
272
+ for (auto cell : module->selected_cells())
273
+ {
274
+ if (cell->type == ID($ff)) {
275
+ SigSpec D = sigmap(cell->getPort(ID::D));
276
+ SigSpec Q = sigmap(cell->getPort(ID::Q));
277
+ for (int i = 0; i < GetSize(D); i++)
278
+ ffmap[Q[i]] = make_pair(D[i], make_pair(State::Sm, false));
279
+ }
280
+ if (cell->type == ID($dff)) {
281
+ SigSpec D = sigmap(cell->getPort(ID::D));
282
+ SigSpec Q = sigmap(cell->getPort(ID::Q));
283
+ SigSpec C = sigmap(cell->getPort(ID::CLK));
284
+ bool clockpol = cell->getParam(ID::CLK_POLARITY).as_bool();
285
+ for (int i = 0; i < GetSize(D); i++)
286
+ ffmap[Q[i]] = make_pair(D[i], make_pair(C, clockpol));
287
+ }
288
+ }
289
+
290
+ for (auto cell : constr_cells)
291
+ {
292
+ if (is_triggered_check_cell(cell)) {
293
+ if (cell->getParam(ID::TRG_WIDTH).as_int() != 1)
294
+ continue;
295
+ cell->setPort(ID::TRG, SigSpec());
296
+ cell->setParam(ID::TRG_ENABLE, false);
297
+ cell->setParam(ID::TRG_WIDTH, 0);
298
+ cell->setParam(ID::TRG_POLARITY, false);
299
+ }
300
+
301
+ IdString flavor = formal_flavor(cell);
302
+
303
+ while (true)
304
+ {
305
+ SigSpec A = sigmap(cell->getPort(ID::A));
306
+ SigSpec EN = sigmap(cell->getPort(ID::EN));
307
+
308
+ if (ffmap.count(A) == 0 || ffmap.count(EN) == 0)
309
+ break;
310
+
311
+ if (!init_zero.count(EN)) {
312
+ if (flavor == ID($cover)) break;
313
+ if (flavor.in(ID($assert), ID($assume)) && !init_one.count(A)) break;
314
+ }
315
+
316
+ const auto &A_map = ffmap.at(A);
317
+ const auto &EN_map = ffmap.at(EN);
318
+
319
+ if (A_map.second != EN_map.second)
320
+ break;
321
+
322
+ cell->setPort(ID::A, A_map.first);
323
+ cell->setPort(ID::EN, EN_map.first);
324
+ }
325
+ }
326
+ }
327
+ else
328
+ if (mode == 'd')
329
+ {
330
+ for (auto cell : constr_cells)
331
+ {
332
+ if (is_triggered_check_cell(cell))
333
+ log_error("Cannot delay edge triggered $check cell %s, run async2sync or clk2fflogic first.\n", cell);
334
+
335
+ for (int i = 0; i < mode_arg; i++)
336
+ {
337
+ SigSpec orig_a = cell->getPort(ID::A);
338
+ SigSpec orig_en = cell->getPort(ID::EN);
339
+
340
+ Wire *new_a = module->addWire(NEW_ID);
341
+ Wire *new_en = module->addWire(NEW_ID);
342
+ new_en->attributes[ID::init] = State::S0;
343
+
344
+ module->addFf(NEW_ID, orig_a, new_a);
345
+ module->addFf(NEW_ID, orig_en, new_en);
346
+
347
+ cell->setPort(ID::A, new_a);
348
+ cell->setPort(ID::EN, new_en);
349
+ }
350
+ }
351
+ }
352
+ else
353
+ if (mode == 's')
354
+ {
355
+ SigSpec en = State::S1;
356
+
357
+ for (int i = 0; i < mode_arg; i++) {
358
+ Wire *w = module->addWire(NEW_ID);
359
+ w->attributes[ID::init] = State::S0;
360
+ module->addFf(NEW_ID, en, w);
361
+ en = w;
362
+ }
363
+
364
+ for (auto cell : constr_cells)
365
+ cell->setPort(ID::EN, module->LogicAnd(NEW_ID, en, cell->getPort(ID::EN)));
366
+ }
367
+ else
368
+ if (mode =='p')
369
+ {
370
+ for (auto cell : constr_cells)
371
+ {
372
+ if (cell->type == ID($check)) {
373
+ Cell *cover = module->addCell(NEW_ID_SUFFIX("coverenable"), ID($check));
374
+ cover->attributes = cell->attributes;
375
+ cover->parameters = cell->parameters;
376
+ cover->setParam(ID(FLAVOR), Const("cover"));
377
+
378
+ for (auto const &conn : cell->connections())
379
+ if (!conn.first.in(ID::A, ID::EN))
380
+ cover->setPort(conn.first, conn.second);
381
+ cover->setPort(ID::A, cell->getPort(ID::EN));
382
+ cover->setPort(ID::EN, State::S1);
383
+ } else {
384
+ module->addCover(NEW_ID_SUFFIX("coverenable"),
385
+ cell->getPort(ID::EN), State::S1, cell->get_src_attribute());
386
+ }
387
+ }
388
+ }
389
+ else
390
+ if (mode == 'c')
391
+ {
392
+ for (auto cell : constr_cells) {
393
+ IdString flavor = formal_flavor(cell);
394
+ if (assert2assume && flavor == ID($assert))
395
+ set_formal_flavor(cell, ID($assume));
396
+ if (assert2cover && flavor == ID($assert))
397
+ set_formal_flavor(cell, ID($cover));
398
+ else if (assume2assert && flavor == ID($assume))
399
+ set_formal_flavor(cell, ID($assert));
400
+ else if (live2fair && flavor == ID($live))
401
+ set_formal_flavor(cell, ID($fair));
402
+ else if (fair2live && flavor == ID($fair))
403
+ set_formal_flavor(cell, ID($live));
404
+ }
405
+ }
406
+ else
407
+ if (mode == 'l')
408
+ {
409
+ for (auto cell : constr_cells) {
410
+ if (cell->type != ID($check))
411
+ continue;
412
+
413
+ if (is_triggered_check_cell(cell))
414
+ log_error("Cannot lower edge triggered $check cell %s, run async2sync or clk2fflogic first.\n", cell);
415
+
416
+
417
+ Cell *plain_cell = module->addCell(NEW_ID, formal_flavor(cell));
418
+
419
+ plain_cell->attributes = cell->attributes;
420
+
421
+ SigBit sig_a = cell->getPort(ID::A);
422
+ SigBit sig_en = cell->getPort(ID::EN);
423
+
424
+ plain_cell->setPort(ID::A, sig_a);
425
+ plain_cell->setPort(ID::EN, sig_en);
426
+
427
+ if (plain_cell->type.in(ID($assert), ID($assume)))
428
+ sig_a = module->Not(NEW_ID, sig_a);
429
+
430
+ SigBit combined_en = module->And(NEW_ID, sig_a, sig_en);
431
+
432
+ module->swap_names(cell, plain_cell);
433
+
434
+ if (cell->getPort(ID::ARGS).empty()) {
435
+ module->remove(cell);
436
+ } else {
437
+ cell->type = ID($print);
438
+ cell->setPort(ID::EN, combined_en);
439
+ cell->unsetPort(ID::A);
440
+ cell->unsetParam(ID(FLAVOR));
441
+ }
442
+ }
443
+ }
444
+ }
445
+ }
446
+ } ChformalPass;
447
+
448
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/chtype.cc ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+
22
+ USING_YOSYS_NAMESPACE
23
+ PRIVATE_NAMESPACE_BEGIN
24
+
25
+ static IdString publish(TwinePool &twines, IdString id) {
26
+ std::string name = twines.str(id);
27
+ if (!name.starts_with("$"))
28
+ return id;
29
+ log_debug("publishing %s\n", name);
30
+ IdString published = twines.add("\\" + name);
31
+ log_debug("published %s\n", twines.str(published));
32
+ return published;
33
+ }
34
+
35
+ static void publish_design(RTLIL::Design* design) {
36
+ auto saved_modules = design->modules_;
37
+ design->modules_.clear();
38
+ for (auto& [_, mod] : saved_modules) {
39
+ IdString new_name = publish(design->twines(), mod->name);
40
+ mod->name = new_name;
41
+ design->modules_[new_name] = mod;
42
+ for (auto* cell : mod->cells())
43
+ cell->type = publish(design->twines(), cell->type);
44
+ }
45
+ }
46
+
47
+
48
+ struct ChtypePass : public Pass {
49
+ ChtypePass() : Pass("chtype", "change type of cells in the design") { }
50
+ void help() override
51
+ {
52
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
53
+ log("\n");
54
+ log(" chtype [options] [selection]\n");
55
+ log("\n");
56
+ log("Change the types of cells in the design.\n");
57
+ log("\n");
58
+ log(" -set <type>\n");
59
+ log(" set the cell type to the given type\n");
60
+ log("\n");
61
+ log(" -map <old_type> <new_type>\n");
62
+ log(" change cells types that match <old_type> to <new_type>\n");
63
+ log("\n");
64
+ log(" -publish_icells\n");
65
+ log(" change internal cells types to public types\n");
66
+ log("\n");
67
+ log("\n");
68
+ }
69
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
70
+ {
71
+ IdString set_type;
72
+ dict<IdString, IdString> map_types;
73
+ bool publish_mode = false;
74
+
75
+ size_t argidx;
76
+ for (argidx = 1; argidx < args.size(); argidx++)
77
+ {
78
+ if (set_type == IdString() && args[argidx] == "-set" && argidx+1 < args.size()) {
79
+ set_type = design->twines().add(RTLIL::escape_id(args[++argidx]));
80
+ continue;
81
+ }
82
+ if (args[argidx] == "-map" && argidx+2 < args.size()) {
83
+ IdString old_type = design->twines().add(RTLIL::escape_id(args[++argidx]));
84
+ IdString new_type = design->twines().add(RTLIL::escape_id(args[++argidx]));
85
+ map_types[old_type] = new_type;
86
+ continue;
87
+ }
88
+ if (args[argidx] == "-publish_icells") {
89
+ publish_mode = true;
90
+ continue;
91
+ }
92
+ break;
93
+ }
94
+ extra_args(args, argidx, design);
95
+
96
+ if (publish_mode)
97
+ publish_design(design);
98
+
99
+ for (auto module : design->selected_modules())
100
+ {
101
+ for (auto cell : module->selected_cells())
102
+ {
103
+ if (map_types.count(cell->type)) {
104
+ cell->type = map_types.at(cell->type);
105
+ continue;
106
+ }
107
+
108
+ if (set_type != IdString()) {
109
+ cell->type = set_type;
110
+ continue;
111
+ }
112
+ }
113
+ }
114
+ }
115
+ } ChtypePass;
116
+
117
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/clean_zerowidth.cc ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2021 Marcelina Kościelnicka <mwk@0x04.net>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/celltypes.h"
22
+ #include "kernel/mem.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct CleanZeroWidthPass : public Pass {
28
+ CleanZeroWidthPass() : Pass("clean_zerowidth", "clean zero-width connections from the design") { }
29
+ void help() override
30
+ {
31
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
32
+ log("\n");
33
+ log(" clean_zerowidth [selection]\n");
34
+ log("\n");
35
+ log("Fixes the selected cells and processes to contain no zero-width connections.\n");
36
+ log("Depending on the cell type, this may be implemented by removing the connection,\n");
37
+ log("widening it to 1-bit, or removing the cell altogether.\n");
38
+ log("\n");
39
+ }
40
+
41
+ void clean_case(RTLIL::CaseRule *cs)
42
+ {
43
+ std::vector<SigSig> new_actions;
44
+ for (auto &action : cs->actions)
45
+ if (GetSize(action.first) != 0)
46
+ new_actions.push_back(action);
47
+ std::swap(new_actions, cs->actions);
48
+ for (auto sw : cs->switches)
49
+ for (auto scs : sw->cases)
50
+ clean_case(scs);
51
+ }
52
+
53
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
54
+ {
55
+ size_t argidx;
56
+ for (argidx = 1; argidx < args.size(); argidx++)
57
+ {
58
+ break;
59
+ }
60
+ extra_args(args, argidx, design);
61
+
62
+ CellTypes ct;
63
+ ct.setup();
64
+
65
+ for (auto module : design->selected_modules())
66
+ {
67
+ for (auto cell : module->selected_cells())
68
+ {
69
+ if (!ct.cell_known(cell->type)) {
70
+ // User-defined cell: just prune zero-width connections.
71
+ for (auto it: cell->connections()) {
72
+ if (GetSize(it.second) == 0) {
73
+ cell->unsetPort(it.first);
74
+ }
75
+ }
76
+ } else if (cell->is_builtin_ff()) {
77
+ // Coarse FF cells: remove if WIDTH == 0 (no outputs).
78
+ // This will also trigger on fine cells, so use the Q port
79
+ // width instead of actual WIDTH parameter.
80
+ if (GetSize(cell->getPort(ID::Q)) == 0) {
81
+ module->remove(cell);
82
+ }
83
+ } else if (cell->type.in(ID($pmux), ID($bmux), ID($demux))) {
84
+ // Remove altogether if WIDTH is 0, replace with
85
+ // a connection if S_WIDTH is 0.
86
+ if (cell->getParam(ID::WIDTH).as_int() == 0) {
87
+ module->remove(cell);
88
+ }
89
+ if (cell->getParam(ID::S_WIDTH).as_int() == 0) {
90
+ module->connect(cell->getPort(ID::Y), cell->getPort(ID::A));
91
+ module->remove(cell);
92
+ }
93
+ } else if (cell->type == ID($concat)) {
94
+ // If a concat has a zero-width input: replace with direct
95
+ // connection to the other input.
96
+ if (cell->getParam(ID::A_WIDTH).as_int() == 0) {
97
+ module->connect(cell->getPort(ID::Y), cell->getPort(ID::B));
98
+ module->remove(cell);
99
+ } else if (cell->getParam(ID::B_WIDTH).as_int() == 0) {
100
+ module->connect(cell->getPort(ID::Y), cell->getPort(ID::A));
101
+ module->remove(cell);
102
+ }
103
+ } else if (cell->type == ID($fsm)) {
104
+ // TODO: not supported
105
+ } else if (cell->is_mem_cell()) {
106
+ // Skip — will be handled below.
107
+ } else if (cell->type == ID($lut)) {
108
+ // Zero-width LUT is just a const driver.
109
+ if (cell->getParam(ID::WIDTH).as_int() == 0) {
110
+ module->connect(cell->getPort(ID::Y), cell->getParam(ID::LUT)[0]);
111
+ module->remove(cell);
112
+ }
113
+ } else if (cell->type == ID($sop)) {
114
+ // Zero-width SOP is just a const driver.
115
+ if (cell->getParam(ID::WIDTH).as_int() == 0) {
116
+ // The value is 1 iff DEPTH is non-0.
117
+ bool val = cell->getParam(ID::DEPTH).as_int() != 0;
118
+ module->connect(cell->getPort(ID::Y), val);
119
+ module->remove(cell);
120
+ }
121
+ } else if (cell->hasParam(ID::WIDTH)) {
122
+ // For cells with WIDTH parameter: remove if zero.
123
+ if (cell->getParam(ID::WIDTH).as_int() == 0) {
124
+ module->remove(cell);
125
+ }
126
+ } else if (cell->hasParam(ID::Y_WIDTH)) {
127
+ // For most operators: remove if Y width is 0, expand
128
+ // A and B to 1-bit if their width is 0.
129
+ if (cell->getParam(ID::Y_WIDTH).as_int() == 0) {
130
+ module->remove(cell);
131
+ } else if (cell->type.in(ID($macc), ID($macc_v2))) {
132
+ // TODO: fixing zero-width A and B not supported.
133
+ } else {
134
+ if (cell->getParam(ID::A_WIDTH).as_int() == 0) {
135
+ cell->setPort(ID::A, State::S0);
136
+ cell->setParam(ID::A_WIDTH, 1);
137
+ }
138
+ if (cell->hasParam(ID::B_WIDTH) && cell->getParam(ID::B_WIDTH).as_int() == 0) {
139
+ cell->setPort(ID::B, State::S0);
140
+ cell->setParam(ID::B_WIDTH, 1);
141
+ }
142
+ }
143
+ }
144
+ }
145
+
146
+ // NOTE: Zero-width switch signals are left alone for processes, as there
147
+ // is no simple way of cleaning them up.
148
+ for (auto &it: module->processes) {
149
+ if (!design->selected(module, it.second))
150
+ continue;
151
+ clean_case(&it.second->root_case);
152
+ for (auto sync : it.second->syncs) {
153
+ std::vector<int> swizzle;
154
+ std::vector<RTLIL::MemWriteAction> new_memwr_actions;
155
+ for (int i = 0; i < GetSize(sync->mem_write_actions); i++) {
156
+ auto &memwr = sync->mem_write_actions[i];
157
+ if (GetSize(memwr.data) == 0)
158
+ continue;
159
+ if (GetSize(memwr.address) == 0)
160
+ memwr.address = State::S0;
161
+ RTLIL::Const::Builder new_mask_bits(swizzle.size());
162
+ for (auto x : swizzle) {
163
+ new_mask_bits.push_back(memwr.priority_mask[x]);
164
+ }
165
+ memwr.priority_mask = new_mask_bits.build();
166
+ swizzle.push_back(i);
167
+ new_memwr_actions.push_back(memwr);
168
+ }
169
+ std::swap(new_memwr_actions, sync->mem_write_actions);
170
+ std::vector<SigSig> new_actions;
171
+ for (auto &action : sync->actions)
172
+ if (GetSize(action.first) != 0)
173
+ new_actions.push_back(action);
174
+ std::swap(new_actions, sync->actions);
175
+ }
176
+ }
177
+
178
+ for (auto &mem : Mem::get_selected_memories(module)) {
179
+ if (mem.width == 0) {
180
+ mem.remove();
181
+ continue;
182
+ }
183
+ for (auto &init : mem.inits) {
184
+ if (GetSize(init.addr) == 0) {
185
+ init.addr = State::S0;
186
+ }
187
+ }
188
+ for (auto &port : mem.rd_ports) {
189
+ if (GetSize(port.addr) == 0) {
190
+ port.addr = State::S0;
191
+ }
192
+ }
193
+ for (auto &port : mem.wr_ports) {
194
+ if (GetSize(port.addr) == 0) {
195
+ port.addr = State::S0;
196
+ }
197
+ }
198
+ mem.emit();
199
+ }
200
+
201
+ std::vector<SigSig> new_conns;
202
+ for (auto &conn : module->connections())
203
+ if (GetSize(conn.first) != 0)
204
+ new_conns.push_back(conn);
205
+ module->new_connections(new_conns);
206
+ }
207
+ }
208
+ } CleanZeroWidthPass;
209
+
210
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/connect.cc ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/rtlil.h"
22
+ #include "kernel/sigtools.h"
23
+ #include "kernel/celltypes.h"
24
+ #include "kernel/log.h"
25
+
26
+ USING_YOSYS_NAMESPACE
27
+ PRIVATE_NAMESPACE_BEGIN
28
+
29
+ static void unset_drivers(RTLIL::Design *design, RTLIL::Module *module, SigMap &sigmap, RTLIL::SigSpec &sig)
30
+ {
31
+ CellTypes ct(design);
32
+
33
+ RTLIL::Wire *dummy_wire = module->addWire(NEW_ID, sig.size());
34
+
35
+ for (auto cell : module->cells())
36
+ for (auto &port : cell->connections_)
37
+ if (ct.cell_output(cell->type, port.first))
38
+ sigmap(port.second).replace(sig, dummy_wire, &port.second);
39
+
40
+ for (auto &conn : module->connections_)
41
+ sigmap(conn.first).replace(sig, dummy_wire, &conn.first);
42
+ }
43
+
44
+ struct ConnectPass : public Pass {
45
+ ConnectPass() : Pass("connect", "create or remove connections") { }
46
+ void help() override
47
+ {
48
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
49
+ log("\n");
50
+ log(" connect [-nomap] [-nounset] -set <lhs-expr> <rhs-expr> [selection]\n");
51
+ log("\n");
52
+ log("Create a connection. This is equivalent to adding the statement 'assign\n");
53
+ log("<lhs-expr> = <rhs-expr>;' to the Verilog input. Per default, all existing\n");
54
+ log("drivers for <lhs-expr> are unconnected. This can be overwritten by using\n");
55
+ log("the -nounset option.\n");
56
+ log("\n");
57
+ log("\n");
58
+ log(" connect [-nomap] -unset <expr> [selection]\n");
59
+ log("\n");
60
+ log("Unconnect all existing drivers for the specified expression.\n");
61
+ log("\n");
62
+ log("\n");
63
+ log(" connect [-nomap] [-assert] -port <cell> <port> <expr> [selection]\n");
64
+ log("\n");
65
+ log("Connect the specified cell port to the specified cell port.\n");
66
+ log("\n");
67
+ log("\n");
68
+ log("Per default signal alias names are resolved and all signal names are mapped\n");
69
+ log("the the signal name of the primary driver. Using the -nomap option deactivates\n");
70
+ log("this behavior.\n");
71
+ log("\n");
72
+ log("The connect command operates in one module only. Either only one module must\n");
73
+ log("be selected or an active module must be set using the 'cd' command.\n");
74
+ log("\n");
75
+ log("The -assert option verifies that the connection already exists, instead of\n");
76
+ log("making it.\n");
77
+ log("\n");
78
+ log("This command does not operate on module with processes.\n");
79
+ log("\n");
80
+ }
81
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
82
+ {
83
+ bool flag_nounset = false, flag_nomap = false, flag_assert = false;
84
+ std::string set_lhs, set_rhs, unset_expr;
85
+ std::string port_cell, port_port, port_expr;
86
+
87
+ size_t argidx;
88
+ for (argidx = 1; argidx < args.size(); argidx++)
89
+ {
90
+ std::string arg = args[argidx];
91
+ if (arg == "-nounset") {
92
+ flag_nounset = true;
93
+ continue;
94
+ }
95
+ if (arg == "-nomap") {
96
+ flag_nomap = true;
97
+ continue;
98
+ }
99
+ if (arg == "-assert") {
100
+ flag_assert = true;
101
+ continue;
102
+ }
103
+ if (arg == "-set" && argidx+2 < args.size()) {
104
+ set_lhs = args[++argidx];
105
+ set_rhs = args[++argidx];
106
+ continue;
107
+ }
108
+ if (arg == "-unset" && argidx+1 < args.size()) {
109
+ unset_expr = args[++argidx];
110
+ continue;
111
+ }
112
+ if (arg == "-port" && argidx+3 < args.size()) {
113
+ port_cell = args[++argidx];
114
+ port_port = args[++argidx];
115
+ port_expr = args[++argidx];
116
+ continue;
117
+ }
118
+ break;
119
+ }
120
+ extra_args(args, argidx, design);
121
+
122
+ RTLIL::Module *module = nullptr;
123
+ for (auto mod : design->selected_modules()) {
124
+ if (module != nullptr)
125
+ log_cmd_error("Multiple modules selected: %s, %s\n", module, mod);
126
+ module = mod;
127
+ }
128
+ if (module == nullptr)
129
+ log_cmd_error("No modules selected.\n");
130
+ if (!module->processes.empty())
131
+ log_cmd_error("Found processes in selected module.\n");
132
+
133
+ SigMap sigmap;
134
+ if (!flag_nomap)
135
+ for (auto &it : module->connections()) {
136
+ std::vector<RTLIL::SigBit> lhs = it.first.to_sigbit_vector();
137
+ std::vector<RTLIL::SigBit> rhs = it.second.to_sigbit_vector();
138
+ for (size_t i = 0; i < lhs.size(); i++)
139
+ if (rhs[i].wire != nullptr)
140
+ sigmap.add(lhs[i], rhs[i]);
141
+ }
142
+
143
+ if (!set_lhs.empty())
144
+ {
145
+ if (!unset_expr.empty() || !port_cell.empty())
146
+ log_cmd_error("Can't use -set together with -unset and/or -port.\n");
147
+
148
+ if (flag_assert)
149
+ log_cmd_error("The -assert option is only supported with -port.\n");
150
+
151
+ RTLIL::SigSpec sig_lhs, sig_rhs;
152
+ if (!RTLIL::SigSpec::parse_sel(sig_lhs, design, module, set_lhs))
153
+ log_cmd_error("Failed to parse set lhs expression `%s'.\n", set_lhs);
154
+ if (!RTLIL::SigSpec::parse_rhs(sig_lhs, sig_rhs, module, set_rhs))
155
+ log_cmd_error("Failed to parse set rhs expression `%s'.\n", set_rhs);
156
+
157
+ sigmap.apply(sig_lhs);
158
+ sigmap.apply(sig_rhs);
159
+
160
+ if (!flag_nounset)
161
+ unset_drivers(design, module, sigmap, sig_lhs);
162
+
163
+ module->connect(RTLIL::SigSig(sig_lhs, sig_rhs));
164
+ }
165
+ else
166
+ if (!unset_expr.empty())
167
+ {
168
+ if (!port_cell.empty() || flag_nounset)
169
+ log_cmd_error("Can't use -unset together with -port and/or -nounset.\n");
170
+
171
+ if (flag_assert)
172
+ log_cmd_error("The -assert option is only supported with -port.\n");
173
+
174
+ RTLIL::SigSpec sig;
175
+ if (!RTLIL::SigSpec::parse_sel(sig, design, module, unset_expr))
176
+ log_cmd_error("Failed to parse unset expression `%s'.\n", unset_expr);
177
+
178
+ sigmap.apply(sig);
179
+ unset_drivers(design, module, sigmap, sig);
180
+ }
181
+ else
182
+ if (!port_cell.empty())
183
+ {
184
+ if (flag_nounset)
185
+ log_cmd_error("Can't use -port together with -nounset.\n");
186
+
187
+ RTLIL::Cell *port_cell_obj = module->cell(RTLIL::escape_id(port_cell));
188
+ if (port_cell_obj == nullptr)
189
+ log_cmd_error("Can't find cell %s.\n", port_cell);
190
+
191
+ RTLIL::SigSpec sig;
192
+ if (!RTLIL::SigSpec::parse_sel(sig, design, module, port_expr))
193
+ log_cmd_error("Failed to parse port expression `%s'.\n", port_expr);
194
+
195
+ IdString port_port_ref = module->twines().add(RTLIL::escape_id(port_port));
196
+ if (!flag_assert) {
197
+ port_cell_obj->setPort(port_port_ref, sigmap(sig));
198
+ } else {
199
+ SigSpec cur = port_cell_obj->getPort(port_port_ref);
200
+ if (sigmap(sig) != sigmap(cur)) {
201
+ log_cmd_error("Expected connection not present: expected %s, found %s.\n", log_signal(sig), log_signal(cur));
202
+ }
203
+ }
204
+ }
205
+ else
206
+ log_cmd_error("Expected -set, -unset, or -port.\n");
207
+ }
208
+ } ConnectPass;
209
+
210
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/connwrappers.cc ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/rtlil.h"
23
+ #include "kernel/log.h"
24
+
25
+ USING_YOSYS_NAMESPACE
26
+ PRIVATE_NAMESPACE_BEGIN
27
+
28
+ struct ConnwrappersWorker
29
+ {
30
+ struct portdecl_t {
31
+ // key: celltype, portname;
32
+ std::string widthparam, signparam;
33
+ bool is_signed;
34
+ };
35
+
36
+ std::set<std::string> decl_celltypes;
37
+ std::map<std::pair<std::string, std::string>, portdecl_t> decls;
38
+
39
+ void add_port(std::string celltype, std::string portname, std::string widthparam, std::string signparam)
40
+ {
41
+ std::pair<std::string, std::string> key(RTLIL::escape_id(celltype), RTLIL::escape_id(portname));
42
+ decl_celltypes.insert(key.first);
43
+
44
+ if (decls.count(key))
45
+ log_cmd_error("Duplicate port decl: %s %s\n", celltype, portname);
46
+
47
+ portdecl_t decl;
48
+ decl.widthparam = RTLIL::escape_id(widthparam);
49
+ decl.signparam = RTLIL::escape_id(signparam);
50
+ decl.is_signed = false;
51
+ decls[key] = decl;
52
+ }
53
+
54
+ void add_port(std::string celltype, std::string portname, std::string widthparam, bool is_signed)
55
+ {
56
+ std::pair<std::string, std::string> key(RTLIL::escape_id(celltype), RTLIL::escape_id(portname));
57
+ decl_celltypes.insert(key.first);
58
+
59
+ if (decls.count(key))
60
+ log_cmd_error("Duplicate port decl: %s %s\n", celltype, portname);
61
+
62
+ portdecl_t decl;
63
+ decl.widthparam = RTLIL::escape_id(widthparam);
64
+ decl.is_signed = is_signed;
65
+ decls[key] = decl;
66
+ }
67
+
68
+ void work(RTLIL::Module *module)
69
+ {
70
+ std::map<RTLIL::SigBit, std::pair<bool, RTLIL::SigSpec>> extend_map;
71
+ SigMap sigmap(module);
72
+
73
+ for (auto cell : module->cells())
74
+ {
75
+ if (!decl_celltypes.count(cell->type))
76
+ continue;
77
+
78
+ for (auto &conn : cell->connections())
79
+ {
80
+ std::pair<std::string, std::string> key(cell->type, module->twines().str(conn.first));
81
+
82
+ if (!decls.count(key))
83
+ continue;
84
+
85
+ portdecl_t &decl = decls.at(key);
86
+
87
+ IdString widthparam = module->twines().find(decl.widthparam);
88
+ if (widthparam == IdString::Null || !cell->parameters.count(widthparam))
89
+ continue;
90
+
91
+ IdString signparam = decl.signparam.empty() ? IdString::Null : module->twines().find(decl.signparam);
92
+ if (!decl.signparam.empty() && (signparam == IdString::Null || !cell->parameters.count(signparam)))
93
+ continue;
94
+
95
+ int inner_width = cell->parameters.at(widthparam).as_int();
96
+ int outer_width = conn.second.size();
97
+ bool is_signed = decl.signparam.empty() ? decl.is_signed : cell->parameters.at(signparam).as_bool();
98
+
99
+ if (inner_width >= outer_width)
100
+ continue;
101
+
102
+ RTLIL::SigSpec sig = sigmap(conn.second);
103
+ extend_map[sig.extract(inner_width - 1, 1)] = std::pair<bool, RTLIL::SigSpec>(is_signed,
104
+ sig.extract(inner_width, outer_width - inner_width));
105
+ }
106
+ }
107
+
108
+ for (auto cell : module->selected_cells())
109
+ {
110
+ for (auto &conn : cell->connections_)
111
+ {
112
+ std::vector<RTLIL::SigBit> sigbits = sigmap(conn.second).to_sigbit_vector();
113
+ RTLIL::SigSpec old_sig;
114
+
115
+ for (size_t i = 0; i < sigbits.size(); i++)
116
+ {
117
+ if (!extend_map.count(sigbits[i]))
118
+ continue;
119
+
120
+ bool is_signed = extend_map.at(sigbits[i]).first;
121
+ RTLIL::SigSpec extend_sig = extend_map.at(sigbits[i]).second;
122
+
123
+ int extend_width = 0;
124
+ RTLIL::SigBit extend_bit = is_signed ? sigbits[i] : RTLIL::SigBit(RTLIL::State::S0);
125
+ while (extend_width < extend_sig.size() && i + extend_width + 1 < sigbits.size() &&
126
+ sigbits[i + extend_width + 1] == extend_bit) extend_width++;
127
+
128
+ if (extend_width == 0)
129
+ continue;
130
+
131
+ if (old_sig.size() == 0)
132
+ old_sig = conn.second;
133
+
134
+ conn.second.replace(i+1, extend_sig.extract(0, extend_width));
135
+ i += extend_width;
136
+ }
137
+
138
+ if (old_sig.size())
139
+ log("Connected extended bits of %s.%s:%s: %s -> %s\n", module, cell,
140
+ PooledName(module, conn.first).unescape(), log_signal(old_sig), log_signal(conn.second));
141
+ }
142
+ }
143
+ }
144
+ };
145
+
146
+ struct ConnwrappersPass : public Pass {
147
+ ConnwrappersPass() : Pass("connwrappers", "match width of input-output port pairs") { }
148
+ void help() override
149
+ {
150
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
151
+ log("\n");
152
+ log(" connwrappers [options] [selection]\n");
153
+ log("\n");
154
+ log("Wrappers are used in coarse-grain synthesis to wrap cells with smaller ports\n");
155
+ log("in wrapper cells with a (larger) constant port size. I.e. the upper bits\n");
156
+ log("of the wrapper output are signed/unsigned bit extended. This command uses this\n");
157
+ log("knowledge to rewire the inputs of the driven cells to match the output of\n");
158
+ log("the driving cell.\n");
159
+ log("\n");
160
+ log(" -signed <cell_type> <port_name> <width_param>\n");
161
+ log(" -unsigned <cell_type> <port_name> <width_param>\n");
162
+ log(" consider the specified signed/unsigned wrapper output\n");
163
+ log("\n");
164
+ log(" -port <cell_type> <port_name> <width_param> <sign_param>\n");
165
+ log(" use the specified parameter to decide if signed or unsigned\n");
166
+ log("\n");
167
+ log("The options -signed, -unsigned, and -port can be specified multiple times.\n");
168
+ log("\n");
169
+ }
170
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
171
+ {
172
+ ConnwrappersWorker worker;
173
+
174
+ size_t argidx;
175
+ for (argidx = 1; argidx < args.size(); argidx++)
176
+ {
177
+ if (args[argidx] == "-signed" && argidx+3 < args.size()) {
178
+ worker.add_port(args[argidx+1], args[argidx+2], args[argidx+3], true);
179
+ argidx += 3;
180
+ continue;
181
+ }
182
+ if (args[argidx] == "-unsigned" && argidx+3 < args.size()) {
183
+ worker.add_port(args[argidx+1], args[argidx+2], args[argidx+3], false);
184
+ argidx += 3;
185
+ continue;
186
+ }
187
+ if (args[argidx] == "-port" && argidx+4 < args.size()) {
188
+ worker.add_port(args[argidx+1], args[argidx+2], args[argidx+3], args[argidx+4]);
189
+ argidx += 4;
190
+ continue;
191
+ }
192
+ break;
193
+ }
194
+ extra_args(args, argidx, design);
195
+
196
+ log_header(design, "Executing CONNWRAPPERS pass (connect extended ports of wrapper cells).\n");
197
+
198
+ for (auto module : design->selected_modules())
199
+ worker.work(module);
200
+ }
201
+ } ConnwrappersPass;
202
+
203
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/copy.cc ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/rtlil.h"
22
+ #include "kernel/log.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct CopyPass : public Pass {
28
+ CopyPass() : Pass("copy", "copy modules in the design") { }
29
+ void help() override
30
+ {
31
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
32
+ log("\n");
33
+ log(" copy old_name new_name\n");
34
+ log("\n");
35
+ log("Copy the specified module. Note that selection patterns are not supported\n");
36
+ log("by this command.\n");
37
+ log("\n");
38
+ }
39
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
40
+ {
41
+ if (args.size() != 3)
42
+ log_cmd_error("Invalid number of arguments!\n");
43
+
44
+ std::string src_name = RTLIL::escape_id(args[1]);
45
+ std::string trg_name = RTLIL::escape_id(args[2]);
46
+
47
+ IdString src_ref = design->twines().find(src_name);
48
+ if (design->module(src_ref) == nullptr)
49
+ log_cmd_error("Can't find source module %s.\n", src_name);
50
+
51
+ if (design->module(trg_name) != nullptr)
52
+ log_cmd_error("Target module name %s already exists.\n", trg_name);
53
+
54
+ design->module(src_ref)->clone(design, design->twines().add(trg_name));
55
+ }
56
+ } CopyPass;
57
+
58
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/delete.cc ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+
22
+ USING_YOSYS_NAMESPACE
23
+ PRIVATE_NAMESPACE_BEGIN
24
+
25
+ struct DeletePass : public Pass {
26
+ DeletePass() : Pass("delete", "delete objects in the design") { }
27
+ void help() override
28
+ {
29
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
30
+ log("\n");
31
+ log(" delete [selection]\n");
32
+ log("\n");
33
+ log("Deletes the selected objects. This will also remove entire modules, if the\n");
34
+ log("whole module is selected.\n");
35
+ log("\n");
36
+ log("\n");
37
+ log(" delete {-input|-output|-port} [selection]\n");
38
+ log("\n");
39
+ log("Does not delete any object but removes the input and/or output flag on the\n");
40
+ log("selected wires, thus 'deleting' module ports.\n");
41
+ log("\n");
42
+ }
43
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
44
+ {
45
+ bool flag_input = false;
46
+ bool flag_output = false;
47
+
48
+ size_t argidx;
49
+ for (argidx = 1; argidx < args.size(); argidx++)
50
+ {
51
+ if (args[argidx] == "-input") {
52
+ flag_input = true;
53
+ continue;
54
+ }
55
+ if (args[argidx] == "-output") {
56
+ flag_output = true;
57
+ continue;
58
+ }
59
+ if (args[argidx] == "-port") {
60
+ flag_input = true;
61
+ flag_output = true;
62
+ continue;
63
+ }
64
+ break;
65
+ }
66
+ extra_args(args, argidx, design);
67
+
68
+ std::vector<RTLIL::Module *> delete_mods;
69
+ for (auto module : design->modules())
70
+ {
71
+ if (design->selected_whole_module(module->name) && !flag_input && !flag_output) {
72
+ delete_mods.push_back(module);
73
+ continue;
74
+ }
75
+
76
+ if (!design->selected_module(module->name))
77
+ continue;
78
+
79
+ if (flag_input || flag_output) {
80
+ for (auto wire : module->wires())
81
+ if (design->selected(module, wire)) {
82
+ if (flag_input)
83
+ wire->port_input = false;
84
+ if (flag_output)
85
+ wire->port_output = false;
86
+ }
87
+ module->fixup_ports();
88
+ continue;
89
+ }
90
+
91
+ pool<RTLIL::Wire*> delete_wires;
92
+ pool<RTLIL::Cell*> delete_cells;
93
+ pool<RTLIL::Process*> delete_procs;
94
+ dict<std::string, RTLIL::IdString> delete_mems;
95
+
96
+ for (auto wire : module->selected_wires())
97
+ delete_wires.insert(wire);
98
+
99
+ for (auto &it : module->memories)
100
+ if (design->selected(module, it.second))
101
+ delete_mems[design->twines().str(it.first)] = it.first;
102
+
103
+ for (auto cell : module->cells()) {
104
+ if (design->selected(module, cell))
105
+ delete_cells.insert(cell);
106
+ if (cell->has_memid() &&
107
+ delete_mems.count(cell->parameters.at(ID::MEMID).decode_string()) != 0)
108
+ delete_cells.insert(cell);
109
+ }
110
+
111
+ for (auto &it : module->processes)
112
+ if (design->selected(module, it.second))
113
+ delete_procs.insert(it.second);
114
+
115
+ for (auto &it : delete_mems) {
116
+ delete module->memories.at(it.second);
117
+ module->memories.erase(it.second);
118
+ }
119
+
120
+ for (auto &it : delete_cells)
121
+ module->remove(it);
122
+
123
+ for (auto &it : delete_procs)
124
+ module->remove(it);
125
+
126
+ module->remove(delete_wires);
127
+
128
+ module->fixup_ports();
129
+ }
130
+
131
+ for (auto mod : delete_mods) {
132
+ design->remove(mod);
133
+ }
134
+ }
135
+ } DeletePass;
136
+
137
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/design.cc ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "frontends/verilog/preproc.h"
22
+ #include "frontends/ast/ast.h"
23
+
24
+ YOSYS_NAMESPACE_BEGIN
25
+
26
+ std::map<std::string, std::shared_ptr<RTLIL::Design>> saved_designs;
27
+ std::vector<std::shared_ptr<RTLIL::Design>> pushed_designs;
28
+
29
+ static std::shared_ptr<RTLIL::Design> snapshot(RTLIL::Design *design)
30
+ {
31
+ auto copy = std::make_shared<RTLIL::Design>();
32
+ design->clone_into(copy.get());
33
+ return copy;
34
+ }
35
+
36
+ static void copy_modules(RTLIL::Design *dst, const std::vector<RTLIL::Module*> &modules, const std::string &as_name)
37
+ {
38
+ if (!as_name.empty() && modules.size() > 1)
39
+ log_cmd_error("Only one module can be selected in combination with -as.\n");
40
+
41
+ for (auto mod : modules)
42
+ {
43
+ std::string trg_name = as_name.empty() ? mod->name.str() : RTLIL::escape_id(as_name);
44
+ IdString trg_ref = dst->twines().add(trg_name);
45
+
46
+ if (dst->module(trg_ref) != nullptr)
47
+ dst->remove(dst->module(trg_ref));
48
+
49
+ mod->clone(dst, trg_ref);
50
+ }
51
+ }
52
+
53
+ static void import_design(RTLIL::Design *src, RTLIL::Design *dst, std::vector<RTLIL::Module*> modules,
54
+ const std::string &as_name)
55
+ {
56
+ std::vector<RTLIL::Module*> candidates;
57
+ for (auto module : modules)
58
+ {
59
+ if (module->get_bool_attribute(ID::top)) {
60
+ candidates.clear();
61
+ candidates.push_back(module);
62
+ break;
63
+ }
64
+ if (!module->get_blackbox_attribute())
65
+ candidates.push_back(module);
66
+ }
67
+
68
+ if (GetSize(candidates) == 1)
69
+ modules = std::move(candidates);
70
+
71
+ std::string prefix = RTLIL::escape_id(as_name);
72
+ IdString as_name_ref = dst->twines().add(prefix);
73
+
74
+ pool<Module*> queue;
75
+ dict<IdString, IdString> done;
76
+
77
+ if (dst->module(as_name_ref) != nullptr)
78
+ dst->remove(dst->module(as_name_ref));
79
+
80
+ if (GetSize(modules) != 1)
81
+ log_cmd_error("No top module found in source design.\n");
82
+
83
+ for (auto mod : modules)
84
+ {
85
+ log("Importing %s as %s.\n", mod, PooledName(dst, as_name_ref).unescape());
86
+
87
+ RTLIL::Module *t = mod->clone(dst, as_name_ref);
88
+ t->attributes.erase(ID::top);
89
+
90
+ queue.insert(t);
91
+ done[mod->name] = as_name_ref;
92
+ }
93
+
94
+ while (!queue.empty())
95
+ {
96
+ pool<Module*> old_queue;
97
+ old_queue.swap(queue);
98
+
99
+ for (auto mod : old_queue)
100
+ for (auto cell : mod->cells())
101
+ {
102
+ Module *fmod = src->module(src->twines().find(dst->twines().str(cell->type)));
103
+
104
+ if (fmod == nullptr)
105
+ continue;
106
+
107
+ if (done.count(cell->type) == 0)
108
+ {
109
+ IdString trg_ref = dst->twines().add(
110
+ TwineSpec::Suffix{as_name_ref, "." + cell->type.unescape()});
111
+
112
+ log("Importing %s as %s.\n", fmod, PooledName(dst, trg_ref).unescape());
113
+
114
+ if (dst->module(trg_ref) != nullptr)
115
+ dst->remove(dst->module(trg_ref));
116
+
117
+ RTLIL::Module *t = fmod->clone(dst, trg_ref);
118
+ t->attributes.erase(ID::top);
119
+
120
+ queue.insert(t);
121
+ done[cell->type] = trg_ref;
122
+ }
123
+
124
+ cell->type = done.at(cell->type);
125
+ }
126
+ }
127
+ }
128
+
129
+ struct DesignPass : public Pass {
130
+ DesignPass() : Pass("design", "save, restore and reset current design") { }
131
+ void on_shutdown() override {
132
+ saved_designs.clear();
133
+ pushed_designs.clear();
134
+ }
135
+ void help() override
136
+ {
137
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
138
+ log("\n");
139
+ log(" design -reset\n");
140
+ log("\n");
141
+ log("Clear the current design. This also restarts the numbering of generated\n");
142
+ log("names.\n");
143
+ log("\n");
144
+ log("\n");
145
+ log(" design -save <name>\n");
146
+ log("\n");
147
+ log("Save the current design under the given name.\n");
148
+ log("\n");
149
+ log("\n");
150
+ log(" design -stash <name>\n");
151
+ log("\n");
152
+ log("Save the current design under the given name and then clear the current design.\n");
153
+ log("\n");
154
+ log("\n");
155
+ log(" design -push\n");
156
+ log("\n");
157
+ log("Push the current design to the stack and then clear the current design.\n");
158
+ log("\n");
159
+ log("\n");
160
+ log(" design -push-copy\n");
161
+ log("\n");
162
+ log("Push the current design to the stack without clearing the current design.\n");
163
+ log("\n");
164
+ log("\n");
165
+ log(" design -pop\n");
166
+ log("\n");
167
+ log("Reset the current design and pop the last design from the stack.\n");
168
+ log("\n");
169
+ log("\n");
170
+ log(" design -load <name>\n");
171
+ log("\n");
172
+ log("Reset the current design and load the design previously saved under the given\n");
173
+ log("name.\n");
174
+ log("\n");
175
+ log("\n");
176
+ log(" design -copy-from <name> [-as <new_mod_name>] <selection>\n");
177
+ log("\n");
178
+ log("Copy modules from the specified design into the current one. The selection is\n");
179
+ log("evaluated in the other design.\n");
180
+ log("\n");
181
+ log("\n");
182
+ log(" design -copy-to <name> [-as <new_mod_name>] [selection]\n");
183
+ log("\n");
184
+ log("Copy modules from the current design into the specified one.\n");
185
+ log("\n");
186
+ log("\n");
187
+ log(" design -import <name> [-as <new_top_name>] [selection]\n");
188
+ log("\n");
189
+ log("Import the specified design into the current design. The source design must\n");
190
+ log("either have a selected top module or the selection must contain exactly one\n");
191
+ log("module that is then used as top module for this command.\n");
192
+ log("\n");
193
+ log("\n");
194
+ log(" design -reset-vlog\n");
195
+ log("\n");
196
+ log("The Verilog front-end remembers defined macros and top-level declarations\n");
197
+ log("between calls to 'read_verilog'. This command resets this memory.\n");
198
+ log("\n");
199
+ log(" design -delete <name>\n");
200
+ log("\n");
201
+ log("Delete the design previously saved under the given name.\n");
202
+ log("\n");
203
+
204
+ }
205
+ enum class Mode { None, Reset, ResetVlog, Push, PushCopy, Pop, Save, Stash, Load, CopyFrom, CopyTo, Import, Delete };
206
+
207
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
208
+ {
209
+ static const std::map<std::string, Mode> flag_modes = {
210
+ {"-reset", Mode::Reset}, {"-reset-vlog", Mode::ResetVlog},
211
+ {"-push", Mode::Push}, {"-push-copy", Mode::PushCopy}, {"-pop", Mode::Pop},
212
+ };
213
+ static const std::map<std::string, Mode> named_modes = {
214
+ {"-save", Mode::Save}, {"-stash", Mode::Stash}, {"-load", Mode::Load},
215
+ {"-copy-from", Mode::CopyFrom}, {"-copy-to", Mode::CopyTo},
216
+ {"-import", Mode::Import}, {"-delete", Mode::Delete},
217
+ };
218
+
219
+ Mode mode = Mode::None;
220
+ std::string name, as_name;
221
+
222
+ if (!design)
223
+ log_cmd_error("No default design.\n");
224
+
225
+ size_t argidx;
226
+ for (argidx = 1; argidx < args.size(); argidx++)
227
+ {
228
+ const std::string &arg = args[argidx];
229
+ bool has_value = argidx+1 < args.size();
230
+ if (mode == Mode::None && flag_modes.count(arg)) {
231
+ mode = flag_modes.at(arg);
232
+ continue;
233
+ }
234
+ if (mode == Mode::None && named_modes.count(arg) && has_value) {
235
+ mode = named_modes.at(arg);
236
+ name = args[++argidx];
237
+ continue;
238
+ }
239
+ bool copying = mode == Mode::CopyFrom || mode == Mode::CopyTo || mode == Mode::Import;
240
+ if (copying && arg == "-as" && has_value) {
241
+ as_name = args[++argidx];
242
+ continue;
243
+ }
244
+ break;
245
+ }
246
+
247
+ bool reads_saved = mode == Mode::Load || mode == Mode::CopyFrom || mode == Mode::Import || mode == Mode::Delete;
248
+ if (reads_saved && saved_designs.count(name) == 0)
249
+ log_cmd_error("No saved design '%s' found!\n", name);
250
+
251
+ RTLIL::Design *copy_from_design = nullptr, *copy_to_design = nullptr;
252
+ if (mode == Mode::CopyFrom || mode == Mode::Import) {
253
+ copy_from_design = saved_designs.at(name).get();
254
+ copy_to_design = design;
255
+ }
256
+ if (mode == Mode::CopyTo) {
257
+ auto &saved = saved_designs[name];
258
+ if (!saved)
259
+ saved = std::make_shared<RTLIL::Design>();
260
+ copy_from_design = design;
261
+ copy_to_design = saved.get();
262
+ }
263
+ if (mode == Mode::Import && as_name.empty())
264
+ as_name = name;
265
+
266
+ std::vector<RTLIL::Module*> copy_src_modules;
267
+ if (copy_from_design != nullptr)
268
+ {
269
+ if (copy_from_design != design && argidx == args.size() && mode != Mode::Import)
270
+ cmd_error(args, argidx, "Missing selection.");
271
+
272
+ if (argidx != args.size()) {
273
+ handle_extra_select_args(this, args, argidx, args.size(), copy_from_design);
274
+ argidx = args.size();
275
+ } else {
276
+ copy_from_design->push_complete_selection();
277
+ }
278
+
279
+ for (auto mod : copy_from_design->selected_modules(RTLIL::SELECT_WHOLE_CMDERR, RTLIL::SB_ALL))
280
+ copy_src_modules.push_back(mod);
281
+
282
+ copy_from_design->pop_selection();
283
+ }
284
+
285
+ extra_args(args, argidx, design, false);
286
+
287
+ if (mode == Mode::None)
288
+ cmd_error(args, argidx, "Missing mode argument.");
289
+
290
+ if (mode == Mode::Pop && pushed_designs.empty())
291
+ log_cmd_error("No pushed designs.\n");
292
+
293
+ switch (mode) {
294
+ case Mode::Reset:
295
+ design->reset();
296
+ break;
297
+ case Mode::ResetVlog:
298
+ design->reset_verilog_state();
299
+ break;
300
+ case Mode::Push:
301
+ pushed_designs.push_back(snapshot(design));
302
+ design->reset();
303
+ break;
304
+ case Mode::PushCopy:
305
+ pushed_designs.push_back(snapshot(design));
306
+ break;
307
+ case Mode::Pop:
308
+ design->reset();
309
+ pushed_designs.back()->clone_into(design);
310
+ pushed_designs.pop_back();
311
+ break;
312
+ case Mode::Save:
313
+ saved_designs[name] = snapshot(design);
314
+ break;
315
+ case Mode::Stash:
316
+ saved_designs[name] = snapshot(design);
317
+ design->reset();
318
+ break;
319
+ case Mode::Load:
320
+ design->reset();
321
+ saved_designs.at(name)->clone_into(design);
322
+ break;
323
+ case Mode::CopyFrom:
324
+ case Mode::CopyTo:
325
+ copy_modules(copy_to_design, copy_src_modules, as_name);
326
+ break;
327
+ case Mode::Import:
328
+ import_design(copy_from_design, copy_to_design, copy_src_modules, as_name);
329
+ break;
330
+ case Mode::Delete:
331
+ saved_designs.erase(name);
332
+ break;
333
+ case Mode::None:
334
+ log_abort();
335
+ }
336
+ }
337
+ } DesignPass;
338
+
339
+ YOSYS_NAMESPACE_END
chips/yosys/passes/cmds/design_equal.cc ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/rtlil.h"
22
+
23
+ YOSYS_NAMESPACE_BEGIN
24
+
25
+ class PoolBridge
26
+ {
27
+ const TwinePool *pool_a;
28
+ const TwinePool *pool_b;
29
+
30
+ public:
31
+ PoolBridge(RTLIL::Design *design_a, RTLIL::Design *design_b) :
32
+ pool_a(&design_a->twines()), pool_b(&design_b->twines()) {}
33
+
34
+ IdString a_to_b(IdString ref) const { return pool_b->find_from(*pool_a, ref); }
35
+ IdString b_to_a(IdString ref) const { return pool_a->find_from(*pool_b, ref); }
36
+
37
+ bool same(IdString a, IdString b) const { return pool_a->str(a) == pool_b->str(b); }
38
+ };
39
+
40
+ class ModuleComparator
41
+ {
42
+ RTLIL::Module *mod_a;
43
+ RTLIL::Module *mod_b;
44
+ const PoolBridge &bridge;
45
+
46
+ public:
47
+ ModuleComparator(RTLIL::Module *mod_a, RTLIL::Module *mod_b, const PoolBridge &bridge) :
48
+ mod_a(mod_a), mod_b(mod_b), bridge(bridge) {}
49
+
50
+ template <typename... Args>
51
+ [[noreturn]] void error(FmtString<TypeIdentity<Args>...> fmt, const Args &... args)
52
+ {
53
+ formatted_error(fmt.format(args...));
54
+ }
55
+ [[noreturn]]
56
+ void formatted_error(std::string err)
57
+ {
58
+ log("Module A: %s\n", mod_a);
59
+ log_module(mod_a, " ");
60
+ log("Module B: %s\n", mod_b);
61
+ log_module(mod_b, " ");
62
+ log_cmd_error("Designs are different: %s\n", err);
63
+ }
64
+
65
+ bool compare_sigbit(const RTLIL::SigBit &a, const RTLIL::SigBit &b)
66
+ {
67
+ if (a.wire == nullptr && b.wire == nullptr)
68
+ return a.data == b.data;
69
+ if (a.wire != nullptr && b.wire != nullptr)
70
+ return bridge.same(a.wire->name, b.wire->name) && a.offset == b.offset;
71
+ return false;
72
+ }
73
+
74
+ bool compare_sigspec(const RTLIL::SigSpec &a, const RTLIL::SigSpec &b)
75
+ {
76
+ if (a.size() != b.size()) return false;
77
+ auto it_a = a.begin(), it_b = b.begin();
78
+ for (; it_a != a.end(); ++it_a, ++it_b) {
79
+ if (!compare_sigbit(*it_a, *it_b)) return false;
80
+ }
81
+ return true;
82
+ }
83
+
84
+ std::string compare_attributes(const RTLIL::AttrObject *a, const RTLIL::AttrObject *b)
85
+ {
86
+ for (const auto &it : a->attributes) {
87
+ IdString in_b = bridge.a_to_b(it.first);
88
+ if (b->attributes.count(in_b) == 0)
89
+ return "missing attribute " + std::string(mod_a->twines().unescaped_str(it.first)) + " in second design";
90
+ if (it.second != b->attributes.at(in_b))
91
+ return "attribute " + std::string(mod_a->twines().unescaped_str(it.first)) + " mismatch: " + log_const(it.second) + " != " + log_const(b->attributes.at(in_b));
92
+ }
93
+ for (const auto &it : b->attributes)
94
+ if (a->attributes.count(bridge.b_to_a(it.first)) == 0)
95
+ return "missing attribute " + std::string(mod_b->twines().unescaped_str(it.first)) + " in first design";
96
+ return "";
97
+ }
98
+
99
+ std::string compare_wires(const RTLIL::Wire *a, const RTLIL::Wire *b)
100
+ {
101
+ if (!bridge.same(a->name, b->name))
102
+ return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape();
103
+ if (a->width != b->width)
104
+ return "width mismatch: " + std::to_string(a->width) + " != " + std::to_string(b->width);
105
+ if (a->start_offset != b->start_offset)
106
+ return "start_offset mismatch: " + std::to_string(a->start_offset) + " != " + std::to_string(b->start_offset);
107
+ if (a->port_id != b->port_id)
108
+ return "port_id mismatch: " + std::to_string(a->port_id) + " != " + std::to_string(b->port_id);
109
+ if (a->port_input != b->port_input)
110
+ return "port_input mismatch: " + std::to_string(a->port_input) + " != " + std::to_string(b->port_input);
111
+ if (a->port_output != b->port_output)
112
+ return "port_output mismatch: " + std::to_string(a->port_output) + " != " + std::to_string(b->port_output);
113
+ if (a->upto != b->upto)
114
+ return "upto mismatch: " + std::to_string(a->upto) + " != " + std::to_string(b->upto);
115
+ if (a->is_signed != b->is_signed)
116
+ return "is_signed mismatch: " + std::to_string(a->is_signed) + " != " + std::to_string(b->is_signed);
117
+ if (std::string mismatch = compare_attributes(a, b); !mismatch.empty())
118
+ return mismatch;
119
+ return "";
120
+ }
121
+
122
+ void check_wires()
123
+ {
124
+ for (const auto &it : mod_a->wires_) {
125
+ RTLIL::Wire *wb = mod_b->wire(bridge.a_to_b(it.first));
126
+ if (!wb)
127
+ error("Module %s missing wire %s in second design.\n", mod_a, it.second);
128
+ else if (std::string mismatch = compare_wires(it.second, wb); !mismatch.empty())
129
+ error("Module %s wire %s %s.\n", mod_a, it.second, mismatch);
130
+ }
131
+ for (const auto &it : mod_b->wires_) {
132
+ if (!mod_a->wire(bridge.b_to_a(it.first)))
133
+ error("Module %s missing wire %s in first design.\n", mod_b, it.second);
134
+ }
135
+ }
136
+
137
+ std::string compare_memories(const RTLIL::Memory *a, const RTLIL::Memory *b)
138
+ {
139
+ if (!bridge.same(a->name, b->name))
140
+ return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape();
141
+ if (a->width != b->width)
142
+ return "width mismatch: " + std::to_string(a->width) + " != " + std::to_string(b->width);
143
+ if (a->start_offset != b->start_offset)
144
+ return "start_offset mismatch: " + std::to_string(a->start_offset) + " != " + std::to_string(b->start_offset);
145
+ if (a->size != b->size)
146
+ return "size mismatch: " + std::to_string(a->size) + " != " + std::to_string(b->size);
147
+ if (std::string mismatch = compare_attributes(a, b); !mismatch.empty())
148
+ return mismatch;
149
+ return "";
150
+ }
151
+
152
+ std::string compare_cells(const RTLIL::Cell *a, const RTLIL::Cell *b)
153
+ {
154
+ if (!bridge.same(a->name, b->name))
155
+ return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape();
156
+ if (!bridge.same(a->type, b->type))
157
+ return "type mismatch: " + std::string(a->type.unescape()) + " != " + b->type.unescape();
158
+ if (std::string mismatch = compare_attributes(a, b); !mismatch.empty())
159
+ return mismatch;
160
+
161
+ for (const auto &it : a->parameters) {
162
+ IdString in_b = bridge.a_to_b(it.first);
163
+ if (b->parameters.count(in_b) == 0)
164
+ return "parameter mismatch: missing parameter " + std::string(mod_a->twines().unescaped_str(it.first)) + " in second design";
165
+ if (it.second != b->parameters.at(in_b))
166
+ return "parameter mismatch: " + std::string(mod_a->twines().unescaped_str(it.first)) + " mismatch: " + log_const(it.second) + " != " + log_const(b->parameters.at(in_b));
167
+ }
168
+ for (const auto &it : b->parameters)
169
+ if (a->parameters.count(bridge.b_to_a(it.first)) == 0)
170
+ return "parameter mismatch: missing parameter " + std::string(mod_b->twines().unescaped_str(it.first)) + " in first design";
171
+
172
+ for (const auto &it : a->connections()) {
173
+ IdString in_b = bridge.a_to_b(it.first);
174
+ if (b->connections().count(in_b) == 0)
175
+ return "connection mismatch: missing connection " + a->twines().unescaped_str(it.first) + " in second design";
176
+ if (!compare_sigspec(it.second, b->connections().at(in_b)))
177
+ return "connection " + a->twines().unescaped_str(it.first) + " mismatch: " + log_signal(it.second) + " != " + log_signal(b->connections().at(in_b));
178
+ }
179
+ for (const auto &it : b->connections())
180
+ if (a->connections().count(bridge.b_to_a(it.first)) == 0)
181
+ return "connection mismatch: missing connection " + a->twines().unescaped_str(it.first) + " in first design";
182
+
183
+ return "";
184
+ }
185
+
186
+ void check_cells()
187
+ {
188
+ for (const auto &it : mod_a->cells_) {
189
+ RTLIL::Cell *cb = mod_b->cell(bridge.a_to_b(it.first));
190
+ if (!cb)
191
+ error("Module %s missing cell %s in second design.\n", mod_a, it.second);
192
+ else if (std::string mismatch = compare_cells(it.second, cb); !mismatch.empty())
193
+ error("Module %s cell %s %s.\n", mod_a, it.second, mismatch);
194
+ }
195
+ for (const auto &it : mod_b->cells_) {
196
+ if (!mod_a->cell(bridge.b_to_a(it.first)))
197
+ error("Module %s missing cell %s in first design.\n", mod_b, it.second);
198
+ }
199
+ }
200
+
201
+ void check_memories()
202
+ {
203
+ for (const auto &it : mod_a->memories) {
204
+ IdString in_b = bridge.a_to_b(it.first);
205
+ if (mod_b->memories.count(in_b) == 0)
206
+ error("Module %s missing memory %s in second design.\n", mod_a, it.second);
207
+ if (std::string mismatch = compare_memories(it.second, mod_b->memories.at(in_b)); !mismatch.empty())
208
+ error("Module %s memory %s %s.\n", mod_a, it.second, mismatch);
209
+ }
210
+ for (const auto &it : mod_b->memories)
211
+ if (mod_a->memories.count(bridge.b_to_a(it.first)) == 0)
212
+ error("Module %s missing memory %s in first design.\n", mod_b, it.second);
213
+ }
214
+
215
+ std::string compare_case_rules(const RTLIL::CaseRule *a, const RTLIL::CaseRule *b)
216
+ {
217
+ if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) return mismatch;
218
+
219
+ if (a->compare.size() != b->compare.size())
220
+ return "compare size mismatch: " + std::to_string(a->compare.size()) + " != " + std::to_string(b->compare.size());
221
+ for (size_t i = 0; i < a->compare.size(); i++)
222
+ if (!compare_sigspec(a->compare[i], b->compare[i]))
223
+ return "compare " + std::to_string(i) + " mismatch: " + log_signal(a->compare[i]) + " != " + log_signal(b->compare[i]);
224
+
225
+ if (a->actions.size() != b->actions.size())
226
+ return "actions size mismatch: " + std::to_string(a->actions.size()) + " != " + std::to_string(b->actions.size());
227
+ for (size_t i = 0; i < a->actions.size(); i++) {
228
+ if (!compare_sigspec(a->actions[i].first, b->actions[i].first))
229
+ return "action " + std::to_string(i) + " lhs mismatch: " + log_signal(a->actions[i].first) + " != " + log_signal(b->actions[i].first);
230
+ if (!compare_sigspec(a->actions[i].second, b->actions[i].second))
231
+ return "action " + std::to_string(i) + " rhs mismatch: " + log_signal(a->actions[i].second) + " != " + log_signal(b->actions[i].second);
232
+ }
233
+
234
+ if (a->switches.size() != b->switches.size())
235
+ return "switches size mismatch: " + std::to_string(a->switches.size()) + " != " + std::to_string(b->switches.size());
236
+ for (size_t i = 0; i < a->switches.size(); i++)
237
+ if (std::string mismatch = compare_switch_rules(a->switches[i], b->switches[i]); !mismatch.empty())
238
+ return "switch " + std::to_string(i) + " " + mismatch;
239
+
240
+ return "";
241
+ }
242
+
243
+ std::string compare_switch_rules(const RTLIL::SwitchRule *a, const RTLIL::SwitchRule *b)
244
+ {
245
+ if (std::string mismatch = compare_attributes(a, b); !mismatch.empty())
246
+ return mismatch;
247
+ if (!compare_sigspec(a->signal, b->signal))
248
+ return "signal mismatch: " + log_signal(a->signal) + " != " + log_signal(b->signal);
249
+
250
+ if (a->cases.size() != b->cases.size())
251
+ return "cases size mismatch: " + std::to_string(a->cases.size()) + " != " + std::to_string(b->cases.size());
252
+ for (size_t i = 0; i < a->cases.size(); i++)
253
+ if (std::string mismatch = compare_case_rules(a->cases[i], b->cases[i]); !mismatch.empty())
254
+ return "case " + std::to_string(i) + " " + mismatch;
255
+
256
+ return "";
257
+ }
258
+
259
+ std::string compare_sync_rules(const RTLIL::SyncRule *a, const RTLIL::SyncRule *b)
260
+ {
261
+ if (a->type != b->type)
262
+ return "type mismatch: " + std::to_string(a->type) + " != " + std::to_string(b->type);
263
+ if (!compare_sigspec(a->signal, b->signal))
264
+ return "signal mismatch: " + log_signal(a->signal) + " != " + log_signal(b->signal);
265
+ if (a->actions.size() != b->actions.size())
266
+ return "actions size mismatch: " + std::to_string(a->actions.size()) + " != " + std::to_string(b->actions.size());
267
+ for (size_t i = 0; i < a->actions.size(); i++) {
268
+ if (!compare_sigspec(a->actions[i].first, b->actions[i].first))
269
+ return "action " + std::to_string(i) + " lhs mismatch: " + log_signal(a->actions[i].first) + " != " + log_signal(b->actions[i].first);
270
+ if (!compare_sigspec(a->actions[i].second, b->actions[i].second))
271
+ return "action " + std::to_string(i) + " rhs mismatch: " + log_signal(a->actions[i].second) + " != " + log_signal(b->actions[i].second);
272
+ }
273
+ if (a->mem_write_actions.size() != b->mem_write_actions.size())
274
+ return "mem_write_actions size mismatch: " + std::to_string(a->mem_write_actions.size()) + " != " + std::to_string(b->mem_write_actions.size());
275
+ for (size_t i = 0; i < a->mem_write_actions.size(); i++) {
276
+ const auto &ma = a->mem_write_actions[i];
277
+ const auto &mb = b->mem_write_actions[i];
278
+ if (!bridge.same(ma.memid, mb.memid))
279
+ return "mem_write_actions " + std::to_string(i) + " memid mismatch: " + mod_a->twines().unescaped_str(ma.memid) + " != " + mod_b->twines().unescaped_str(mb.memid);
280
+ if (!compare_sigspec(ma.address, mb.address))
281
+ return "mem_write_actions " + std::to_string(i) + " address mismatch: " + log_signal(ma.address) + " != " + log_signal(mb.address);
282
+ if (!compare_sigspec(ma.data, mb.data))
283
+ return "mem_write_actions " + std::to_string(i) + " data mismatch: " + log_signal(ma.data) + " != " + log_signal(mb.data);
284
+ if (!compare_sigspec(ma.enable, mb.enable))
285
+ return "mem_write_actions " + std::to_string(i) + " enable mismatch: " + log_signal(ma.enable) + " != " + log_signal(mb.enable);
286
+ if (ma.priority_mask != mb.priority_mask)
287
+ return "mem_write_actions " + std::to_string(i) + " priority_mask mismatch: " + log_const(ma.priority_mask) + " != " + log_const(mb.priority_mask);
288
+ if (std::string mismatch = compare_attributes(&ma, &mb); !mismatch.empty())
289
+ return "mem_write_actions " + std::to_string(i) + " " + mismatch;
290
+ }
291
+ return "";
292
+ }
293
+
294
+ std::string compare_processes(const RTLIL::Process *a, const RTLIL::Process *b)
295
+ {
296
+ if (!bridge.same(a->name, b->name)) return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape();
297
+ if (std::string mismatch = compare_attributes(a, b); !mismatch.empty())
298
+ return mismatch;
299
+ if (std::string mismatch = compare_case_rules(&a->root_case, &b->root_case); !mismatch.empty())
300
+ return "case rule " + mismatch;
301
+ if (a->syncs.size() != b->syncs.size())
302
+ return "sync count mismatch: " + std::to_string(a->syncs.size()) + " != " + std::to_string(b->syncs.size());
303
+ for (size_t i = 0; i < a->syncs.size(); i++)
304
+ if (std::string mismatch = compare_sync_rules(a->syncs[i], b->syncs[i]); !mismatch.empty())
305
+ return "sync " + std::to_string(i) + " " + mismatch;
306
+ return "";
307
+ }
308
+
309
+ void check_processes()
310
+ {
311
+ for (auto &it : mod_a->processes) {
312
+ IdString in_b = bridge.a_to_b(it.first);
313
+ if (mod_b->processes.count(in_b) == 0)
314
+ error("Module %s missing process %s in second design.\n", mod_a, it.second);
315
+ if (std::string mismatch = compare_processes(it.second, mod_b->processes.at(in_b)); !mismatch.empty())
316
+ error("Module %s process %s %s.\n", mod_a, it.second, mismatch.c_str());
317
+ }
318
+ for (auto &it : mod_b->processes)
319
+ if (mod_a->processes.count(bridge.b_to_a(it.first)) == 0)
320
+ error("Module %s missing process %s in first design.\n", mod_b, it.second);
321
+ }
322
+
323
+ void check_connections()
324
+ {
325
+ const auto &conns_a = mod_a->connections();
326
+ const auto &conns_b = mod_b->connections();
327
+ if (conns_a.size() != conns_b.size()) {
328
+ error("Module %s connection count differs: %zu != %zu\n", mod_a, conns_a.size(), conns_b.size());
329
+ } else {
330
+ for (size_t i = 0; i < conns_a.size(); i++) {
331
+ if (!compare_sigspec(conns_a[i].first, conns_b[i].first))
332
+ error("Module %s connection %zu LHS %s != %s.\n", mod_a, i, log_signal(conns_a[i].first), log_signal(conns_b[i].first));
333
+ if (!compare_sigspec(conns_a[i].second, conns_b[i].second))
334
+ error("Module %s connection %zu RHS %s != %s.\n", mod_a, i, log_signal(conns_a[i].second), log_signal(conns_b[i].second));
335
+ }
336
+ }
337
+ }
338
+
339
+ void check()
340
+ {
341
+ if (!bridge.same(mod_a->name, mod_b->name))
342
+ error("Modules have different names: %s != %s\n", mod_a, mod_b);
343
+ if (std::string mismatch = compare_attributes(mod_a, mod_b); !mismatch.empty())
344
+ error("Module %s %s.\n", mod_a, mismatch);
345
+ check_wires();
346
+ check_cells();
347
+ check_memories();
348
+ check_connections();
349
+ check_processes();
350
+ }
351
+ };
352
+
353
+ struct DesignEqualPass : public Pass {
354
+ DesignEqualPass() : Pass("design_equal", "check if two designs are the same") { }
355
+ void help() override
356
+ {
357
+ log("\n");
358
+ log(" design_equal <name>\n");
359
+ log("\n");
360
+ log("Compare the current design with the design previously saved under the given\n");
361
+ log("name. Abort with an error if the designs are different.\n");
362
+ log("\n");
363
+ }
364
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
365
+ {
366
+ if (args.size() != 2)
367
+ log_cmd_error("Missing argument.\n");
368
+
369
+ std::string check_name = args[1];
370
+ if (saved_designs.count(check_name) == 0)
371
+ log_cmd_error("No saved design '%s' found!\n", check_name);
372
+
373
+ RTLIL::Design *other = saved_designs.at(check_name).get();
374
+
375
+ PoolBridge bridge(design, other);
376
+
377
+ for (auto &it : design->modules_) {
378
+ RTLIL::Module *mod = it.second;
379
+ RTLIL::Module *other_mod = other->module(bridge.a_to_b(it.first));
380
+ if (!other_mod)
381
+ log_error("Second design missing module %s.\n", mod);
382
+
383
+ ModuleComparator cmp(mod, other_mod, bridge);
384
+ cmp.check();
385
+ }
386
+ for (auto &it : other->modules_) {
387
+ RTLIL::Module *mod = it.second;
388
+ if (!design->has(bridge.b_to_a(it.first)))
389
+ log_error("First design missing module %s.\n", mod);
390
+ }
391
+
392
+ log("Designs are identical.\n");
393
+ }
394
+ } DesignEqualPass;
395
+
396
+ YOSYS_NAMESPACE_END
chips/yosys/passes/cmds/dft_tag.cc ADDED
@@ -0,0 +1,1031 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2022 Jannis Harder <jix@yosyshq.com> <me@jix.one>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/celltypes.h"
21
+ #include "kernel/ff.h"
22
+ #include "kernel/modtools.h"
23
+ #include "kernel/sigtools.h"
24
+ #include "kernel/yosys.h"
25
+ #include "kernel/log_help.h"
26
+ #include <deque>
27
+
28
+ USING_YOSYS_NAMESPACE
29
+ PRIVATE_NAMESPACE_BEGIN
30
+
31
+ struct DftTagOptions {
32
+ bool tag_public = false;
33
+ bool overwrite_only = false;
34
+ };
35
+
36
+ struct DftTagWorker {
37
+ Module *module;
38
+ DftTagOptions options;
39
+ ModWalker modwalker;
40
+ SigMap &sigmap;
41
+ FfInitVals initvals;
42
+
43
+ struct tag_set {
44
+ int index = 0;
45
+
46
+ tag_set(int index = 0) : index(index) {}
47
+
48
+ bool operator<(const tag_set &other) const { return index < other.index; }
49
+ bool operator==(const tag_set &other) const { return index == other.index; }
50
+
51
+ [[nodiscard]] Hasher hash_into(Hasher h) const { h.eat(index); return h; }
52
+
53
+ bool empty() const { return index == 0; }
54
+ };
55
+
56
+ idict<pool<IdString>> tag_sets;
57
+
58
+ pool<IdString> tmp_tag_set;
59
+ dict<std::pair<tag_set, tag_set>, tag_set> tag_set_union_cache;
60
+
61
+ dict<SigBit, tag_set> tagged_signals;
62
+
63
+ dict<IdString, pool<IdString>> tag_groups;
64
+ dict<IdString, IdString> group_of_tag;
65
+ pool<IdString> all_tags;
66
+
67
+ pool<Cell *> pending_cells;
68
+ std::deque<Cell *> pending_cell_queue;
69
+
70
+ dict<std::pair<IdString, SigBit>, SigBit> tag_signals;
71
+
72
+ // Uses SigSpec instead of SigBit so we can use coarse grained cells to combine the individual tags
73
+ dict<std::pair<IdString, SigSpec>, SigSpec> tag_group_signals;
74
+
75
+ pool<Cell *> warned_cells;
76
+
77
+ DftTagWorker(Module *module, DftTagOptions options) :
78
+ module(module), options(options), modwalker(module->design), sigmap(modwalker.sigmap)
79
+ {
80
+ modwalker.setup(module);
81
+ initvals.set(&modwalker.sigmap, module);
82
+ tag_sets(tmp_tag_set);
83
+ }
84
+
85
+ void resolve_overwrites()
86
+ {
87
+ std::vector<Cell *> overwrite_cells;
88
+ std::vector<Cell *> original_cells;
89
+
90
+ bool design_changed = false;
91
+
92
+ for (auto cell : module->cells()) {
93
+ if (cell->type == ID($overwrite_tag))
94
+ overwrite_cells.push_back(cell);
95
+
96
+ if (cell->type == ID($original_tag))
97
+ original_cells.push_back(cell);
98
+ }
99
+
100
+ for (auto cell : overwrite_cells) {
101
+ log_debug("Applying $overwrite_tag %s for signal %s\n", cell, log_signal(cell->getPort(ID::A)));
102
+ SigSpec orig_signal = cell->getPort(ID::A);
103
+ SigSpec interposed_signal = divert_users(orig_signal);
104
+ auto *set_tag_cell = module->addSetTag(NEW_ID, cell->getParam(ID::TAG).decode_string(), orig_signal, cell->getPort(ID::SET), cell->getPort(ID::CLR), interposed_signal);
105
+ modwalker.add_cell(set_tag_cell); // Make sure the next $overwrite_tag sees the new connections
106
+ design_changed = true;
107
+ }
108
+
109
+ for (auto cell : overwrite_cells) {
110
+ module->remove(cell);
111
+ }
112
+ for (auto cell : original_cells) {
113
+ cell->type = ID($get_tag);
114
+ }
115
+
116
+ if (design_changed)
117
+ modwalker.setup(module);
118
+ }
119
+
120
+ SigSpec divert_users(SigSpec signal)
121
+ {
122
+ SigSpec signal_mapped = sigmap(signal);
123
+ signal_mapped.sort_and_unify();
124
+ if (GetSize(signal_mapped) < GetSize(signal))
125
+ log_warning("Detected $overwrite_tag on signal %s which contains repeated bits, this can result in unexpected behavior.\n", log_signal(signal));
126
+ SigSpec new_wire = module->addWire(NEW_ID, GetSize(signal));
127
+ for (int i = 0; i < GetSize(new_wire); ++i)
128
+ divert_users(signal[i], new_wire[i]);
129
+ return new_wire;
130
+ }
131
+
132
+ void divert_users(SigBit driver_bit, SigBit interposed_bit)
133
+ {
134
+ dict<std::pair<Cell *, IdString>, SigSpec> updated_ports;
135
+ // TODO also check module outputs
136
+ auto found = modwalker.signal_consumers.find(driver_bit);
137
+ if (found == modwalker.signal_consumers.end())
138
+ return;
139
+ for (auto &consumer : found->second) {
140
+ if (consumer.cell->type.in(ID($original_tag)))
141
+ continue;
142
+ if (sigmap(consumer.cell->getPort(consumer.port)[consumer.offset]) != driver_bit)
143
+ continue;
144
+ std::pair<Cell *, IdString> key = {consumer.cell, consumer.port};
145
+ auto found_port = updated_ports.find(key);
146
+ if (found_port == updated_ports.end()) {
147
+ updated_ports.emplace(key, consumer.cell->getPort(consumer.port));
148
+ }
149
+ updated_ports[key][consumer.offset] = interposed_bit;
150
+ }
151
+ for (auto &update : updated_ports) {
152
+ update.first.first->setPort(update.first.second, update.second);
153
+ modwalker.add_cell(update.first.first); // Make sure the next $overwrite_tag sees the new connections
154
+ }
155
+ }
156
+
157
+ const pool<IdString> &tag_pool(tag_set set) { return tag_sets[set.index]; }
158
+
159
+ tag_set singleton(IdString tag)
160
+ {
161
+ tmp_tag_set.clear();
162
+ tmp_tag_set.emplace(tag);
163
+ return tag_sets(tmp_tag_set);
164
+ }
165
+
166
+ tag_set merge(tag_set a, tag_set b)
167
+ {
168
+ if (b < a)
169
+ std::swap(a, b);
170
+ if (a.empty() || a == b)
171
+ return b;
172
+ auto found = tag_set_union_cache.find(std::make_pair(a, b));
173
+ if (found == tag_set_union_cache.end()) {
174
+ tmp_tag_set.clear();
175
+ auto &a_tags = tag_pool(a);
176
+ auto &b_tags = tag_pool(b);
177
+ tmp_tag_set.insert(a_tags.begin(), a_tags.end());
178
+ tmp_tag_set.insert(b_tags.begin(), b_tags.end());
179
+ tag_set result = tag_sets(tmp_tag_set);
180
+ tag_set_union_cache.emplace(std::make_pair(a, b), result);
181
+ return result;
182
+ }
183
+ return found->second;
184
+ }
185
+
186
+ tag_set tags(SigBit bit)
187
+ {
188
+ sigmap.apply(bit);
189
+ auto found = tagged_signals.find(bit);
190
+ if (found != tagged_signals.end())
191
+ return found->second;
192
+ return tag_set();
193
+ }
194
+
195
+ tag_set tags(SigSpec sig)
196
+ {
197
+ tag_set result;
198
+ for (auto bit : sig)
199
+ result = merge(result, tags(bit));
200
+ return result;
201
+ }
202
+
203
+ tag_set tags(Cell *cell)
204
+ {
205
+ tag_set result;
206
+ for (auto &conn : cell->connections()) {
207
+ if (cell->input(conn.first))
208
+ result = merge(result, tags(conn.second));
209
+ }
210
+ return result;
211
+ }
212
+
213
+ void add_tags(SigBit bit, tag_set new_tags)
214
+ {
215
+ sigmap.apply(bit);
216
+ auto &tags = tagged_signals[bit];
217
+ tag_set merged_tags = merge(tags, new_tags);
218
+ if (merged_tags == tags)
219
+ return;
220
+ tags = merged_tags;
221
+ auto it = modwalker.signal_consumers.find(bit);
222
+ if (it == modwalker.signal_consumers.end())
223
+ return;
224
+ for (auto &consumer : it->second)
225
+ if (pending_cells.insert(consumer.cell).second)
226
+ pending_cell_queue.push_back(consumer.cell);
227
+ }
228
+
229
+ void add_tags(SigSpec sig, tag_set new_tags)
230
+ {
231
+ for (auto bit : sigmap(sig))
232
+ add_tags(bit, new_tags);
233
+ }
234
+
235
+ void add_tags(Cell *cell, tag_set new_tags)
236
+ {
237
+ for (auto &conn : cell->connections())
238
+ if (cell->output(conn.first))
239
+ add_tags(conn.second, new_tags);
240
+ }
241
+
242
+ void forward_tags(SigSpec dst, SigSpec src)
243
+ {
244
+ log_assert(GetSize(dst) == GetSize(src));
245
+ for (int i = 0; i < GetSize(dst); i++)
246
+ add_tags(dst[i], tags(src[i]));
247
+ }
248
+
249
+ void propagate_tags()
250
+ {
251
+ for (auto cell : module->cells()) {
252
+ if (cell->type == ID($set_tag)) {
253
+ pending_cells.insert(cell);
254
+ pending_cell_queue.push_back(cell);
255
+ }
256
+ }
257
+
258
+ while (!pending_cell_queue.empty()) {
259
+ Cell *cell = pending_cell_queue.front();
260
+ pending_cell_queue.pop_front();
261
+ pending_cells.erase(cell);
262
+
263
+ propagate_tags(cell);
264
+ }
265
+ }
266
+
267
+ SigBit tag_signal(IdString tag, SigBit bit)
268
+ {
269
+ sigmap.apply(bit);
270
+ if (!bit.is_wire())
271
+ return State::S0; // Constant value - no tags
272
+
273
+ auto found = tag_signals.find(std::make_pair(tag, bit));
274
+ if (found != tag_signals.end())
275
+ return found->second;
276
+
277
+ if (!tag_pool(tags(bit)).count(tag))
278
+ return State::S0; // Statically known to not have this tag
279
+
280
+ // TODO handle module inputs
281
+ auto drivers = modwalker.signal_drivers.find(bit);
282
+ if (drivers == modwalker.signal_drivers.end() || drivers->second.empty())
283
+ return State::S0; // No driver - no tags
284
+
285
+ log_assert(drivers->second.size() == 1);
286
+ auto driver = *drivers->second.begin();
287
+
288
+ emit_tag_signals(tag, driver.cell);
289
+
290
+ found = tag_signals.find(std::make_pair(tag, bit));
291
+ log_assert(found != tag_signals.end());
292
+ return found->second;
293
+ }
294
+
295
+ SigSpec tag_signal(IdString tag, SigSpec sig)
296
+ {
297
+ SigSpec result;
298
+ for (auto bit : sig)
299
+ result.append(tag_signal(tag, bit));
300
+ return result;
301
+ }
302
+
303
+ SigSpec tag_group_signal(IdString tag_group, SigSpec sig)
304
+ {
305
+ sigmap.apply(sig);
306
+ if (sig.is_fully_const() || tag_groups.count(tag_group) == 0)
307
+ return Const(0, GetSize(sig));
308
+
309
+ auto found = tag_group_signals.find(std::make_pair(tag_group, sig));
310
+ if (found != tag_group_signals.end())
311
+ return found->second;
312
+
313
+ SigSpec combined;
314
+
315
+ for (auto &tag : tag_groups[tag_group]) {
316
+ auto tag_sig = tag_signal(tag, sig);
317
+
318
+ if (!GetSize(combined))
319
+ combined = tag_sig;
320
+ else
321
+ combined = autoOr(NEW_ID, combined, tag_sig);
322
+ }
323
+
324
+ if (!GetSize(combined))
325
+ combined = Const(0, GetSize(sig));
326
+
327
+ tag_group_signals.emplace(std::make_pair(tag_group, sig), combined);
328
+ return combined;
329
+ }
330
+
331
+ void emit_tag_signal(IdString tag, SigBit bit, SigBit tag_bit)
332
+ {
333
+ sigmap.apply(bit);
334
+ sigmap.apply(tag_bit);
335
+
336
+ if (!tag_pool(tags(bit)).count(tag))
337
+ return;
338
+
339
+ auto key = std::make_pair(tag, bit);
340
+ auto found = tag_signals.find(key);
341
+ if (found != tag_signals.end()) {
342
+ module->connect(found->second, tag_bit);
343
+ return;
344
+ }
345
+ tag_signals.emplace(key, tag_bit);
346
+ }
347
+
348
+ void emit_tag_signal(IdString tag, SigSpec sig, SigSpec tag_sig)
349
+ {
350
+ log_assert(GetSize(sig) == GetSize(tag_sig));
351
+ for (int i = 0; i < GetSize(sig); i++)
352
+ emit_tag_signal(tag, sig[i], tag_sig[i]);
353
+ }
354
+
355
+ void emit_tag_signals(IdString tag, Cell *cell)
356
+ {
357
+ if (!pending_cells.insert(cell).second) {
358
+ // We have a cycle, emit placeholder wires which will be connected
359
+ // when the outer call for this tag/cell returns
360
+ for (auto &conn : cell->connections())
361
+ if (cell->output(conn.first))
362
+ emit_tag_signal(tag, conn.second, module->addWire(NEW_ID, GetSize(conn.second)));
363
+
364
+ return;
365
+ }
366
+
367
+ process_cell(tag, cell);
368
+
369
+ pending_cells.erase(cell);
370
+ }
371
+
372
+ IdString tag_id(const Cell *cell)
373
+ {
374
+ return module->twines().add(RTLIL::escape_id(cell->getParam(ID::TAG).decode_string()));
375
+ }
376
+
377
+ void propagate_tags(Cell *cell)
378
+ {
379
+ if (cell->type == ID($set_tag)) {
380
+ IdString tag = tag_id(cell);
381
+ if (all_tags.insert(tag).second) {
382
+ std::string tag_str = module->twines().str(tag);
383
+ auto group_sep = tag_str.find(':');
384
+ IdString tag_group = group_sep != std::string::npos
385
+ ? module->twines().add(tag_str.substr(0, group_sep)) : tag;
386
+ tag_groups[tag_group].insert(tag);
387
+ group_of_tag[tag] = tag_group;
388
+ }
389
+
390
+ auto &sig_y = cell->getPort(ID::Y);
391
+ auto &sig_a = cell->getPort(ID::A);
392
+ // TODO handle constant set/clr masks
393
+ add_tags(sig_y, singleton(tag));
394
+ forward_tags(sig_y, sig_a);
395
+ return;
396
+ }
397
+
398
+ if (cell->type == ID($get_tag)) {
399
+ return;
400
+ }
401
+
402
+ if (cell->type.in(ID($not), ID($pos))) {
403
+ auto &sig_y = cell->getPort(ID::Y);
404
+ auto sig_a = cell->getPort(ID::A);
405
+ if (cell->type.in(ID($not), ID($or))) {
406
+ sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool());
407
+ }
408
+ forward_tags(sig_y, sig_a);
409
+ return;
410
+ }
411
+
412
+ if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor), ID($bweqx))) {
413
+ auto &sig_y = cell->getPort(ID::Y);
414
+ auto sig_a = cell->getPort(ID::A);
415
+ auto sig_b = cell->getPort(ID::B);
416
+ if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor))) {
417
+ sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool());
418
+ sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool());
419
+ }
420
+ forward_tags(sig_y, sig_a);
421
+ forward_tags(sig_y, sig_b);
422
+ return;
423
+ }
424
+
425
+ if (cell->type.in(ID($mux), ID($bwmux))) {
426
+ auto &sig_y = cell->getPort(ID::Y);
427
+ auto &sig_a = cell->getPort(ID::A);
428
+ auto &sig_b = cell->getPort(ID::B);
429
+ auto sig_s = cell->getPort(ID::S);
430
+
431
+ if (cell->type == ID($mux))
432
+ sig_s = SigSpec(sig_s[0], GetSize(sig_y));
433
+
434
+ forward_tags(sig_y, sig_a);
435
+ forward_tags(sig_y, sig_b);
436
+ forward_tags(sig_y, sig_s);
437
+ return;
438
+ }
439
+
440
+ if (cell->is_builtin_ff() || cell->type == ID($anyinit)) {
441
+ FfData ff(&initvals, cell);
442
+
443
+ if (ff.has_clk || ff.has_gclk)
444
+ forward_tags(ff.sig_q, ff.sig_d);
445
+ return;
446
+ }
447
+
448
+ // Single output but, sensitive to all inputs
449
+ if (cell->type.in(
450
+ ID($le), ID($lt), ID($ge), ID($gt),
451
+ ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor),
452
+ ID($reduce_bool), ID($logic_not), ID($logic_or), ID($logic_and),
453
+ ID($eq), ID($ne)
454
+ )) {
455
+ auto &sig_y = cell->getPort(ID::Y);
456
+
457
+ add_tags(sig_y[0], tags(cell));
458
+ return;
459
+ }
460
+
461
+
462
+ // Fallback, propagate tags from all inputs to all outputs
463
+ add_tags(cell, tags(cell));
464
+
465
+ if (cell->type.in(
466
+ ID($_AND_), ID($_OR_), ID($_NAND_), ID($_NOR_), ID($_ANDNOT_), ID($_ORNOT_),
467
+ ID($_XOR_), ID($_XNOR_), ID($_NOT_), ID($_BUF_), ID($_MUX_),
468
+
469
+ ID($assert), ID($assume)
470
+ )) {
471
+ return;
472
+ }
473
+
474
+ // This isn't a correctness concern (unless cell is a module generating
475
+ // tags), but we may end up generating a lot of extra logic when
476
+ // reaching this
477
+ if (!warned_cells.insert(cell).second)
478
+ return;
479
+ if (cell->type.isPublic())
480
+ log_warning("Unhandled cell %s (%s) during tag propagation\n", cell, cell->type.unescape());
481
+ else
482
+ log_debug("Unhandled cell %s (%s) during tag propagation\n", cell, cell->type.unescape());
483
+ }
484
+
485
+ void process_cell(IdString tag, Cell *cell)
486
+ {
487
+ if (cell->type == ID($set_tag)) {
488
+ IdString cell_tag = tag_id(cell);
489
+
490
+ auto tag_sig_a = tag_signal(tag, cell->getPort(ID::A));
491
+ auto &sig_y = cell->getPort(ID::Y);
492
+
493
+ if (cell_tag == tag) {
494
+ auto &sig_set = cell->getPort(ID::SET);
495
+ auto &sig_clr = cell->getPort(ID::CLR);
496
+ tag_sig_a = autoAnd(NEW_ID, tag_sig_a, autoNot(NEW_ID, sig_clr));
497
+ tag_sig_a = autoOr(NEW_ID, tag_sig_a, sig_set);
498
+ }
499
+
500
+ emit_tag_signal(tag, sig_y, tag_sig_a);
501
+ return;
502
+ }
503
+
504
+ if (cell->type == ID($get_tag)) {
505
+ log_assert(false);
506
+ }
507
+
508
+ if (cell->type.in(ID($not), ID($pos), ID($_NOT_), ID($_BUF_))) {
509
+ auto &sig_y = cell->getPort(ID::Y);
510
+ auto sig_a = cell->getPort(ID::A);
511
+ if (cell->type.in(ID($not), ID($or))) {
512
+ sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool());
513
+ }
514
+ emit_tag_signal(tag, sig_y, tag_signal(tag, sig_a));
515
+ return;
516
+ }
517
+
518
+ if (cell->type.in(
519
+ ID($and), ID($or),
520
+ ID($_AND_), ID($_OR_), ID($_NAND_), ID($_NOR_), ID($_ANDNOT_), ID($_ORNOT_)
521
+ )) {
522
+ auto &sig_y = cell->getPort(ID::Y);
523
+ auto sig_a = cell->getPort(ID::A);
524
+ auto sig_b = cell->getPort(ID::B);
525
+ if (cell->type.in(ID($and), ID($or))) {
526
+ sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool());
527
+ sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool());
528
+ }
529
+
530
+ bool inv_a = false;
531
+ bool inv_b = false;
532
+
533
+ if (cell->type.in(ID($or), ID($_OR_), ID($_NOR_), ID($_ORNOT_)))
534
+ inv_a ^= true, inv_b ^= true;
535
+ if (cell->type.in(ID($_ANDNOT_), ID($_ORNOT_)))
536
+ inv_b ^= true;
537
+
538
+ if (inv_a)
539
+ sig_a = autoNot(NEW_ID, sig_a);
540
+ if (inv_b)
541
+ sig_b = autoNot(NEW_ID, sig_b);
542
+
543
+ auto group_sig_a = tag_group_signal(tag, sig_a);
544
+ auto group_sig_b = tag_group_signal(tag, sig_b);
545
+
546
+ auto tag_sig_a = tag_signal(tag, sig_a);
547
+ auto tag_sig_b = tag_signal(tag, sig_b);
548
+
549
+
550
+ // Does this input allow propagating (doesn't fix output or same tag group)
551
+ sig_a = autoOr(NEW_ID, sig_a, group_sig_a);
552
+ sig_b = autoOr(NEW_ID, sig_b, group_sig_b);
553
+
554
+ // Mask input tags by whether the other side allows propagation
555
+ tag_sig_a = autoAnd(NEW_ID, tag_sig_a, sig_b);
556
+ tag_sig_b = autoAnd(NEW_ID, tag_sig_b, sig_a);
557
+
558
+
559
+ auto tag_sig = autoOr(NEW_ID, tag_sig_a, tag_sig_b);
560
+ emit_tag_signal(tag, sig_y, tag_sig);
561
+ return;
562
+ }
563
+
564
+ if (cell->type.in(ID($xor), ID($xnor), ID($bweqx), ID($_XOR_), ID($_XNOR_))) {
565
+ auto &sig_y = cell->getPort(ID::Y);
566
+ auto sig_a = cell->getPort(ID::A);
567
+ auto sig_b = cell->getPort(ID::B);
568
+ if (cell->type.in(ID($xor), ID($xnor))) {
569
+ sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool());
570
+ sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool());
571
+ }
572
+
573
+ auto tag_sig_a = tag_signal(tag, sig_a);
574
+ auto tag_sig_b = tag_signal(tag, sig_b);
575
+
576
+ auto tag_sig = autoOr(NEW_ID, tag_sig_a, tag_sig_b);
577
+ emit_tag_signal(tag, sig_y, tag_sig);
578
+ return;
579
+ }
580
+
581
+
582
+ if (cell->type.in(ID($_MUX_), ID($mux), ID($bwmux))) {
583
+ auto &sig_y = cell->getPort(ID::Y);
584
+ auto &sig_a = cell->getPort(ID::A);
585
+ auto &sig_b = cell->getPort(ID::B);
586
+ auto sig_s = cell->getPort(ID::S);
587
+
588
+ if (cell->type == ID($mux))
589
+ sig_s = SigSpec(sig_s[0], GetSize(sig_y));
590
+
591
+ auto group_sig_a = tag_group_signal(tag, sig_a);
592
+ auto group_sig_b = tag_group_signal(tag, sig_b);
593
+ auto group_sig_s = tag_group_signal(tag, sig_s);
594
+
595
+ auto prop_s = autoOr(NEW_ID,
596
+ autoXor(NEW_ID, sig_a, sig_b),
597
+ autoOr(NEW_ID, group_sig_a, group_sig_b));
598
+
599
+ auto prop_a = autoOr(NEW_ID, autoNot(NEW_ID, sig_s), group_sig_s);
600
+ auto prop_b = autoOr(NEW_ID, sig_s, group_sig_s);
601
+
602
+ auto tag_sig_a = tag_signal(tag, sig_a);
603
+ auto tag_sig_b = tag_signal(tag, sig_b);
604
+ auto tag_sig_s = tag_signal(tag, sig_s);
605
+
606
+ tag_sig_a = autoAnd(NEW_ID, tag_sig_a, prop_a);
607
+ tag_sig_b = autoAnd(NEW_ID, tag_sig_b, prop_b);
608
+ tag_sig_s = autoAnd(NEW_ID, tag_sig_s, prop_s);
609
+
610
+ auto tag_sig = autoOr(NEW_ID, tag_sig_s,
611
+ autoOr(NEW_ID, tag_sig_a, tag_sig_b));
612
+ emit_tag_signal(tag, sig_y, tag_sig);
613
+ return;
614
+ }
615
+
616
+ if (cell->type.in(ID($eq), ID($ne), ID($eqx), ID($nex))) {
617
+ auto &sig_y = cell->getPort(ID::Y);
618
+ auto sig_a = cell->getPort(ID::A);
619
+ auto sig_b = cell->getPort(ID::B);
620
+ int width = std::max(GetSize(sig_a), GetSize(sig_b));
621
+ sig_a.extend_u0(width, cell->getParam(ID::A_SIGNED).as_bool());
622
+ sig_b.extend_u0(width, cell->getParam(ID::B_SIGNED).as_bool());
623
+
624
+ auto group_sig_a = tag_group_signal(tag, sig_a);
625
+ auto group_sig_b = tag_group_signal(tag, sig_b);
626
+
627
+ auto tag_sig_a = tag_signal(tag, sig_a);
628
+ auto tag_sig_b = tag_signal(tag, sig_b);
629
+
630
+ auto group_sig = autoOr(NEW_ID, group_sig_a, group_sig_b);
631
+ // The output can only be affected by the tagged inputs if all group-untagged bits are equal
632
+
633
+ auto masked_a = autoOr(NEW_ID, sig_a, group_sig);
634
+ auto masked_b = autoOr(NEW_ID, sig_b, group_sig);
635
+
636
+ auto prop = autoEq(NEW_ID, masked_a, masked_b);
637
+
638
+ auto tag_sig = autoAnd(NEW_ID, prop, autoReduceOr(NEW_ID, SigSpec{tag_sig_a, tag_sig_b}));
639
+ tag_sig.extend_u0(GetSize(sig_y), false);
640
+ emit_tag_signal(tag, sig_y, tag_sig);
641
+ return;
642
+ }
643
+
644
+
645
+ if (cell->type.in(ID($lt), ID($gt), ID($le), ID($ge))) {
646
+ auto &sig_y = cell->getPort(ID::Y);
647
+ auto sig_a = cell->getPort(ID::A);
648
+ auto sig_b = cell->getPort(ID::B);
649
+ int width = std::max(GetSize(sig_a), GetSize(sig_b));
650
+ sig_a.extend_u0(width, cell->getParam(ID::A_SIGNED).as_bool());
651
+ sig_b.extend_u0(width, cell->getParam(ID::B_SIGNED).as_bool());
652
+
653
+ if (cell->type.in(ID($gt), ID($le)))
654
+ std::swap(sig_a, sig_b);
655
+
656
+ auto group_sig_a = tag_group_signal(tag, sig_a);
657
+ auto group_sig_b = tag_group_signal(tag, sig_b);
658
+
659
+ auto tag_sig_a = tag_signal(tag, sig_a);
660
+ auto tag_sig_b = tag_signal(tag, sig_b);
661
+
662
+ auto group_sig = autoOr(NEW_ID, group_sig_a, group_sig_b);
663
+ // The output can only be affected by the tagged inputs if the greatest possible sig_a is
664
+ // greater or equal to the least possible sig_b
665
+ auto masked_a = autoOr(NEW_ID, sig_a, group_sig);
666
+ auto masked_b = autoAnd(NEW_ID, sig_b, autoNot(NEW_ID, group_sig));
667
+
668
+ auto prop = autoGe(NEW_ID, masked_a, masked_b);
669
+
670
+ auto tag_sig = autoAnd(NEW_ID, prop, autoReduceOr(NEW_ID, SigSpec{tag_sig_a, tag_sig_b}));
671
+ tag_sig.extend_u0(GetSize(sig_y), false);
672
+ emit_tag_signal(tag, sig_y, tag_sig);
673
+ return;
674
+ }
675
+
676
+ if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_bool), ID($logic_not))) {
677
+ auto &sig_y = cell->getPort(ID::Y);
678
+ auto sig_a = cell->getPort(ID::A);
679
+
680
+ auto group_sig_a = tag_group_signal(tag, sig_a);
681
+ auto tag_sig_a = tag_signal(tag, sig_a);
682
+
683
+ if (cell->type.in(ID($reduce_or), ID($reduce_bool), ID($logic_not)))
684
+ sig_a = autoNot(NEW_ID, sig_a);
685
+
686
+ auto filled = autoOr(NEW_ID, sig_a, group_sig_a);
687
+
688
+ auto prop = autoReduceAnd(NEW_ID, filled);
689
+ auto tagged = autoReduceOr(NEW_ID, tag_sig_a);
690
+ auto tag_sig = autoAnd(NEW_ID, prop, tagged);
691
+ tag_sig.extend_u0(GetSize(sig_y), false);
692
+ emit_tag_signal(tag, sig_y, tag_sig);
693
+ return;
694
+ }
695
+
696
+ if (cell->is_builtin_ff() || cell->type == ID($anyinit)) {
697
+ FfData ff(&initvals, cell);
698
+ // TODO handle some more variants
699
+ if ((ff.has_clk || ff.has_gclk) && !ff.has_ce && !ff.has_aload && !ff.has_srst && !ff.has_arst && !ff.has_sr) {
700
+ if (ff.has_clk && !tags(ff.sig_clk).empty())
701
+ log_warning("Tags on CLK input ignored for %s (%s)\n", cell, cell->type.unescape());
702
+
703
+ int width = ff.width;
704
+
705
+ auto sig_q = ff.sig_q;
706
+ auto sig_d = ff.sig_d;
707
+
708
+ ff.name = module->twines().add(NEW_ID);
709
+ ff.cell = nullptr;
710
+ ff.sig_d = tag_signal(tag, ff.sig_d);
711
+ ff.sig_q = module->addWire(NEW_ID, width);
712
+ ff.is_anyinit = false;
713
+ ff.val_init = Const(0, width);
714
+ ff.emit();
715
+
716
+ emit_tag_signal(tag, sig_q, ff.sig_q);
717
+ return;
718
+ } else {
719
+ log_warning("Unhandled FF-cell %s (%s), consider running clk2fflogic, async2sync and/or dffunmap\n", cell, cell->type.unescape());
720
+
721
+ // For unhandled FFs, the default propagation would cause combinational loops
722
+ emit_tag_signal(tag, ff.sig_q, Const(0, ff.width));
723
+ return;
724
+ }
725
+ }
726
+
727
+ // Fallback
728
+ SigSpec tag_input;
729
+
730
+ for (auto &conn : cell->connections()) {
731
+ if (cell->input(conn.first)) {
732
+ auto tag_sig = tag_signal(tag, conn.second);
733
+ tag_input.append(tag_sig);
734
+ }
735
+ }
736
+
737
+ SigBit any_tagged = autoReduceOr(NEW_ID, tag_input);
738
+
739
+ for (auto &conn : cell->connections()) {
740
+ if (cell->output(conn.first)) {
741
+ emit_tag_signal(tag, conn.second, SigSpec(any_tagged, GetSize(conn.second)));
742
+ }
743
+ }
744
+
745
+ // As fallback we propagate all tags from all inputs to all outputs,
746
+ // which is an over-approximation (unless the cell is a module that
747
+ // generates tags itself in which case it could be arbitrary).
748
+ if (warned_cells.insert(cell).second)
749
+ log_warning("Unhandled cell %s (%s) while emitting tag signals\n", cell, cell->type.unescape());
750
+ }
751
+
752
+ void emit_tags()
753
+ {
754
+ warned_cells.clear();
755
+ std::vector<Cell *> get_tag_cells;
756
+ for (auto cell : module->selected_cells())
757
+ if (cell->type == ID($get_tag))
758
+ get_tag_cells.push_back(cell);
759
+
760
+ for (auto cell : get_tag_cells) {
761
+ auto &sig_a = cell->getPort(ID::A);
762
+ IdString tag = tag_id(cell);
763
+
764
+ tag_signal(tag, sig_a);
765
+ }
766
+
767
+ if (options.tag_public)
768
+ {
769
+ std::vector<Wire *> public_wires;
770
+
771
+ for (auto wire : module->selected_wires())
772
+ if (wire->name.isPublic())
773
+ public_wires.push_back(wire);
774
+
775
+ for (auto wire : public_wires) {
776
+ for (auto tag : tag_pool(tags(SigSpec(wire)))) {
777
+ auto tag_sig = tag_signal(tag, SigSpec(wire));
778
+ if (tag_sig.is_fully_zero())
779
+ continue;
780
+
781
+ int index = 0;
782
+ std::string tag_str = module->twines().unescaped_str(tag);
783
+ auto name = module->uniquify(stringf("%s:%s", wire->name, tag_str), index);
784
+ auto hdlname = wire->get_hdlname_attribute();
785
+
786
+ if (!hdlname.empty())
787
+ hdlname.back() += index ?
788
+ stringf(":%s_%d", tag_str, index) :
789
+ stringf(":%s", tag_str);
790
+
791
+ auto tag_wire = module->addWire(name, wire->width);
792
+
793
+ tag_wire->set_bool_attribute(ID::keep);
794
+ tag_wire->set_bool_attribute(ID(dft_tag));
795
+ if (!hdlname.empty())
796
+ tag_wire->set_hdlname_attribute(hdlname);
797
+
798
+ module->connect(tag_wire, tag_sig);
799
+ }
800
+ }
801
+ }
802
+ }
803
+
804
+ void replace_dft_cells()
805
+ {
806
+ std::vector<Cell *> get_tag_cells;
807
+ std::vector<Cell *> set_tag_cells;
808
+ for (auto cell : module->cells()) {
809
+ if (cell->type == ID($get_tag))
810
+ get_tag_cells.push_back(cell);
811
+
812
+ if (cell->type == ID($set_tag))
813
+ set_tag_cells.push_back(cell);
814
+
815
+ log_assert(!cell->type.in(ID($overwrite_tag), ID($original_tag)));
816
+ }
817
+
818
+ for (auto cell : set_tag_cells) {
819
+ auto &sig_a = cell->getPort(ID::A);
820
+ auto &sig_y = cell->getPort(ID::Y);
821
+ module->connect(sig_y, sig_a);
822
+ module->remove(cell);
823
+ }
824
+
825
+ for (auto cell : get_tag_cells) {
826
+ auto &sig_a = cell->getPort(ID::A);
827
+ auto &sig_y = cell->getPort(ID::Y);
828
+ IdString tag = tag_id(cell);
829
+
830
+ auto tag_sig = tag_signal(tag, sig_a);
831
+ module->connect(sig_y, tag_sig);
832
+ module->remove(cell);
833
+ }
834
+ }
835
+
836
+
837
+ SigSpec autoAnd(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b)
838
+ {
839
+ log_assert(GetSize(sig_a) == GetSize(sig_b));
840
+ if (sig_a.is_fully_zero() || sig_b.is_fully_ones() || sig_a == sig_b)
841
+ return sig_a;
842
+ if (sig_a.is_fully_ones() || sig_b.is_fully_zero())
843
+ return sig_b;
844
+
845
+ return module->And(std::move(name), sig_a, sig_b);
846
+ }
847
+
848
+ SigSpec autoOr(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b)
849
+ {
850
+ log_assert(GetSize(sig_a) == GetSize(sig_b));
851
+ if (sig_a.is_fully_ones() || sig_b.is_fully_zero() || sig_a == sig_b)
852
+ return sig_a;
853
+ if (sig_a.is_fully_zero() || sig_b.is_fully_ones())
854
+ return sig_b;
855
+
856
+ return module->Or(std::move(name), sig_a, sig_b);
857
+ }
858
+
859
+ SigSpec autoXor(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b)
860
+ {
861
+ log_assert(GetSize(sig_a) == GetSize(sig_b));
862
+ if (sig_a == sig_b)
863
+ return Const(State::S0, GetSize(sig_a));
864
+ if (sig_a.is_fully_zero())
865
+ return sig_b;
866
+ if (sig_b.is_fully_zero())
867
+ return sig_a;
868
+ if (sig_a.is_fully_ones())
869
+ return autoNot(std::move(name), sig_b);
870
+ if (sig_b.is_fully_ones())
871
+ return autoNot(std::move(name), sig_a);
872
+ return module->Xor(std::move(name), sig_a, sig_b);
873
+ }
874
+
875
+ SigSpec autoXnor(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b)
876
+ {
877
+ log_assert(GetSize(sig_a) == GetSize(sig_b));
878
+ if (sig_a == sig_b)
879
+ return Const(State::S1, GetSize(sig_a));
880
+ if (sig_a.is_fully_ones())
881
+ return sig_b;
882
+ if (sig_b.is_fully_ones())
883
+ return sig_a;
884
+ if (sig_a.is_fully_zero())
885
+ return autoNot(std::move(name), sig_b);
886
+ if (sig_b.is_fully_zero())
887
+ return autoNot(std::move(name), sig_a);
888
+ return module->Xnor(std::move(name), sig_a, sig_b);
889
+ }
890
+
891
+ SigSpec autoNot(TwineSpec &&name, const SigSpec &sig_a)
892
+ {
893
+ if (sig_a.is_fully_const()) {
894
+ auto const_val = sig_a.as_const();
895
+ for (auto bit : const_val) {
896
+ State b = bit;
897
+ bit = b == State::S0 ? State::S1 : b == State::S1 ? State::S0 : b;
898
+ }
899
+ return const_val;
900
+ }
901
+ return module->Not(std::move(name), sig_a);
902
+ }
903
+
904
+ SigSpec autoEq(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b)
905
+ {
906
+ log_assert(GetSize(sig_a) == GetSize(sig_b));
907
+ if (sig_a == sig_b)
908
+ return State::S1;
909
+ for (int i = 0; i < GetSize(sig_a); i++) {
910
+ auto bit_a = sig_a[i];
911
+ auto bit_b = sig_b[i];
912
+ if (bit_a.is_wire() || bit_b.is_wire())
913
+ continue;
914
+ if ((bit_a.data == State::S0 && bit_b.data == State::S1) ||
915
+ (bit_a.data == State::S1 && bit_b.data == State::S0))
916
+ return State::S0;
917
+ }
918
+
919
+ return module->Eq(std::move(name), sig_a, sig_b);
920
+ }
921
+
922
+ SigSpec autoGe(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b)
923
+ {
924
+ log_assert(GetSize(sig_a) == GetSize(sig_b));
925
+ if (sig_a == sig_b || sig_a.is_fully_ones())
926
+ return State::S1;
927
+ if (sig_b.is_fully_zero())
928
+ return State::S1;
929
+
930
+ return module->Ge(std::move(name), sig_a, sig_b);
931
+ }
932
+
933
+ SigSpec autoReduceAnd(TwineSpec &&name, const SigSpec &sig_a)
934
+ {
935
+ if (GetSize(sig_a) == 0)
936
+ return State::S1;
937
+
938
+ if (GetSize(sig_a) == 1 || sig_a == SigSpec(sig_a[0], GetSize(sig_a)))
939
+ return sig_a[0];
940
+ for (auto bit : sig_a)
941
+ if (!bit.is_wire() && bit.data == State::S0)
942
+ return State::S0;
943
+ if (sig_a.is_fully_ones())
944
+ return State::S1;
945
+ return module->ReduceAnd(std::move(name), sig_a);
946
+ }
947
+
948
+ SigSpec autoReduceOr(TwineSpec &&name, const SigSpec &sig_a)
949
+ {
950
+ if (GetSize(sig_a) == 0)
951
+ return State::S0;
952
+
953
+ if (GetSize(sig_a) == 1 || sig_a == SigSpec(sig_a[0], GetSize(sig_a)))
954
+ return sig_a[0];
955
+ for (auto bit : sig_a)
956
+ if (!bit.is_wire() && bit.data == State::S1)
957
+ return State::S1;
958
+ if (sig_a.is_fully_zero())
959
+ return State::S0;
960
+ return module->ReduceOr(std::move(name), sig_a);
961
+ }
962
+ };
963
+
964
+ struct DftTagPass : public Pass {
965
+ DftTagPass() : Pass("dft_tag", "create tagging logic for data flow tracking") {}
966
+ bool formatted_help() override {
967
+ auto *help = PrettyHelp::get_current();
968
+ help->set_group("formal");
969
+ return false;
970
+ }
971
+ void help() override
972
+ {
973
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
974
+ log("\n");
975
+ log(" dft_tag [options] [selection]\n");
976
+ log("\n");
977
+ log("This pass... TODO\n");
978
+ log("\n");
979
+ log(" -overwrite-only\n");
980
+ log(" Only process $overwrite_tag and $original_tag cells.\n");
981
+ log(" -tag-public\n");
982
+ log(" For each public wire that may carry tagged data, create a new public\n");
983
+ log(" wire (named <wirename>:<tagname>) that carries the tag bits. Note\n");
984
+ log(" that without this, tagging logic will only be emitted as required\n");
985
+ log(" for uses of $get_tag.\n");
986
+ log("\n");
987
+ }
988
+
989
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
990
+ {
991
+ DftTagOptions options;
992
+
993
+ log_header(design, "Executing DFT_TAG pass.\n");
994
+
995
+ size_t argidx;
996
+ for (argidx = 1; argidx < args.size(); argidx++) {
997
+ if (args[argidx] == "-tag-public") {
998
+ options.tag_public = true;
999
+ continue;
1000
+ }
1001
+ if (args[argidx] == "-overwrite-only") {
1002
+ options.overwrite_only = true;
1003
+ continue;
1004
+ }
1005
+ break;
1006
+ }
1007
+
1008
+ extra_args(args, argidx, design);
1009
+
1010
+ for (auto module : design->selected_modules()) {
1011
+ DftTagWorker worker(module, options);
1012
+
1013
+ log_debug("Resolve overwrite_tag and original_tag.\n");
1014
+ worker.resolve_overwrites();
1015
+
1016
+ if (options.overwrite_only)
1017
+ continue;
1018
+
1019
+ log_debug("Propagate tagged signals.\n");
1020
+ worker.propagate_tags();
1021
+
1022
+ log_debug("Emit tag signals and logic.\n");
1023
+ worker.emit_tags();
1024
+
1025
+ log_debug("Replace dft cells.\n");
1026
+ worker.replace_dft_cells();
1027
+ }
1028
+ }
1029
+ } DftTagPass;
1030
+
1031
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/edgetypes.cc ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct EdgetypePass : public Pass {
28
+ EdgetypePass() : Pass("edgetypes", "list all types of edges in selection") { }
29
+ bool formatted_help() override {
30
+ auto *help = PrettyHelp::get_current();
31
+ help->set_group("passes/status");
32
+ return false;
33
+ }
34
+ void help() override
35
+ {
36
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
37
+ log("\n");
38
+ log(" edgetypes [options] [selection]\n");
39
+ log("\n");
40
+ log("This command lists all unique types of 'edges' found in the selection. An 'edge'\n");
41
+ log("is a 4-tuple of source and sink cell type and port name.\n");
42
+ log("\n");
43
+ }
44
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
45
+ {
46
+ size_t argidx;
47
+ for (argidx = 1; argidx < args.size(); argidx++) {
48
+ // if (args[argidx] == "-ltr") {
49
+ // config.ltr = true;
50
+ // continue;
51
+ // }
52
+ break;
53
+ }
54
+ extra_args(args, argidx, design);
55
+
56
+ pool<string> edge_cache;
57
+
58
+ for (auto module : design->selected_modules())
59
+ {
60
+ SigMap sigmap(module);
61
+ dict<SigBit, pool<tuple<IdString, IdString, int>>> bit_sources, bit_sinks;
62
+ pool<std::pair<IdString, IdString>> multibit_ports;
63
+
64
+ for (auto cell : module->selected_cells())
65
+ for (auto conn : cell->connections())
66
+ {
67
+ IdString cell_type = cell->type;
68
+ IdString port_name = conn.first;
69
+ SigSpec sig = sigmap(conn.second);
70
+
71
+ if (GetSize(sig) > 1)
72
+ multibit_ports.insert(std::pair<IdString, IdString>(cell_type, port_name));
73
+
74
+ for (int i = 0; i < GetSize(sig); i++) {
75
+ if (cell->output(port_name))
76
+ bit_sources[sig[i]].insert(tuple<IdString, IdString, int>(cell_type, port_name, i));
77
+ if (cell->input(port_name))
78
+ bit_sinks[sig[i]].insert(tuple<IdString, IdString, int>(cell_type, port_name, i));
79
+ }
80
+ }
81
+
82
+ for (auto &it : bit_sources)
83
+ for (auto &source : it.second)
84
+ for (auto &sink : bit_sinks[it.first])
85
+ {
86
+ auto source_cell_type = std::get<0>(source);
87
+ auto source_port_name = std::get<1>(source);
88
+ auto source_bit_index = std::get<2>(source);
89
+
90
+ auto sink_cell_type = std::get<0>(sink);
91
+ auto sink_port_name = std::get<1>(sink);
92
+ auto sink_bit_index = std::get<2>(sink);
93
+
94
+ string source_str = multibit_ports.count(std::pair<IdString, IdString>(source_cell_type, source_port_name)) ?
95
+ stringf("%s.%s[%d]", PooledName(module, source_cell_type).unescape(), PooledName(module, source_port_name).unescape(), source_bit_index) :
96
+ stringf("%s.%s", PooledName(module, source_cell_type).unescape(), PooledName(module, source_port_name).unescape());
97
+
98
+ string sink_str = multibit_ports.count(std::pair<IdString, IdString>(sink_cell_type, sink_port_name)) ?
99
+ stringf("%s.%s[%d]", PooledName(module, sink_cell_type).unescape(), PooledName(module, sink_port_name).unescape(), sink_bit_index) :
100
+ stringf("%s.%s", PooledName(module, sink_cell_type).unescape(), PooledName(module, sink_port_name).unescape());
101
+
102
+ edge_cache.insert(source_str + " " + sink_str);
103
+ }
104
+ }
105
+
106
+ edge_cache.sort();
107
+ for (auto &str : edge_cache)
108
+ log("%s\n", str);
109
+ }
110
+ } EdgetypePass;
111
+
112
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/example_dt.cc ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "kernel/yosys.h"
2
+ #include "kernel/drivertools.h"
3
+ #include "kernel/topo_scc.h"
4
+ #include "kernel/compute_graph.h"
5
+
6
+ USING_YOSYS_NAMESPACE
7
+ PRIVATE_NAMESPACE_BEGIN
8
+
9
+
10
+
11
+
12
+ struct ExampleWorker
13
+ {
14
+ DriverMap dm;
15
+ Module *module;
16
+
17
+ ExampleWorker(Module *module) : module(module) {
18
+ dm.celltypes.setup();
19
+ }
20
+ };
21
+
22
+ struct ExampleDtPass : public Pass
23
+ {
24
+ ExampleDtPass() : Pass("example_dt", "drivertools example") {
25
+ internal();
26
+ }
27
+
28
+ void help() override
29
+ {
30
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
31
+ log("\n");
32
+ log("TODO: add help message\n");
33
+ log("\n");
34
+ }
35
+
36
+
37
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
38
+ {
39
+ size_t argidx = 1;
40
+ extra_args(args, argidx, design);
41
+
42
+ for (auto module : design->selected_modules()) {
43
+ ExampleWorker worker(module);
44
+ DriverMap dm;
45
+
46
+ TwinePool &twines = design->twines();
47
+ const IdString fn_concat = twines.add("$$concat");
48
+ const IdString fn_input = twines.add("$$input");
49
+ const IdString fn_buf = twines.add("$$buf");
50
+ const IdString fn_slice = twines.add("$$slice");
51
+ const IdString fn_state = twines.add("$$state");
52
+ const IdString fn_cell_output = twines.add("$$cell_output");
53
+ const IdString fn_const = twines.add("$$const");
54
+ const IdString fn_multi = twines.add("$$multi");
55
+ const IdString fn_undriven = twines.add("$$undriven");
56
+
57
+ struct ExampleFn {
58
+ IdString name;
59
+ dict<IdString, Const> parameters;
60
+
61
+ ExampleFn(IdString name) : name(name) {}
62
+ ExampleFn(IdString name, dict<IdString, Const> parameters) : name(name), parameters(parameters) {}
63
+
64
+ bool operator==(ExampleFn const &other) const {
65
+ return name == other.name && parameters == other.parameters;
66
+ }
67
+
68
+ [[nodiscard]] Hasher hash_into(Hasher h) const {
69
+ h.eat(name);
70
+ h.eat(parameters);
71
+ return h;
72
+ }
73
+ };
74
+
75
+ typedef ComputeGraph<ExampleFn, int, IdString, IdString> ExampleGraph;
76
+
77
+ ExampleGraph compute_graph;
78
+
79
+
80
+ dm.add(module);
81
+
82
+ idict<DriveSpec> queue;
83
+ idict<Cell *> cells;
84
+
85
+ IntGraph edges;
86
+ std::vector<int> graph_nodes;
87
+
88
+ auto enqueue = [&](DriveSpec const &spec) {
89
+ int index = queue(spec);
90
+ if (index == GetSize(graph_nodes))
91
+ graph_nodes.emplace_back(compute_graph.add(ID($pending), index).index());
92
+ //if (index >= GetSize(graph_nodes))
93
+ return compute_graph[graph_nodes[index]];
94
+ };
95
+
96
+ for (auto cell : module->cells()) {
97
+ if (cell->type.in(ID($assert), ID($assume), ID($cover), ID($check)))
98
+ enqueue(DriveBitMarker(cells(cell), 0));
99
+ }
100
+
101
+ for (auto wire : module->wires()) {
102
+ if (!wire->port_output)
103
+ continue;
104
+ enqueue(DriveChunk(DriveChunkWire(wire, 0, wire->width))).assign_key(wire->name);
105
+ }
106
+
107
+ for (int i = 0; i != GetSize(queue); ++i)
108
+ {
109
+ DriveSpec spec = queue[i];
110
+ ExampleGraph::Ref node = compute_graph[i];
111
+
112
+ if (spec.chunks().size() > 1) {
113
+ node.set_function(fn_concat);
114
+
115
+ for (auto const &chunk : spec.chunks()) {
116
+ node.append_arg(enqueue(chunk));
117
+ }
118
+ } else if (spec.chunks().size() == 1) {
119
+ DriveChunk chunk = spec.chunks()[0];
120
+ if (chunk.is_wire()) {
121
+ DriveChunkWire wire_chunk = chunk.wire();
122
+ if (wire_chunk.is_whole()) {
123
+ node.sparse_attr() = wire_chunk.wire->name;
124
+ if (wire_chunk.wire->port_input) {
125
+ node.set_function(ExampleFn(fn_input, {{wire_chunk.wire->name, {}}}));
126
+ } else {
127
+ DriveSpec driver = dm(DriveSpec(wire_chunk));
128
+ node.set_function(fn_buf);
129
+
130
+ node.append_arg(enqueue(driver));
131
+ }
132
+ } else {
133
+ DriveChunkWire whole_wire(wire_chunk.wire, 0, wire_chunk.wire->width);
134
+ node.set_function(ExampleFn(fn_slice, {{ID::offset, wire_chunk.offset}, {ID::width, wire_chunk.width}}));
135
+ node.append_arg(enqueue(whole_wire));
136
+ }
137
+ } else if (chunk.is_port()) {
138
+ DriveChunkPort port_chunk = chunk.port();
139
+ if (port_chunk.is_whole()) {
140
+ if (dm.celltypes.cell_output(port_chunk.cell->type, port_chunk.port)) {
141
+ if (port_chunk.cell->type.in(ID($dff), ID($ff)))
142
+ {
143
+ Cell *cell = port_chunk.cell;
144
+ node.set_function(ExampleFn(fn_state, {{cell->name, {}}}));
145
+ for (auto const &conn : cell->connections()) {
146
+ if (!dm.celltypes.cell_input(cell->type, conn.first))
147
+ continue;
148
+ enqueue(DriveChunkPort(cell, conn)).assign_key(cell->name);
149
+ }
150
+ }
151
+ else
152
+ {
153
+ node.set_function(ExampleFn(fn_cell_output, {{port_chunk.port, {}}}));
154
+ node.append_arg(enqueue(DriveBitMarker(cells(port_chunk.cell), 0)));
155
+ }
156
+ } else {
157
+ node.set_function(fn_buf);
158
+
159
+ DriveSpec driver = dm(DriveSpec(port_chunk));
160
+ node.append_arg(enqueue(driver));
161
+ }
162
+
163
+ } else {
164
+ DriveChunkPort whole_port(port_chunk.cell, port_chunk.port, 0, GetSize(port_chunk.cell->connections().at(port_chunk.port)));
165
+ node.set_function(ExampleFn(fn_slice, {{ID::offset, port_chunk.offset}}));
166
+ node.append_arg(enqueue(whole_port));
167
+ }
168
+ } else if (chunk.is_constant()) {
169
+ node.set_function(ExampleFn(fn_const, {{ID::value, chunk.constant()}}));
170
+
171
+ } else if (chunk.is_multiple()) {
172
+ node.set_function(fn_multi);
173
+ for (auto const &driver : chunk.multiple().multiple())
174
+ node.append_arg(enqueue(driver));
175
+ } else if (chunk.is_marker()) {
176
+ Cell *cell = cells[chunk.marker().marker];
177
+
178
+ node.set_function(ExampleFn(cell->type, dict<IdString, Const>(cell->parameters.begin(), cell->parameters.end())));
179
+ for (auto const &conn : cell->connections()) {
180
+ if (!dm.celltypes.cell_input(cell->type, conn.first))
181
+ continue;
182
+
183
+ node.append_arg(enqueue(DriveChunkPort(cell, conn)));
184
+ }
185
+ } else if (chunk.is_none()) {
186
+ node.set_function(fn_undriven);
187
+
188
+ } else {
189
+ log_error("unhandled drivespec: %s\n", log_signal(chunk));
190
+ log_abort();
191
+ }
192
+ } else {
193
+ log_abort();
194
+ }
195
+ }
196
+
197
+
198
+ // Perform topo sort and detect SCCs
199
+ ExampleGraph::SccAdaptor compute_graph_scc(compute_graph);
200
+
201
+
202
+ std::vector<int> perm;
203
+ TopoSortedSccs(compute_graph_scc, [&](int *begin, int *end) {
204
+ perm.insert(perm.end(), begin, end);
205
+ if (end > begin + 1)
206
+ {
207
+ std::string message = "SCC:";
208
+ for (int *i = begin; i != end; ++i)
209
+ message += stringf(" %d", *i);
210
+ log_warning("%s\n", message);
211
+ }
212
+ }).process_sources().process_all();
213
+ compute_graph.permute(perm);
214
+
215
+
216
+ // Forward $$buf unless we have a name in the sparse attribute
217
+ std::vector<int> alias;
218
+ perm.clear();
219
+
220
+ for (int i = 0; i < compute_graph.size(); ++i)
221
+ {
222
+ if (compute_graph[i].function().name == fn_buf && !compute_graph[i].has_sparse_attr() && compute_graph[i].arg(0).index() < i)
223
+ {
224
+
225
+ alias.push_back(alias[compute_graph[i].arg(0).index()]);
226
+ }
227
+ else
228
+ {
229
+ alias.push_back(GetSize(perm));
230
+ perm.push_back(i);
231
+ }
232
+ }
233
+ compute_graph.permute(perm, alias);
234
+
235
+ // Dump the compute graph
236
+ for (int i = 0; i < compute_graph.size(); ++i)
237
+ {
238
+ auto ref = compute_graph[i];
239
+ std::string message = stringf("n%d ", i);
240
+ message += PooledName(design, ref.function().name).unescape();
241
+ for (auto const &param : ref.function().parameters)
242
+ {
243
+ if (param.second.empty())
244
+ message += stringf("[%s]", PooledName(design, param.first).unescape());
245
+ else
246
+ message += stringf("[%s=%s]", PooledName(design, param.first).unescape(), log_const(param.second));
247
+ }
248
+ message += "(";
249
+
250
+ for (int i = 0, end = ref.size(); i != end; ++i)
251
+ {
252
+ if (i > 0)
253
+ message += ", ";
254
+ message += stringf("n%d", ref.arg(i).index());
255
+ }
256
+ log("%s)\n", message);
257
+ if (ref.has_sparse_attr())
258
+ log("// wire %s\n", PooledName(design, ref.sparse_attr()).unescape());
259
+ log("// was #%d %s\n", ref.attr(), log_signal(queue[ref.attr()]));
260
+ }
261
+
262
+ for (auto const &key : compute_graph.keys())
263
+ {
264
+ log("return %d as %s \n", key.second, PooledName(design, key.first).unescape());
265
+ }
266
+ }
267
+ log("Plugin test passed!\n");
268
+ }
269
+ } ExampleDtPass;
270
+
271
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/exec.cc ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 - 2020 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/log_help.h"
22
+ #include <cstdio>
23
+ #include <regex>
24
+
25
+ #if defined(_WIN32)
26
+ # include <csignal>
27
+ # define WIFEXITED(x) 1
28
+ # define WIFSIGNALED(x) 0
29
+ # define WIFSTOPPED(x) 0
30
+ # define WEXITSTATUS(x) ((x) & 0xff)
31
+ # define WTERMSIG(x) SIGTERM
32
+ # define WSTOPSIG(x) 0
33
+ #else
34
+ # include <sys/wait.h>
35
+ #endif
36
+
37
+ USING_YOSYS_NAMESPACE
38
+ PRIVATE_NAMESPACE_BEGIN
39
+
40
+ struct ExecPass : public Pass {
41
+ ExecPass() : Pass("exec", "execute commands in the operating system shell") { }
42
+ bool formatted_help() override {
43
+ auto *help = PrettyHelp::get_current();
44
+ help->set_group("passes/status");
45
+ return false;
46
+ }
47
+ void help() override
48
+ {
49
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
50
+ log("\n");
51
+ log(" exec [options] -- [command]\n");
52
+ log("\n");
53
+ log("Execute a command in the operating system shell. All supplied arguments are\n");
54
+ log("concatenated and passed as a command to popen(3). Whitespace is not guaranteed\n");
55
+ log("to be preserved, even if quoted. stdin and stderr are not connected, while\n");
56
+ log("stdout is logged unless the \"-q\" option is specified.\n");
57
+ log("\n");
58
+ log("\n");
59
+ log(" -q\n");
60
+ log(" Suppress stdout and stderr from subprocess\n");
61
+ log("\n");
62
+ log(" -expect-return <int>\n");
63
+ log(" Generate an error if popen() does not return specified value.\n");
64
+ log(" May only be specified once; the final specified value is controlling\n");
65
+ log(" if specified multiple times.\n");
66
+ log("\n");
67
+ log(" -expect-stdout <regex>\n");
68
+ log(" Generate an error if the specified regex does not match any line\n");
69
+ log(" in subprocess's stdout. May be specified multiple times.\n");
70
+ log("\n");
71
+ log(" -not-expect-stdout <regex>\n");
72
+ log(" Generate an error if the specified regex matches any line\n");
73
+ log(" in subprocess's stdout. May be specified multiple times.\n");
74
+ log("\n");
75
+ log("\n");
76
+ log(" Example: exec -q -expect-return 0 -- echo \"bananapie\" | grep \"nana\"\n");
77
+ log("\n");
78
+ log("\n");
79
+ }
80
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
81
+ {
82
+ std::string cmd = "";
83
+ char buf[1024] = {};
84
+ std::string linebuf = "";
85
+ bool flag_cmd = false;
86
+ bool flag_quiet = false;
87
+ bool flag_expect_return = false;
88
+ int expect_return_value = 0;
89
+ bool flag_expect_stdout = false;
90
+ struct expect_stdout_elem {
91
+ bool matched;
92
+ bool polarity; //true: this regex must match at least one line
93
+ //false: this regex must not match any line
94
+ std::string str;
95
+ std::regex re;
96
+
97
+ expect_stdout_elem() : matched(false), polarity(true), str(), re(){};
98
+ };
99
+ std::vector<expect_stdout_elem> expect_stdout;
100
+
101
+ if(args.size() == 0)
102
+ log_cmd_error("No command provided.\n");
103
+
104
+ for(size_t argidx = 1; argidx < args.size(); ++argidx) {
105
+ if (flag_cmd) {
106
+ cmd += args[argidx] + (argidx != (args.size() - 1)? " " : "");
107
+ } else {
108
+ if (args[argidx] == "--")
109
+ flag_cmd = true;
110
+ else if (args[argidx] == "-q")
111
+ flag_quiet = true;
112
+ else if (args[argidx] == "-expect-return") {
113
+ flag_expect_return = true;
114
+ ++argidx;
115
+ if (argidx >= args.size())
116
+ log_cmd_error("No expected return value specified.\n");
117
+
118
+ expect_return_value = atoi(args[argidx].c_str());
119
+ } else if (args[argidx] == "-expect-stdout") {
120
+ flag_expect_stdout = true;
121
+ ++argidx;
122
+ if (argidx >= args.size())
123
+ log_cmd_error("No expected regular expression specified.\n");
124
+
125
+ try{
126
+ expect_stdout_elem x;
127
+ x.str = args[argidx];
128
+ x.re = YS_REGEX_COMPILE(args[argidx]);
129
+ expect_stdout.push_back(x);
130
+ } catch (const std::regex_error& e) {
131
+ log_cmd_error("Error in regex expression '%s' !\n", args[argidx]);
132
+ }
133
+ } else if (args[argidx] == "-not-expect-stdout") {
134
+ flag_expect_stdout = true;
135
+ ++argidx;
136
+ if (argidx >= args.size())
137
+ log_cmd_error("No expected regular expression specified.\n");
138
+
139
+ try{
140
+ expect_stdout_elem x;
141
+ x.str = args[argidx];
142
+ x.re = YS_REGEX_COMPILE(args[argidx]);
143
+ x.polarity = false;
144
+ expect_stdout.push_back(x);
145
+ } catch (const std::regex_error& e) {
146
+ log_cmd_error("Error in regex expression '%s' !\n", args[argidx]);
147
+ }
148
+
149
+ } else
150
+ log_cmd_error("Unknown option \"%s\" or \"--\" doesn\'t precede command.\n", args[argidx]);
151
+ }
152
+ }
153
+
154
+ log_header(design, "Executing command \"%s\".\n", cmd);
155
+ log_push();
156
+
157
+ fflush(stdout);
158
+ bool keep_reading = true;
159
+ int status = 0;
160
+ int retval = 0;
161
+
162
+ FILE *f = popen(cmd.c_str(), "r");
163
+ if (f == nullptr)
164
+ log_cmd_error("errno %d after popen() returned NULL.\n", errno);
165
+ while (keep_reading) {
166
+ keep_reading = (fgets(buf, sizeof(buf), f) != nullptr);
167
+ linebuf += buf;
168
+ memset(buf, 0, sizeof(buf));
169
+
170
+ auto pos = linebuf.find('\n');
171
+ while (pos != std::string::npos) {
172
+ std::string line = linebuf.substr(0, pos);
173
+ linebuf.erase(0, pos + 1);
174
+ if (!flag_quiet)
175
+ log("%s\n", line);
176
+
177
+ if (flag_expect_stdout)
178
+ for(auto &x : expect_stdout)
179
+ if (std::regex_search(line, x.re))
180
+ x.matched = true;
181
+
182
+ pos = linebuf.find('\n');
183
+ }
184
+ }
185
+ status = pclose(f);
186
+
187
+ if(WIFEXITED(status)) {
188
+ retval = WEXITSTATUS(status);
189
+ }
190
+ else if(WIFSIGNALED(status)) {
191
+ retval = WTERMSIG(status);
192
+ }
193
+ else if(WIFSTOPPED(status)) {
194
+ retval = WSTOPSIG(status);
195
+ }
196
+
197
+ if (flag_expect_return && retval != expect_return_value)
198
+ log_cmd_error("Return value %d did not match expected return value %d.\n", retval, expect_return_value);
199
+
200
+ if (flag_expect_stdout)
201
+ for (auto &x : expect_stdout)
202
+ if (x.polarity ^ x.matched)
203
+ log_cmd_error("Command stdout did%s have a line matching given regex \"%s\".\n", (x.polarity? " not" : ""), x.str);
204
+
205
+ log_pop();
206
+ }
207
+ } ExecPass;
208
+
209
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/future.cc ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2023 Jannis Harder <jix@yosyshq.com> <me@jix.one>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/celltypes.h"
21
+ #include "kernel/ff.h"
22
+ #include "kernel/ffinit.h"
23
+ #include "kernel/modtools.h"
24
+ #include "kernel/sigtools.h"
25
+ #include "kernel/utils.h"
26
+ #include "kernel/yosys.h"
27
+ #include "kernel/log_help.h"
28
+ #include <deque>
29
+
30
+ USING_YOSYS_NAMESPACE
31
+ PRIVATE_NAMESPACE_BEGIN
32
+
33
+ struct FutureOptions {
34
+ };
35
+
36
+ struct FutureWorker {
37
+ Module *module;
38
+ FutureOptions options;
39
+ ModWalker modwalker;
40
+ SigMap &sigmap;
41
+ FfInitVals initvals;
42
+
43
+ dict<SigBit, SigBit> future_ff_signals;
44
+
45
+ FutureWorker(Module *module, FutureOptions options) :
46
+ module(module), options(options), modwalker(module->design), sigmap(modwalker.sigmap)
47
+ {
48
+ modwalker.setup(module);
49
+ initvals.set(&modwalker.sigmap, module);
50
+
51
+ std::vector<Cell *> replaced_cells;
52
+ for (auto cell : module->selected_cells()) {
53
+ if (cell->type != ID($future_ff))
54
+ continue;
55
+
56
+ module->connect(cell->getPort(ID::Y), future_ff(cell->getPort(ID::A)));
57
+ replaced_cells.push_back(cell);
58
+ }
59
+
60
+ for (auto cell : replaced_cells) {
61
+ module->remove(cell);
62
+ }
63
+ }
64
+
65
+ SigSpec future_ff(SigSpec sig)
66
+ {
67
+ for (auto &bit : sig) {
68
+ bit = future_ff(bit);
69
+ }
70
+ return sig;
71
+ }
72
+
73
+ SigBit future_ff(SigBit bit)
74
+ {
75
+ if (!bit.is_wire())
76
+ return bit;
77
+
78
+ auto found = future_ff_signals.find(bit);
79
+ if (found != future_ff_signals.end())
80
+ return found->second;
81
+
82
+ auto found_driver = modwalker.signal_drivers.find(bit);
83
+ if (found_driver == modwalker.signal_drivers.end() || found_driver->second.size() < 1)
84
+ log_error("No driver for future_ff target signal %s found\n", log_signal(bit));
85
+ if (found_driver->second.size() > 1)
86
+ log_error("Found multiple drivers for future_ff target signal %s\n", log_signal(bit));
87
+ auto driver = *found_driver->second.begin();
88
+ if (!driver.cell->is_builtin_ff() && driver.cell->type != ID($anyinit))
89
+ log_error("Driver for future_ff target signal %s has non-FF cell type %s\n", log_signal(bit), driver.cell->type.unescape());
90
+
91
+ FfData ff(&initvals, driver.cell);
92
+
93
+ if (!ff.has_clk && !ff.has_gclk)
94
+ log_error("Driver for future_ff target signal %s has cell type %s, which is not clocked\n", log_signal(bit),
95
+ driver.cell->type.unescape());
96
+
97
+ ff.unmap_ce_srst();
98
+
99
+ // We insert all bits into the mapping, because unmap_ce_srst might
100
+ // have removed the cell which is still present in the modwalker data.
101
+ // By inserting all bits driven by th FF we ensure that we'll never use
102
+ // that stale modwalker data again.
103
+
104
+ for (int i = 0; i < ff.width; ++i) {
105
+ future_ff_signals.emplace(ff.sig_q[i], ff.sig_d[i]);
106
+ }
107
+
108
+ return future_ff_signals.at(bit);
109
+ }
110
+ };
111
+
112
+ struct FuturePass : public Pass {
113
+ FuturePass() : Pass("future", "resolve future sampled value functions") {}
114
+ bool formatted_help() override {
115
+ auto *help = PrettyHelp::get_current();
116
+ help->set_group("formal");
117
+ return false;
118
+ }
119
+ void help() override
120
+ {
121
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
122
+ log("\n");
123
+ log(" future [options] [selection]\n");
124
+ log("\n");
125
+ }
126
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
127
+ {
128
+ FutureOptions options;
129
+
130
+ log_header(design, "Executing FUTURE pass.\n");
131
+
132
+ size_t argidx;
133
+ for (argidx = 1; argidx < args.size(); argidx++) {
134
+
135
+ break;
136
+ }
137
+
138
+ extra_args(args, argidx, design);
139
+
140
+ for (auto module : design->selected_modules()) {
141
+ FutureWorker worker(module, options);
142
+ }
143
+ }
144
+ } FuturePass;
145
+
146
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/glift.cc ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2020 Alberto Gonzalez <boqwxp@airmail.cc>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/utils.h"
21
+ #include "kernel/yosys.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct GliftWorker {
28
+ private:
29
+ bool is_top_module = false;
30
+ bool opt_create_precise_model = false, opt_create_imprecise_model = false, opt_create_instrumented_model = false;
31
+ bool opt_taintconstants = false, opt_keepoutputs = false, opt_simplecostmodel = false, opt_nocostmodel = false;
32
+ bool opt_instrumentmore = false;
33
+ std::vector<RTLIL::Wire *> new_taint_outputs;
34
+ std::vector<std::pair<RTLIL::SigSpec, RTLIL::IdString>> meta_mux_selects;
35
+ RTLIL::Module *module = nullptr;
36
+
37
+ const IdString cost_model_wire_name = ID::__glift_weight;
38
+ const IdString glift_attribute_name = ID::glift;
39
+
40
+
41
+ RTLIL::SigSpec get_corresponding_taint_signal(RTLIL::SigSpec sig) {
42
+ RTLIL::SigSpec ret;
43
+
44
+ //Get the connected wire for the cell port:
45
+ log_assert(sig.is_wire() || sig.is_fully_const());
46
+ log_assert(sig.is_wire() || sig.is_fully_const());
47
+
48
+ //Get a SigSpec for the corresponding taint signal for the cell port, creating one if necessary:
49
+ if (sig.is_wire()) {
50
+ IdString taint_name_ref = module->twines().add(sig.as_wire()->name.str() + "_t");
51
+ RTLIL::Wire *w = module->wire(taint_name_ref);
52
+ if (w == nullptr) w = module->addWire(sig.as_wire()->name.str() + "_t", 1);
53
+ ret = w;
54
+ }
55
+ else if (sig.is_fully_const() && opt_taintconstants)
56
+ ret = RTLIL::State::S1;
57
+ else if (sig.is_fully_const())
58
+ ret = RTLIL::State::S0;
59
+ else
60
+ log_cmd_error("Cell port SigSpec has unexpected type.\n");
61
+
62
+ //Finally, if the cell port was a module input or output, make sure the corresponding taint signal is marked, too:
63
+ if(sig.is_wire() && sig.as_wire()->port_input)
64
+ ret.as_wire()->port_input = true;
65
+ if(sig.is_wire() && sig.as_wire()->port_output)
66
+ new_taint_outputs.push_back(ret.as_wire());
67
+
68
+ return ret;
69
+ }
70
+
71
+ void add_precise_GLIFT_logic(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) {
72
+ //AKA AN2_SH2 or OR2_SH2
73
+ bool is_and = cell->type.in(ID($_AND_), ID($_NAND_));
74
+ RTLIL::SigSpec n_port_a = module->LogicNot(cell->name.str() + "_t_1_1", port_a, false, cell->get_src_attribute());
75
+ RTLIL::SigSpec n_port_b = module->LogicNot(cell->name.str() + "_t_1_2", port_b, false, cell->get_src_attribute());
76
+ auto subexpr1 = module->And(cell->name.str() + "_t_1_3", is_and? port_a : n_port_a, port_b_taint, false, cell->get_src_attribute());
77
+ auto subexpr2 = module->And(cell->name.str() + "_t_1_4", is_and? port_b : n_port_b, port_a_taint, false, cell->get_src_attribute());
78
+ auto subexpr3 = module->And(cell->name.str() + "_t_1_5", port_a_taint, port_b_taint, false, cell->get_src_attribute());
79
+ auto subexpr4 = module->Or(cell->name.str() + "_t_1_6", subexpr1, subexpr2, false, cell->get_src_attribute());
80
+ module->addOr(cell->name.str() + "_t_1_7", subexpr4, subexpr3, port_y_taint, false, cell->get_src_attribute());
81
+ }
82
+
83
+ void add_imprecise_GLIFT_logic_1(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) {
84
+ //AKA AN2_SH3 or OR2_SH3
85
+ bool is_and = cell->type.in(ID($_AND_), ID($_NAND_));
86
+ RTLIL::SigSpec n_port_a = module->LogicNot(cell->name.str() + "_t_2_1", port_a, false, cell->get_src_attribute());
87
+ auto subexpr1 = module->And(cell->name.str() + "_t_2_2", is_and? port_b : n_port_a, is_and? port_a_taint : port_b_taint, false, cell->get_src_attribute());
88
+ module->addOr(cell->name.str() + "_t_2_3", is_and? port_b_taint : port_a_taint, subexpr1, port_y_taint, false, cell->get_src_attribute());
89
+ }
90
+
91
+ void add_imprecise_GLIFT_logic_2(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) {
92
+ //AKA AN2_SH4 or OR2_SH4
93
+ bool is_and = cell->type.in(ID($_AND_), ID($_NAND_));
94
+ RTLIL::SigSpec n_port_b = module->LogicNot(cell->name.str() + "_t_3_1", port_b, false, cell->get_src_attribute());
95
+ auto subexpr1 = module->And(cell->name.str() + "_t_3_2", is_and? port_a : n_port_b, is_and? port_b_taint : port_a_taint, false, cell->get_src_attribute());
96
+ module->addOr(cell->name.str() + "_t_3_3", is_and? port_a_taint : port_b_taint, subexpr1, port_y_taint, false, cell->get_src_attribute());
97
+ }
98
+
99
+ void add_imprecise_GLIFT_logic_3(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) {
100
+ //AKA AN2_SH5 or OR2_SH5 or XR2_SH2
101
+ module->addOr(cell->name.str() + "_t_4_1", port_a_taint, port_b_taint, port_y_taint, false, cell->get_src_attribute());
102
+ }
103
+
104
+ void add_imprecise_GLIFT_logic_4(RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_y_taint) {
105
+ module->connect(port_y_taint, port_a_taint);
106
+ }
107
+
108
+ void add_imprecise_GLIFT_logic_5(RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) {
109
+ module->connect(port_y_taint, port_b_taint);
110
+ }
111
+
112
+ void add_imprecise_GLIFT_logic_6(RTLIL::SigSpec &port_y_taint) {
113
+ module->connect(port_y_taint, RTLIL::Const(1, 1));
114
+ }
115
+
116
+ void add_imprecise_GLIFT_logic_7(RTLIL::SigSpec &port_y_taint) {
117
+ module->connect(port_y_taint, RTLIL::Const(0, 1));
118
+ }
119
+
120
+ void add_precise_GLIFT_mux(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_s, RTLIL::SigSpec &port_s_taint, RTLIL::SigSpec &port_y_taint) {
121
+ //S&At | ~S&Bt | ~A&B&St | A&~B&St | At&St | Bt&St
122
+ RTLIL::SigSpec n_port_a = module->LogicNot(cell->name.str() + "_t_4_1", port_a, false, cell->get_src_attribute());
123
+ RTLIL::SigSpec n_port_b = module->LogicNot(cell->name.str() + "_t_4_2", port_b, false, cell->get_src_attribute());
124
+ RTLIL::SigSpec n_port_s = module->LogicNot(cell->name.str() + "_t_4_3", port_s, false, cell->get_src_attribute());
125
+ auto subexpr1 = module->And(cell->name.str() + "_t_4_4", port_s, port_a_taint, false, cell->get_src_attribute());
126
+ auto subexpr2 = module->And(cell->name.str() + "_t_4_5", n_port_s, port_b_taint, false, cell->get_src_attribute());
127
+ auto subexpr3 = module->And(cell->name.str() + "_t_4_6", n_port_a, port_b, false, cell->get_src_attribute());
128
+ auto subexpr4 = module->And(cell->name.str() + "_t_4_7", subexpr3, port_s_taint, false, cell->get_src_attribute());
129
+ auto subexpr5 = module->And(cell->name.str() + "_t_4_8", port_a, n_port_b, false, cell->get_src_attribute());
130
+ auto subexpr6 = module->And(cell->name.str() + "_t_4_9", subexpr5, port_s_taint, false, cell->get_src_attribute());
131
+ auto subexpr7 = module->And(cell->name.str() + "_t_4_10", port_a_taint, port_s_taint, false, cell->get_src_attribute());
132
+ auto subexpr8 = module->And(cell->name.str() + "_t_4_11", port_b_taint, port_s_taint, false, cell->get_src_attribute());
133
+ auto subexpr9 = module->Or(cell->name.str() + "_t_4_12", subexpr1, subexpr2, false, cell->get_src_attribute());
134
+ auto subexpr10 = module->Or(cell->name.str() + "_t_4_13", subexpr4, subexpr6, false, cell->get_src_attribute());
135
+ auto subexpr11 = module->Or(cell->name.str() + "_t_4_14", subexpr7, subexpr8, false, cell->get_src_attribute());
136
+ auto subexpr12 = module->Or(cell->name.str() + "_t_4_15", subexpr9, subexpr10, false, cell->get_src_attribute());
137
+ module->addOr(cell->name.str() + "_t_4_16", subexpr11, subexpr12, port_y_taint, false, cell->get_src_attribute());
138
+ }
139
+
140
+ RTLIL::SigSpec score_metamux_select(const RTLIL::SigSpec &metamux_select, const RTLIL::IdString celltype) {
141
+ log_assert(metamux_select.is_wire());
142
+
143
+ if (opt_simplecostmodel) {
144
+ //The complex model is an area model, so a lower score should mean smaller.
145
+ //In this case, a nonzero hole metamux select value means less logic.
146
+ //Thus we should invert the ReduceOr over the metamux_select signal.
147
+ RTLIL::SigSpec pmux_select = module->ReduceOr(metamux_select.as_wire()->name.str() + "_nonzero", metamux_select);
148
+ return module->Pmux(NEW_ID, RTLIL::Const(1), RTLIL::Const(0), pmux_select, metamux_select.as_wire()->get_src_attribute());
149
+ } else {
150
+ auto select_width = metamux_select.as_wire()->width;
151
+
152
+ std::vector<RTLIL::Const> costs;
153
+ if (celltype == ID($_AND_) || celltype == ID($_OR_)) {
154
+ costs = {5, 2, 2, 1, 0, 0, 0, 0};
155
+ log_assert(select_width == 2 || select_width == 3);
156
+ log_assert(opt_instrumentmore || select_width == 2);
157
+ log_assert(!opt_instrumentmore || select_width == 3);
158
+ }
159
+ else if (celltype == ID($_XOR_) || celltype == ID($_XNOR_)) {
160
+ costs = {1, 0, 0, 0};
161
+ log_assert(select_width == 2);
162
+ }
163
+
164
+ std::vector<RTLIL::SigSpec> next_pmux_y_ports, pmux_y_ports(costs.begin(), costs.begin() + exp2(select_width));
165
+ for (auto i = 0; pmux_y_ports.size() > 1; ++i) {
166
+ for (auto j = 0; j+1 < GetSize(pmux_y_ports); j += 2) {
167
+ next_pmux_y_ports.emplace_back(module->Pmux(stringf("%s_mux_%d_%d", metamux_select.as_wire()->name, i, j), pmux_y_ports[j], pmux_y_ports[j+1], metamux_select[GetSize(metamux_select) - 1 - i], metamux_select.as_wire()->get_src_attribute()));
168
+ }
169
+ if (GetSize(pmux_y_ports) % 2 == 1)
170
+ next_pmux_y_ports.push_back(pmux_y_ports[GetSize(pmux_y_ports) - 1]);
171
+ pmux_y_ports.swap(next_pmux_y_ports);
172
+ next_pmux_y_ports.clear();
173
+ }
174
+
175
+ log_assert(pmux_y_ports.size() == 1);
176
+ return pmux_y_ports[0];
177
+ }
178
+ }
179
+
180
+ void create_glift_logic() {
181
+ if (module->get_bool_attribute(glift_attribute_name))
182
+ return;
183
+
184
+ std::vector<RTLIL::SigSig> connections(module->connections());
185
+
186
+ for(auto &cell : module->cells().to_vector()) {
187
+ if (!cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_MUX_), ID($_NMUX_), ID($_NOT_), ID($anyconst), ID($allconst), ID($assume), ID($assert)) && module->design->module(cell->type) == nullptr) {
188
+ log_cmd_error("Unsupported cell type \"%s\" found. Run `techmap` first.\n", cell->type);
189
+ }
190
+ if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_))) {
191
+ const unsigned int A = 0, B = 1, Y = 2;
192
+ const unsigned int NUM_PORTS = 3;
193
+ RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::B), cell->getPort(ID::Y)};
194
+ RTLIL::SigSpec port_taints[NUM_PORTS];
195
+
196
+ if (ports[A].size() != 1 || ports[B].size() != 1 || ports[Y].size() != 1)
197
+ log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n");
198
+ for (unsigned int i = 0; i < NUM_PORTS; ++i)
199
+ port_taints[i] = get_corresponding_taint_signal(ports[i]);
200
+
201
+ if (opt_create_precise_model)
202
+ add_precise_GLIFT_logic(cell, ports[A], port_taints[A], ports[B], port_taints[B], port_taints[Y]);
203
+ else if (opt_create_imprecise_model)
204
+ add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], port_taints[Y]);
205
+ else if (opt_create_instrumented_model) {
206
+ std::vector<RTLIL::SigSpec> taint_version;
207
+ int num_versions = opt_instrumentmore? 8 : 4;
208
+
209
+ for (auto i = 1; i <= num_versions; ++i)
210
+ taint_version.emplace_back(RTLIL::SigSpec(module->addWire(stringf("%s_y%d", cell->name, i), 1)));
211
+
212
+ for (auto i = 0; i < num_versions; ++i) {
213
+ switch(i) {
214
+ case 0: add_precise_GLIFT_logic(cell, ports[A], port_taints[A], ports[B], port_taints[B], taint_version[i]);
215
+ break;
216
+ case 1: add_imprecise_GLIFT_logic_1(cell, ports[A], port_taints[A], ports[B], port_taints[B], taint_version[i]);
217
+ break;
218
+ case 2: add_imprecise_GLIFT_logic_2(cell, ports[A], port_taints[A], ports[B], port_taints[B], taint_version[i]);
219
+ break;
220
+ case 3: add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], taint_version[i]);
221
+ break;
222
+ case 4: add_imprecise_GLIFT_logic_4(port_taints[A], taint_version[i]);
223
+ break;
224
+ case 5: add_imprecise_GLIFT_logic_5(port_taints[B], taint_version[i]);
225
+ break;
226
+ case 6: add_imprecise_GLIFT_logic_6(taint_version[i]);
227
+ break;
228
+ case 7: add_imprecise_GLIFT_logic_7(taint_version[i]);
229
+ break;
230
+ default: log_assert(false);
231
+ }
232
+ }
233
+
234
+ auto select_width = log2(num_versions);
235
+ log_assert(exp2(select_width) == num_versions);
236
+ RTLIL::SigSpec meta_mux_select(module->addWire(cell->name.str() + "_sel", select_width));
237
+ meta_mux_selects.push_back(make_pair(meta_mux_select, cell->type));
238
+ module->connect(meta_mux_select, module->Anyconst(cell->name.str() + "_hole", select_width, cell->get_src_attribute()));
239
+
240
+ std::vector<RTLIL::SigSpec> next_meta_mux_y_ports, meta_mux_y_ports(taint_version);
241
+ for (auto i = 0; meta_mux_y_ports.size() > 1; ++i) {
242
+ for (auto j = 0; j+1 < GetSize(meta_mux_y_ports); j += 2) {
243
+ next_meta_mux_y_ports.emplace_back(module->Mux(stringf("%s_mux_%d_%d", cell->name, i, j), meta_mux_y_ports[j], meta_mux_y_ports[j+1], meta_mux_select[GetSize(meta_mux_select) - 1 - i]));
244
+ }
245
+ if (GetSize(meta_mux_y_ports) % 2 == 1)
246
+ next_meta_mux_y_ports.push_back(meta_mux_y_ports[GetSize(meta_mux_y_ports) - 1]);
247
+ meta_mux_y_ports.swap(next_meta_mux_y_ports);
248
+ next_meta_mux_y_ports.clear();
249
+ }
250
+ log_assert(meta_mux_y_ports.size() == 1);
251
+ module->connect(port_taints[Y], meta_mux_y_ports[0]);
252
+ }
253
+ else log_cmd_error("This is a bug (1).\n");
254
+ }
255
+ else if (cell->type.in(ID($_XOR_), ID($_XNOR_))) {
256
+ const unsigned int A = 0, B = 1, Y = 2;
257
+ const unsigned int NUM_PORTS = 3;
258
+ RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::B), cell->getPort(ID::Y)};
259
+ RTLIL::SigSpec port_taints[NUM_PORTS];
260
+
261
+ if (ports[A].size() != 1 || ports[B].size() != 1 || ports[Y].size() != 1)
262
+ log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n");
263
+ for (unsigned int i = 0; i < NUM_PORTS; ++i)
264
+ port_taints[i] = get_corresponding_taint_signal(ports[i]);
265
+
266
+ if (opt_create_precise_model || opt_create_imprecise_model)
267
+ add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], port_taints[Y]);
268
+ else if (opt_create_instrumented_model) {
269
+ std::vector<RTLIL::SigSpec> taint_version;
270
+ int num_versions = 4;
271
+ auto select_width = log2(num_versions);
272
+ log_assert(exp2(select_width) == num_versions);
273
+
274
+ for (auto i = 1; i <= num_versions; ++i)
275
+ taint_version.emplace_back(RTLIL::SigSpec(module->addWire(stringf("%s_y%d", cell->name, i), 1)));
276
+
277
+ for (auto i = 0; i < num_versions; ++i) {
278
+ switch(i) {
279
+ case 0: add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], taint_version[i]);
280
+ break;
281
+ case 1: add_imprecise_GLIFT_logic_4(port_taints[A], taint_version[i]);
282
+ break;
283
+ case 2: add_imprecise_GLIFT_logic_5(port_taints[B], taint_version[i]);
284
+ break;
285
+ case 3: add_imprecise_GLIFT_logic_6(taint_version[i]);
286
+ break;
287
+ default: log_assert(false);
288
+ }
289
+ }
290
+
291
+ RTLIL::SigSpec meta_mux_select(module->addWire(cell->name.str() + "_sel", select_width));
292
+ meta_mux_selects.push_back(make_pair(meta_mux_select, cell->type));
293
+ module->connect(meta_mux_select, module->Anyconst(cell->name.str() + "_hole", select_width, cell->get_src_attribute()));
294
+
295
+ std::vector<RTLIL::SigSpec> next_meta_mux_y_ports, meta_mux_y_ports(taint_version);
296
+ for (auto i = 0; meta_mux_y_ports.size() > 1; ++i) {
297
+ for (auto j = 0; j+1 < GetSize(meta_mux_y_ports); j += 2) {
298
+ next_meta_mux_y_ports.emplace_back(module->Mux(stringf("%s_mux_%d_%d", cell->name, i, j), meta_mux_y_ports[j], meta_mux_y_ports[j+1], meta_mux_select[GetSize(meta_mux_select) - 1 - i]));
299
+ }
300
+ if (GetSize(meta_mux_y_ports) % 2 == 1)
301
+ next_meta_mux_y_ports.push_back(meta_mux_y_ports[GetSize(meta_mux_y_ports) - 1]);
302
+ meta_mux_y_ports.swap(next_meta_mux_y_ports);
303
+ next_meta_mux_y_ports.clear();
304
+ }
305
+ log_assert(meta_mux_y_ports.size() == 1);
306
+ module->connect(port_taints[Y], meta_mux_y_ports[0]);
307
+ }
308
+ else log_cmd_error("This is a bug (2).\n");
309
+
310
+ }
311
+ else if (cell->type.in(ID($_MUX_), ID($_NMUX_))) {
312
+ const unsigned int A = 0, B = 1, S = 2, Y = 3;
313
+ const unsigned int NUM_PORTS = 4;
314
+ RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::B), cell->getPort(ID::S), cell->getPort(ID::Y)};
315
+ RTLIL::SigSpec port_taints[NUM_PORTS];
316
+
317
+ if (ports[A].size() != 1 || ports[B].size() != 1 || ports[S].size() != 1 || ports[Y].size() != 1)
318
+ log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n");
319
+ for (unsigned int i = 0; i < NUM_PORTS; ++i)
320
+ port_taints[i] = get_corresponding_taint_signal(ports[i]);
321
+
322
+ add_precise_GLIFT_mux(cell, ports[A], port_taints[A], ports[B], port_taints[B], ports[S], port_taints[S], port_taints[Y]);
323
+ }
324
+ else if (cell->type.in(ID($_NOT_))) {
325
+ const unsigned int A = 0, Y = 1;
326
+ const unsigned int NUM_PORTS = 2;
327
+ RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::Y)};
328
+ RTLIL::SigSpec port_taints[NUM_PORTS];
329
+
330
+ if (ports[A].size() != 1 || ports[Y].size() != 1)
331
+ log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n");
332
+ for (unsigned int i = 0; i < NUM_PORTS; ++i)
333
+ port_taints[i] = get_corresponding_taint_signal(ports[i]);
334
+
335
+ if (cell->type == ID($_NOT_)) {
336
+ module->connect(port_taints[Y], port_taints[A]);
337
+ }
338
+ else log_cmd_error("This is a bug (3).\n");
339
+ }
340
+ else if (module->design->module(cell->type) != nullptr) {
341
+ //User cell type
342
+ //This function is called on modules according to topological order, so we do not need to
343
+ //recurse to GLIFT model the child module. However, we need to augment the ports list
344
+ //with taint signals and connect the new ports to the corresponding taint signals.
345
+ RTLIL::Module *cell_module_def = module->design->module(cell->type);
346
+ dict<RTLIL::IdString, RTLIL::SigSpec> orig_ports = cell->connections();
347
+ log("Adding cell %s\n", cell_module_def->name);
348
+ for (auto &it : orig_ports) {
349
+ RTLIL::SigSpec port = it.second;
350
+ RTLIL::SigSpec port_taint = get_corresponding_taint_signal(port);
351
+
352
+ log_assert(port_taint.is_wire());
353
+ log_assert(std::find(cell_module_def->ports.begin(), cell_module_def->ports.end(), port_taint.as_wire()->name) != cell_module_def->ports.end());
354
+ cell->setPort(port_taint.as_wire()->name, port_taint);
355
+ }
356
+ }
357
+ else log_cmd_error("This is a bug (4).\n");
358
+ } //end foreach cell in cells
359
+
360
+ for (auto &conn : connections) {
361
+ RTLIL::SigSpec first = get_corresponding_taint_signal(conn.first);
362
+ RTLIL::SigSpec second = get_corresponding_taint_signal(conn.second);
363
+
364
+ module->connect(first, second);
365
+
366
+ if(conn.second.is_wire() && conn.second.as_wire()->port_input)
367
+ second.as_wire()->port_input = true;
368
+ if(conn.first.is_wire() && conn.first.as_wire()->port_output)
369
+ new_taint_outputs.push_back(first.as_wire());
370
+ } //end foreach conn in connections
371
+
372
+ //Create a rough model of area by summing the (potentially simplified) "weight" score of each meta-mux select:
373
+ if (!opt_nocostmodel) {
374
+ std::vector<RTLIL::SigSpec> meta_mux_select_sums;
375
+ std::vector<RTLIL::SigSpec> meta_mux_select_sums_buf;
376
+ for (auto &it : meta_mux_selects) {
377
+ meta_mux_select_sums.emplace_back(score_metamux_select(it.first, it.second));
378
+ }
379
+ for (unsigned int i = 0; meta_mux_select_sums.size() > 1; ) {
380
+ meta_mux_select_sums_buf.clear();
381
+ for (i = 0; i + 1 < meta_mux_select_sums.size(); i += 2) {
382
+ meta_mux_select_sums_buf.push_back(module->Add(meta_mux_select_sums[i].as_wire()->name.str() + "_add", meta_mux_select_sums[i], meta_mux_select_sums[i+1], false));
383
+ }
384
+ if (meta_mux_select_sums.size() % 2 == 1)
385
+ meta_mux_select_sums_buf.push_back(meta_mux_select_sums[meta_mux_select_sums.size()-1]);
386
+ meta_mux_select_sums.swap(meta_mux_select_sums_buf);
387
+ }
388
+ if (meta_mux_select_sums.size() > 0) {
389
+ meta_mux_select_sums[0].as_wire()->set_bool_attribute(ID::minimize);
390
+ meta_mux_select_sums[0].as_wire()->set_bool_attribute(ID::keep);
391
+ module->rename(meta_mux_select_sums[0].as_wire(), cost_model_wire_name);
392
+ }
393
+ }
394
+
395
+ //Mark new module outputs:
396
+ for (auto &port_name : module->ports) {
397
+ RTLIL::Wire *port = module->wire(port_name);
398
+ log_assert(port != nullptr);
399
+ if (is_top_module && port->port_output && !opt_keepoutputs)
400
+ port->port_output = false;
401
+ }
402
+ for (auto &output : new_taint_outputs)
403
+ output->port_output = true;
404
+ module->fixup_ports(); //we have some new taint signals in the module interface
405
+ module->set_bool_attribute(glift_attribute_name, true);
406
+ }
407
+
408
+ public:
409
+ GliftWorker(RTLIL::Module *_module, bool _is_top_module, bool _opt_create_precise_model, bool _opt_create_imprecise_model, bool _opt_create_instrumented_model, bool _opt_taintconstants, bool _opt_keepoutputs, bool _opt_simplecostmodel, bool _opt_nocostmodel, bool _opt_instrumentmore) {
410
+ module = _module;
411
+ is_top_module = _is_top_module;
412
+ opt_create_precise_model = _opt_create_precise_model;
413
+ opt_create_imprecise_model = _opt_create_imprecise_model;
414
+ opt_create_instrumented_model = _opt_create_instrumented_model;
415
+ opt_taintconstants = _opt_taintconstants;
416
+ opt_keepoutputs = _opt_keepoutputs;
417
+ opt_simplecostmodel = _opt_simplecostmodel;
418
+ opt_nocostmodel = _opt_nocostmodel;
419
+ opt_instrumentmore = _opt_instrumentmore;
420
+
421
+ create_glift_logic();
422
+ }
423
+ };
424
+
425
+ struct GliftPass : public Pass {
426
+ GliftPass() : Pass("glift", "create GLIFT models and optimization problems") {}
427
+
428
+ bool formatted_help() override {
429
+ auto *help = PrettyHelp::get_current();
430
+ help->set_group("formal");
431
+ return false;
432
+ }
433
+
434
+ void help() override
435
+ {
436
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
437
+ log("\n");
438
+ log(" glift <command> [options] [selection]\n");
439
+ log("\n");
440
+ log("Augments the current or specified module with gate-level information flow \n");
441
+ log("tracking (GLIFT) logic using the \"constructive mapping\" approach. Also can set\n");
442
+ log("up QBF-SAT optimization problems in order to optimize GLIFT models or trade off\n");
443
+ log("precision and complexity.\n");
444
+ log("\n");
445
+ log("\n");
446
+ log("Commands:\n");
447
+ log("\n");
448
+ log(" -create-precise-model\n");
449
+ log(" Replaces the current or specified module with one that has corresponding\n");
450
+ log(" \"taint\" inputs, outputs, and internal nets along with precise taint\n");
451
+ log(" tracking logic. For example, precise taint tracking logic for an AND gate\n");
452
+ log(" is:\n");
453
+ log("\n");
454
+ log(" y_t = a & b_t | b & a_t | a_t & b_t\n");
455
+ log("\n");
456
+ log("\n");
457
+ log(" -create-imprecise-model\n");
458
+ log(" Replaces the current or specified module with one that has corresponding\n");
459
+ log(" \"taint\" inputs, outputs, and internal nets along with imprecise \"All OR\"\n");
460
+ log(" taint tracking logic:\n");
461
+ log("\n");
462
+ log(" y_t = a_t | b_t\n");
463
+ log("\n");
464
+ log("\n");
465
+ log(" -create-instrumented-model\n");
466
+ log(" Replaces the current or specified module with one that has corresponding\n");
467
+ log(" \"taint\" inputs, outputs, and internal nets along with 4 varying-precision\n");
468
+ log(" versions of taint tracking logic. Which version of taint tracking logic is\n");
469
+ log(" used for a given gate is determined by a MUX selected by an $anyconst cell.\n");
470
+ log(" By default, unless the `-no-cost-model` option is provided, an additional\n");
471
+ log(" wire named `__glift_weight` with the `keep` and `minimize` attributes is\n");
472
+ log(" added to the module along with pmuxes and adders to calculate a rough\n");
473
+ log(" estimate of the number of logic gates in the GLIFT model given an assignment\n");
474
+ log(" for the $anyconst cells. The four versions of taint tracking logic for an\n");
475
+ log(" AND gate are:\n");
476
+ log(" y_t = a & b_t | b & a_t | a_t & b_t (like `-create-precise-model`)\n");
477
+ log(" y_t = a_t | a & b_t\n");
478
+ log(" y_t = b_t | b & a_t\n");
479
+ log(" y_t = a_t | b_t (like `-create-imprecise-model`)\n");
480
+ log("\n");
481
+ log("\n");
482
+ log("Options:\n");
483
+ log("\n");
484
+ log(" -taint-constants\n");
485
+ log(" Constant values in the design are labeled as tainted.\n");
486
+ log(" (default: label constants as un-tainted)\n");
487
+ log("\n");
488
+ log(" -keep-outputs\n");
489
+ log(" Do not remove module outputs. Taint tracking outputs will appear in the\n");
490
+ log(" module ports alongside the orignal outputs.\n");
491
+ log(" (default: original module outputs are removed)\n");
492
+ log("\n");
493
+ log(" -simple-cost-model\n");
494
+ log(" Do not model logic area. Instead model the number of non-zero assignments to\n");
495
+ log(" $anyconsts. Taint tracking logic versions vary in their size, but all\n");
496
+ log(" reduced-precision versions are significantly smaller than the fully-precise\n");
497
+ log(" version. A non-zero $anyconst assignment means that reduced-precision taint\n");
498
+ log(" tracking logic was chosen for some gate. Only applicable in combination with\n");
499
+ log(" `-create-instrumented-model`. (default: use a complex model and give that\n");
500
+ log(" wire the \"keep\" and \"minimize\" attributes)\n");
501
+ log("\n");
502
+ log(" -no-cost-model\n");
503
+ log(" Do not model taint tracking logic area and do not create a `__glift_weight`\n");
504
+ log(" wire. Only applicable in combination with `-create-instrumented-model`.\n");
505
+ log(" (default: model area and give that wire the \"keep\" and \"minimize\"\n");
506
+ log(" attributes)\n");
507
+ log("\n");
508
+ log(" -instrument-more\n");
509
+ log(" Allow choice from more versions of (even simpler) taint tracking logic. A\n");
510
+ log(" total of 8 versions of taint tracking logic will be added per gate,\n");
511
+ log(" including the 4 versions from `-create-instrumented-model` and these\n");
512
+ log(" additional versions:\n");
513
+ log("\n");
514
+ log(" y_t = a_t\n");
515
+ log(" y_t = b_t\n");
516
+ log(" y_t = 1\n");
517
+ log(" y_t = 0\n");
518
+ log("\n");
519
+ log(" Only applicable in combination with `-create-instrumented-model`.\n");
520
+ log(" (default: do not add more versions of taint tracking logic.\n");
521
+ log("\n");
522
+ }
523
+
524
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
525
+ {
526
+ bool opt_create_precise_model = false, opt_create_imprecise_model = false, opt_create_instrumented_model = false;
527
+ bool opt_taintconstants = false, opt_keepoutputs = false, opt_simplecostmodel = false, opt_nocostmodel = false;
528
+ bool opt_instrumentmore = false;
529
+ log_header(design, "Executing GLIFT pass (creating and manipulating GLIFT models).\n");
530
+ std::vector<std::string>::size_type argidx;
531
+
532
+ for (argidx = 1; argidx < args.size(); argidx++) {
533
+ if (args[argidx] == "-create-precise-model") {
534
+ opt_create_precise_model = true;
535
+ continue;
536
+ }
537
+ if (args[argidx] == "-create-imprecise-model") {
538
+ opt_create_imprecise_model = true;
539
+ continue;
540
+ }
541
+ if (args[argidx] == "-create-instrumented-model") {
542
+ opt_create_instrumented_model = true;
543
+ continue;
544
+ }
545
+ if (args[argidx] == "-taint-constants") {
546
+ opt_taintconstants = true;
547
+ continue;
548
+ }
549
+ if (args[argidx] == "-keep-outputs") {
550
+ opt_keepoutputs = true;
551
+ continue;
552
+ }
553
+ if (args[argidx] == "-simple-cost-model") {
554
+ opt_simplecostmodel = true;
555
+ continue;
556
+ }
557
+ if (args[argidx] == "-no-cost-model") {
558
+ opt_nocostmodel = true;
559
+ continue;
560
+ }
561
+ if (args[argidx] == "-instrument-more") {
562
+ opt_instrumentmore = true;
563
+ continue;
564
+ }
565
+ break;
566
+ }
567
+ if(!opt_create_precise_model && !opt_create_imprecise_model && !opt_create_instrumented_model)
568
+ log_cmd_error("No command provided. See help for usage.\n");
569
+ if(static_cast<int>(opt_create_precise_model) + static_cast<int>(opt_create_imprecise_model) + static_cast<int>(opt_create_instrumented_model) != 1)
570
+ log_cmd_error("Only one command may be specified. See help for usage.\n");
571
+ if(opt_simplecostmodel && opt_nocostmodel)
572
+ log_cmd_error("Only one of `-simple-cost-model` and `-no-cost-model` may be specified. See help for usage.\n");
573
+ if((opt_simplecostmodel || opt_nocostmodel) && !opt_create_instrumented_model)
574
+ log_cmd_error("Options `-simple-cost-model` and `-no-cost-model` may only be used with `-create-instrumented-model`. See help for usage.\n");
575
+ extra_args(args, argidx, design);
576
+
577
+ if (GetSize(design->selected_modules()) == 0)
578
+ log_cmd_error("Can't operate on an empty selection!\n");
579
+
580
+ TopoSort<RTLIL::Module*, IdString::compare_ptr_by_name<RTLIL::Module>> topo_modules; //cribbed from passes/techmap/flatten.cc
581
+ auto worklist = design->selected_modules();
582
+ pool<RTLIL::IdString> non_top_modules;
583
+ while (!worklist.empty()) {
584
+ RTLIL::Module *module = *(worklist.begin());
585
+ worklist.erase(worklist.begin());
586
+ topo_modules.node(module);
587
+
588
+ for (auto cell : module->selected_cells()) {
589
+ RTLIL::Module *tpl = design->module(cell->type);
590
+ if (tpl != nullptr) {
591
+ if (!topo_modules.has_node(tpl))
592
+ worklist.push_back(tpl);
593
+ topo_modules.edge(tpl, module);
594
+ non_top_modules.insert(cell->type);
595
+ }
596
+ }
597
+ }
598
+
599
+ if (!topo_modules.sort())
600
+ log_cmd_error("Cannot handle recursive module instantiations.\n");
601
+
602
+ for (auto i = 0; i < GetSize(topo_modules.sorted); ++i) {
603
+ RTLIL::Module *module = topo_modules.sorted[i];
604
+ GliftWorker(module, !non_top_modules.count(module->name), opt_create_precise_model, opt_create_imprecise_model, opt_create_instrumented_model, opt_taintconstants, opt_keepoutputs, opt_simplecostmodel, opt_nocostmodel, opt_instrumentmore);
605
+ }
606
+ }
607
+ } GliftPass;
608
+
609
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/icell_liberty.cc ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "kernel/yosys.h"
2
+ #include "kernel/celltypes.h"
3
+ #include "kernel/newcelltypes.h"
4
+ #include "kernel/ff.h"
5
+
6
+ USING_YOSYS_NAMESPACE
7
+ PRIVATE_NAMESPACE_BEGIN
8
+
9
+ struct LibertyStubber {
10
+ CellTypes ct;
11
+ LibertyStubber() {
12
+ ct.setup();
13
+ ct.setup_internals_ff();
14
+ }
15
+ void liberty_prefix(std::ostream& f)
16
+ {
17
+ f << "/*\n";
18
+ f << stringf("\tModels interfaces of select Yosys internal cell.\n");
19
+ f << stringf("\tLikely contains INCORRECT POLARITIES.\n");
20
+ f << stringf("\tImpractical for any simulation, synthesis, or timing.\n");
21
+ f << stringf("\tIntended purely for SDC expansion.\n");
22
+ f << stringf("\tDo not microwave or tumble dry.\n");
23
+ f << stringf("\tGenerated by %s\n", yosys_maybe_version());
24
+ f << "*/\n";
25
+ f << "library (yosys) {\n";
26
+ f << "\tinput_threshold_pct_fall : 50;\n";
27
+ f << "\tinput_threshold_pct_rise : 50;\n";
28
+ f << "\toutput_threshold_pct_fall : 50;\n";
29
+ f << "\toutput_threshold_pct_rise : 50;\n";
30
+ f << "\tslew_lower_threshold_pct_fall : 1;\n";
31
+ f << "\tslew_lower_threshold_pct_rise : 1;\n";
32
+ f << "\tslew_upper_threshold_pct_fall : 99;\n";
33
+ f << "\tslew_upper_threshold_pct_rise : 99;\n";
34
+ }
35
+ void liberty_suffix(std::ostream& f)
36
+ {
37
+ f << "}\n";
38
+ }
39
+ struct LibertyItemizer {
40
+ std::ostream& f;
41
+ int indent;
42
+ LibertyItemizer(std::ostream& f) : f(f), indent(0) {};
43
+ void item(std::string key, std::string val)
44
+ {
45
+ f << std::string(indent, '\t') << key << " : \"" << val << "\";\n";
46
+ }
47
+ };
48
+ void liberty_flop(Module* base, Module* derived, std::ostream& f)
49
+ {
50
+ auto base_name = base->name.str().substr(1);
51
+ auto derived_name = derived->name.str().substr(1);
52
+
53
+ FfTypeData ffType(base->name);
54
+ LibertyItemizer i(f);
55
+
56
+ if (ffType.has_gclk) {
57
+ log_warning("Formal flip flop %s can't be modeled\n", base_name);
58
+ return;
59
+ }
60
+ if (ffType.has_ce) {
61
+ log_warning("DFFE %s can't be modeled\n", base_name);
62
+ return;
63
+ }
64
+
65
+ f << "\tcell (\"" << derived_name << "\") {\n";
66
+ auto& base_type = ct.cell_types[base->name];
67
+ i.indent = 3;
68
+ auto sorted_ports = derived->ports;
69
+ // Hack for CLK and C coming before Q does
70
+ auto cmp = [derived](IdString l, IdString r) { return derived->twines().str(l) < derived->twines().str(r); };
71
+ std::sort(sorted_ports.begin(), sorted_ports.end(), cmp);
72
+ std::string clock_pin_name = "";
73
+ for (auto x : sorted_ports) {
74
+ std::string port_name = derived->twines().unescaped_str(x);
75
+ bool is_input = base_type.inputs.count(x);
76
+ bool is_output = base_type.outputs.count(x);
77
+ f << "\t\tpin (" << port_name << ") {\n";
78
+ if (is_input && !is_output) {
79
+ i.item("direction", "input");
80
+ } else if (!is_input && is_output) {
81
+ i.item("direction", "output");
82
+ } else {
83
+ i.item("direction", "inout");
84
+ }
85
+ if (port_name == "CLK" || port_name == "C") {
86
+ i.item("clock", "true");
87
+ clock_pin_name = port_name;
88
+ }
89
+ if (port_name == "Q") {
90
+ i.item("function", "IQ");
91
+ f << "\t\t\ttiming () {\n";
92
+ i.indent++;
93
+ log_assert(clock_pin_name.size());
94
+ i.item("related_pin", clock_pin_name);
95
+ i.indent--;
96
+ f << "\t\t\t}\n";
97
+ }
98
+ f << "\t\t}\n";
99
+ }
100
+
101
+ f << "\t\tff (\"IQ\",\"IQ_N\") {\n";
102
+ i.indent = 3;
103
+ // TODO polarities?
104
+ if (ffType.has_clk) {
105
+ auto pin = ffType.is_fine ? "C" : "CLK";
106
+ i.item("clocked_on", pin);
107
+ }
108
+ if (ffType.has_arst) {
109
+ auto meaning = (ffType.val_arst == State::S1) ? "preset" : "clear";
110
+ auto pin = ffType.is_fine ? "R" : "ARST";
111
+ i.item(meaning, pin);
112
+ }
113
+ auto next_state = ffType.has_ce ? "D & EN" : "D";
114
+ i.item("next_state", next_state);
115
+ f << "\t\t}\n";
116
+ f << "\t}\n";
117
+ }
118
+ void liberty_cell(Module* base, Module* derived, std::ostream& f)
119
+ {
120
+ auto base_name = base->name.str().substr(1);
121
+ auto derived_name = derived->name.str().substr(1);
122
+ if (!ct.cell_types.count(base->name)) {
123
+ log_debug("skip skeleton for %s\n", base_name);
124
+ return;
125
+ }
126
+
127
+ if (StaticCellTypes::categories.is_ff(base->name))
128
+ return liberty_flop(base, derived, f);
129
+
130
+ auto& base_type = ct.cell_types[base->name];
131
+ f << "\tcell (\"" << derived_name << "\") {\n";
132
+ for (auto x : derived->ports) {
133
+ std::string port_name = derived->twines().unescaped_str(x);
134
+ bool is_input = base_type.inputs.count(x);
135
+ bool is_output = base_type.outputs.count(x);
136
+ f << "\t\tpin (" << port_name << ") {\n";
137
+ if (is_input && !is_output) {
138
+ f << "\t\t\tdirection : input;\n";
139
+ } else if (!is_input && is_output) {
140
+ f << "\t\t\tdirection : output;\n";
141
+ } else {
142
+ f << "\t\t\tdirection : inout;\n";
143
+ }
144
+ f << "\t\t}\n";
145
+ }
146
+ f << "\t}\n";
147
+ }
148
+ };
149
+
150
+ struct IcellLiberty : Pass {
151
+ IcellLiberty() : Pass("icell_liberty", "write Liberty interfaces for used internal cells") {}
152
+ void help() override
153
+ {
154
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
155
+ log("\n");
156
+ log(" icell_liberty <liberty_file>\n");
157
+ log("\n");
158
+ log("Write Liberty files modeling the interfaces of used internal cells.\n");
159
+ log("\n");
160
+ log("Models are not guaranteed to be logically sound.\n");
161
+ log("\n");
162
+ }
163
+ void execute(std::vector<std::string> args, RTLIL::Design *d) override
164
+ {
165
+ log_header(d, "Executing ICELL_LIBERTY pass.\n");
166
+
167
+ size_t argidx;
168
+ std::string liberty_filename;
169
+ auto liberty_file = std::make_unique<std::ofstream>();
170
+
171
+ for (argidx = 1; argidx < args.size(); argidx++) {
172
+ break;
173
+ }
174
+ if (argidx < args.size())
175
+ liberty_filename = args[argidx++];
176
+ else
177
+ log_cmd_error("no Liberty filename specified\n");
178
+
179
+ if (liberty_filename.size()) {
180
+ liberty_file->open(liberty_filename.c_str());
181
+ if (liberty_file->fail()) {
182
+ log_cmd_error("Can't open file `%s' for writing: %s\n", liberty_filename, strerror(errno));
183
+ }
184
+ }
185
+
186
+ pool<RTLIL::IdString> done;
187
+ LibertyStubber stubber = {};
188
+
189
+ stubber.liberty_prefix(*liberty_file);
190
+
191
+ for (auto module : d->selected_modules()) {
192
+ for (auto cell : module->selected_cells()) {
193
+ Module *inst_module = d->module(cell->type);
194
+ if (!inst_module || !inst_module->get_blackbox_attribute())
195
+ continue;
196
+ Module *base = inst_module;
197
+ IdString base_name_id = base->name;
198
+ if (!done.count(base_name_id)) {
199
+ stubber.liberty_cell(base, base, *liberty_file);
200
+ done.insert(base_name_id);
201
+ }
202
+ }
203
+ }
204
+
205
+ stubber.liberty_suffix(*liberty_file);
206
+ }
207
+ } IcellLiberty;
208
+
209
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/internal_stats.cc ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include <iterator>
21
+
22
+ #include "kernel/yosys.h"
23
+ #include "kernel/celltypes.h"
24
+ #include "passes/techmap/libparse.h"
25
+ #include "kernel/cost.h"
26
+ #include "frontends/ast/ast.h"
27
+ #include "libs/json11/json11.hpp"
28
+
29
+ #if defined(__APPLE__) && defined(__MACH__)
30
+ #include <mach/task.h>
31
+ #include <mach/mach_init.h>
32
+ #endif
33
+
34
+ USING_YOSYS_NAMESPACE
35
+ PRIVATE_NAMESPACE_BEGIN
36
+
37
+ std::optional<uint64_t> current_mem_bytes() {
38
+
39
+ #if defined(__APPLE__)
40
+ task_basic_info_64_data_t basicInfo;
41
+ mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
42
+ kern_return_t error = task_info(mach_task_self(), TASK_BASIC_INFO_64, (task_info_t)&basicInfo, &count);
43
+ if (error != KERN_SUCCESS) {
44
+ return {}; // Error getting task information
45
+ }
46
+ return basicInfo.resident_size; // Return RSS in KB
47
+
48
+ #elif defined(__linux__)
49
+ // Not all linux distributions have to have this file
50
+ std::ifstream statusFile("/proc/self/status");
51
+ std::string line;
52
+ while (std::getline(statusFile, line)) {
53
+ if (line.find("VmRSS:") == 0) {
54
+ std::istringstream iss(line);
55
+ std::string token;
56
+ // Skip prefix
57
+ iss >> token;
58
+ uint64_t rss;
59
+ iss >> rss;
60
+ return rss * 1024;
61
+ }
62
+ }
63
+ // Error reading /proc/self/status
64
+ return {};
65
+
66
+ #else
67
+ return {};
68
+ #endif
69
+ }
70
+
71
+ struct InternalStatsPass : public Pass {
72
+ InternalStatsPass() : Pass("internal_stats", "print internal statistics") {
73
+ experimental();
74
+ internal();
75
+ }
76
+ void help() override
77
+ {
78
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
79
+ log("Print internal statistics for developers (experimental)\n");
80
+ }
81
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
82
+ {
83
+ bool json_mode = false;
84
+
85
+ size_t argidx;
86
+ for (argidx = 1; argidx < args.size(); argidx++)
87
+ {
88
+ if (args[argidx] == "-json") {
89
+ json_mode = true;
90
+ continue;
91
+ }
92
+ break;
93
+ }
94
+ extra_args(args, argidx, design);
95
+
96
+ if(!json_mode)
97
+ log_header(design, "Printing internal statistics.\n");
98
+
99
+ log_experimental("internal_stats");
100
+
101
+ if (json_mode) {
102
+ log("{\n");
103
+ log(" \"creator\": %s,\n", json11::Json(yosys_maybe_version()).dump());
104
+ std::stringstream invocation;
105
+ std::copy(args.begin(), args.end(), std::ostream_iterator<std::string>(invocation, " "));
106
+ log(" \"invocation\": %s,\n", json11::Json(invocation.str()).dump());
107
+ if (auto mem = current_mem_bytes()) {
108
+ log(" \"memory_now\": %s,\n", std::to_string(*mem));
109
+ }
110
+ auto ast_bytes = AST::astnode_count() * (unsigned long long) sizeof(AST::AstNode);
111
+ log(" \"memory_ast\": %s,\n", std::to_string(ast_bytes));
112
+ }
113
+
114
+ // stats go here
115
+
116
+ if (json_mode) {
117
+ log("\n");
118
+ log("}\n");
119
+ }
120
+
121
+ }
122
+ } InternalStatsPass;
123
+
124
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/linecoverage.cc ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+
23
+ #include <regex>
24
+
25
+ USING_YOSYS_NAMESPACE
26
+ PRIVATE_NAMESPACE_BEGIN
27
+
28
+
29
+ static const std::regex src_re("(.*):(\\d+)\\.(\\d+)-(\\d+)\\.(\\d+)");
30
+
31
+ struct CoveragePass : public Pass {
32
+ CoveragePass() : Pass("linecoverage", "report coverage information") { }
33
+ void help() override
34
+ {
35
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
36
+ log("\n");
37
+ log(" linecoverage [options] [selection]\n");
38
+ log("\n");
39
+ log("This command prints coverage information on the design based on the current\n");
40
+ log("selection, where items in the selection are considered covered and items not in\n");
41
+ log("the selection are considered uncovered. If the same source location is found\n");
42
+ log("both on items inside and out of the selection, it is considered uncovered.\n");
43
+ log("\n");
44
+ log(" -lcov <filename>\n");
45
+ log(" write coverage information in lcov format to this file\n");
46
+ log("\n");
47
+ }
48
+
49
+ std::string extract_src_filename(std::string src) const
50
+ {
51
+ std::smatch m;
52
+ if (std::regex_match(src, m, src_re)) {
53
+ return m[1].str();
54
+ };
55
+ return "";
56
+ }
57
+
58
+ std::pair<int, int> extract_src_lines(std::string src) const
59
+ {
60
+ std::smatch m;
61
+ if (std::regex_match(src, m, src_re)) {
62
+ return std::make_pair(stoi(m[2].str()), stoi(m[4].str()));
63
+ };
64
+ return std::make_pair(0,0);
65
+ }
66
+
67
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
68
+ {
69
+ std::string ofile;
70
+
71
+ log_header(design, "Executing linecoverage pass.\n");
72
+
73
+ size_t argidx;
74
+ for (argidx = 1; argidx < args.size(); argidx++)
75
+ {
76
+ if (args[argidx] == "-lcov" && argidx+1 < args.size()) {
77
+ ofile = args[++argidx];
78
+ continue;
79
+ }
80
+ break;
81
+ }
82
+ extra_args(args, argidx, design);
83
+
84
+ std::ofstream fout;
85
+ if (!ofile.empty()) {
86
+ fout.open(ofile, std::ios::out | std::ios::trunc);
87
+ if (!fout.is_open())
88
+ log_error("Could not open file \"%s\" with write access.\n", ofile);
89
+ }
90
+
91
+ std::map<std::string, std::set<int>> uncovered_lines;
92
+ std::map<std::string, std::set<int>> all_lines;
93
+
94
+ for (auto module : design->modules())
95
+ {
96
+ log_debug("Module %s:\n", module);
97
+ for (auto wire: module->wires()) {
98
+ log_debug("%s\t%s\t%s\n", module->selected(wire) ? "*" : " ", wire->get_src_attribute(), wire);
99
+ for (auto src: wire->get_strpool_attribute(ID::src)) {
100
+ auto filename = extract_src_filename(src);
101
+ if (filename.empty()) continue;
102
+ auto [begin, end] = extract_src_lines(src);
103
+ for (int l = begin; l <=end; l++) {
104
+ if (l == 0) continue;
105
+ all_lines[filename].insert(l);
106
+ if (!module->selected(wire))
107
+ uncovered_lines[filename].insert(l);
108
+ }
109
+ }
110
+ }
111
+ for (auto cell: module->cells()) {
112
+ log_debug("%s\t%s\t%s\n", module->selected(cell) ? "*" : " ", cell->get_src_attribute(), cell);
113
+ for (auto src: cell->get_strpool_attribute(ID::src)) {
114
+ auto filename = extract_src_filename(src);
115
+ if (filename.empty()) continue;
116
+ auto [begin, end] = extract_src_lines(src);
117
+ for (int l = begin; l <=end; l++) {
118
+ if (l == 0) continue;
119
+ all_lines[filename].insert(l);
120
+ if (!module->selected(cell))
121
+ uncovered_lines[filename].insert(l);
122
+ }
123
+ }
124
+ }
125
+ log_debug("\n");
126
+ }
127
+
128
+ for (const auto& file_entry : all_lines) {
129
+ int lines_found = file_entry.second.size();
130
+ int lines_hit = file_entry.second.size() - (uncovered_lines.count(file_entry.first) ? uncovered_lines[file_entry.first].size() : 0);
131
+ log("File %s: %d/%d lines covered\n", file_entry.first, lines_hit, lines_found);
132
+
133
+ if(!ofile.empty()) {
134
+ fout << "SF:" << file_entry.first << "\n";
135
+ for (int l : file_entry.second) {
136
+ fout << "DA:" << l << ",";
137
+ if (uncovered_lines.count(file_entry.first) && uncovered_lines[file_entry.first].count(l))
138
+ fout << "0";
139
+ else
140
+ fout << "1";
141
+ fout << "\n";
142
+ }
143
+ fout << "LF:" << lines_found << "\n";
144
+ fout << "LH:" << lines_hit << "\n";
145
+ fout << "end_of_record\n";
146
+ }
147
+ }
148
+
149
+ }
150
+ } CoveragePass;
151
+
152
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/linux_perf.cc ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2014 Claire Xenia Wolf <claire@yosyshq.com>
5
+ * Copyright (C) 2014 Johann Glaser <Johann.Glaser@gmx.at>
6
+ *
7
+ * Permission to use, copy, modify, and/or distribute this software for any
8
+ * purpose with or without fee is hereby granted, provided that the above
9
+ * copyright notice and this permission notice appear in all copies.
10
+ *
11
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18
+ *
19
+ */
20
+
21
+ #include "kernel/yosys.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ #include <fcntl.h>
25
+ #include <stdlib.h>
26
+
27
+ USING_YOSYS_NAMESPACE
28
+ PRIVATE_NAMESPACE_BEGIN
29
+
30
+ #ifdef __linux__
31
+ #include <unistd.h>
32
+ struct LinuxPerf : public Pass {
33
+ LinuxPerf() : Pass("linux_perf", "turn linux perf recording off or on") {
34
+ internal();
35
+ }
36
+ bool formatted_help() override
37
+ {
38
+ auto *help = PrettyHelp::get_current();
39
+
40
+ auto content_root = help->get_root();
41
+
42
+ content_root->usage("linux_perf [on|off]");
43
+
44
+ content_root->paragraph(
45
+ "This pass turns Linux 'perf' profiling on or off, when it has been configured to use control FIFOs."
46
+ "YOSYS_PERF_CTL and YOSYS_PERF_ACK must point to Linux perf control FIFOs."
47
+ );
48
+ content_root->paragraph("Example shell command line:");
49
+ content_root->codeblock(
50
+ "mkfifo /tmp/perf.fifo /tmp/perf-ack.fifo\n"
51
+ "YOSYS_PERF_CTL=/tmp/perf.fifo YOSYS_PERF_ACK=/tmp/perf-ack.fifo \\\n"
52
+ " perf record --latency --delay=-1 \\\n"
53
+ " --control=fifo:/tmp/perf.fifo,/tmp/perf-ack.fifo --call-graph=dwarf ./yosys \\\n"
54
+ " -dt -p \"read_rtlil design.rtlil; linux_perf on; opt_clean; linux_perf off\"\n"
55
+ );
56
+
57
+ return true;
58
+ }
59
+ void execute(std::vector<std::string> args, RTLIL::Design *) override
60
+ {
61
+ if (args.size() > 2)
62
+ cmd_error(args, 2, "Unexpected argument.");
63
+
64
+ std::string_view ctl_msg;
65
+ if (args.size() == 2) {
66
+ if (args[1] == "on")
67
+ ctl_msg = "enable\n";
68
+ else if (args[1] == "off")
69
+ ctl_msg = "disable\n";
70
+ else
71
+ cmd_error(args, 1, "Unexpected argument.");
72
+ }
73
+
74
+ const char *ctl_fifo = std::getenv("YOSYS_PERF_CTL");
75
+ if (!ctl_fifo)
76
+ log_error("YOSYS_PERF_CTL environment variable not set.\n");
77
+ const char *ack_fifo = std::getenv("YOSYS_PERF_ACK");
78
+ if (!ack_fifo)
79
+ log_error("YOSYS_PERF_ACK environment variable not set.\n");
80
+
81
+ int ctl_fd = open(ctl_fifo, O_WRONLY);
82
+ if (ctl_fd < 0)
83
+ log_error("Failed to open YOSYS_PERF_CTL.\n");
84
+ int ack_fd = open(ack_fifo, O_RDONLY);
85
+ if (ack_fd < 0)
86
+ log_error("Failed to open YOSYS_PERF_ACK.\n");
87
+ int result = write(ctl_fd, ctl_msg.data(), ctl_msg.size());
88
+ if (result != static_cast<int>(ctl_msg.size()))
89
+ log_error("Failed to write to YOSYS_PERF_CTL.\n");
90
+ char buffer[64];
91
+ result = read(ack_fd, buffer, sizeof(buffer));
92
+ close(ctl_fd);
93
+ close(ack_fd);
94
+ if (result <= 0)
95
+ log_error("Failed to read from YOSYS_PERF_ACK.\n");
96
+ if (strcmp(buffer, "ack\n") != 0)
97
+ log_error("YOSYS_PERF_ACK did not return 'ack'.\n");
98
+ }
99
+ } LinuxPerf;
100
+ #endif
101
+
102
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/logcmd.cc ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ * Copyright (C) 2014 Johann Glaser <Johann.Glaser@gmx.at>
6
+ *
7
+ * Permission to use, copy, modify, and/or distribute this software for any
8
+ * purpose with or without fee is hereby granted, provided that the above
9
+ * copyright notice and this permission notice appear in all copies.
10
+ *
11
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18
+ *
19
+ */
20
+
21
+ #include "kernel/yosys.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct LogPass : public Pass {
28
+ LogPass() : Pass("log", "print text and log files") { }
29
+ bool formatted_help() override {
30
+ auto *help = PrettyHelp::get_current();
31
+ help->set_group("passes/status");
32
+ return false;
33
+ }
34
+ void help() override
35
+ {
36
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
37
+ log("\n");
38
+ log(" log [options] string\n");
39
+ log(" log [ -push | -pop ]\n");
40
+ log("\n");
41
+ log("Print the given string to the screen and/or the log file. This is useful for TCL\n");
42
+ log("scripts, because the TCL command \"puts\" only goes to stdout but not to\n");
43
+ log("logfiles.\n");
44
+ log("\n");
45
+ log(" -stdout\n");
46
+ log(" Print the output to stdout too. This is useful when all Yosys is\n");
47
+ log(" executed with a script and the -q (quiet operation) argument to notify\n");
48
+ log(" the user.\n");
49
+ log("\n");
50
+ log(" -stderr\n");
51
+ log(" Print the output to stderr too.\n");
52
+ log("\n");
53
+ log(" -nolog\n");
54
+ log(" Don't use the internal log() command. Use either -stdout or -stderr,\n");
55
+ log(" otherwise no output will be generated at all.\n");
56
+ log("\n");
57
+ log(" -n\n");
58
+ log(" do not append a newline\n");
59
+ log("\n");
60
+ log(" -header\n");
61
+ log(" log a pass header\n");
62
+ log("\n");
63
+ log(" -push\n");
64
+ log(" push a new level on the pass counter\n");
65
+ log("\n");
66
+ log(" -pop\n");
67
+ log(" pop from the pass counter\n");
68
+ log("\n");
69
+ }
70
+ void execute(std::vector<std::string> args, RTLIL::Design* design) override
71
+ {
72
+ size_t argidx;
73
+ bool to_stdout = false;
74
+ bool to_stderr = false;
75
+ bool to_log = true;
76
+ bool newline = true;
77
+ bool header = false;
78
+ bool push = false;
79
+ bool pop = false;
80
+ std::string text;
81
+
82
+ for (argidx = 1; argidx < args.size(); argidx++)
83
+ {
84
+ if (args[argidx] == "-stdout") to_stdout = true;
85
+ else if (args[argidx] == "-stderr") to_stderr = true;
86
+ else if (args[argidx] == "-nolog") to_log = false;
87
+ else if (args[argidx] == "-n") newline = false;
88
+ else if (args[argidx] == "-header") header = true;
89
+ else if (args[argidx] == "-push") push = true;
90
+ else if (args[argidx] == "-pop") pop = true;
91
+ else break;
92
+ }
93
+
94
+ if ((push || pop) && args.size() != 2)
95
+ log_cmd_error("Bad usage: 'log -push' or 'log -pop' must be used without other arguments.\n");
96
+
97
+ if (push) { log_push(); return; }
98
+ if (pop) { log_pop(); return; }
99
+
100
+ for (; argidx < args.size(); argidx++)
101
+ text += args[argidx] + ' ';
102
+ if (!text.empty()) text.resize(text.size()-1);
103
+
104
+ const char *line_end = newline ? "\n" : "";
105
+
106
+ if (to_stdout) fprintf(stdout, "%s%s", text.c_str(), line_end);
107
+ if (to_stderr) fprintf(stderr, "%s%s", text.c_str(), line_end);
108
+ if (to_log) {
109
+ if (!header) log("%s%s", text, line_end);
110
+ else log_header(design, "%s%s", text, line_end);
111
+ }
112
+ }
113
+ } LogPass;
114
+
115
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/logger.cc ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2020 Miodrag Milanovic <micko@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/log_help.h"
22
+ #include <regex>
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct LoggerPass : public Pass {
28
+ LoggerPass() : Pass("logger", "set logger properties") { }
29
+ bool formatted_help() override {
30
+ auto *help = PrettyHelp::get_current();
31
+ help->set_group("passes/status");
32
+ return false;
33
+ }
34
+ void help() override
35
+ {
36
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
37
+ log("\n");
38
+ log(" logger [options]\n");
39
+ log("\n");
40
+ log("This command sets global logger properties, also available using command line\n");
41
+ log("options.\n");
42
+ log("\n");
43
+ log(" -[no]time\n");
44
+ log(" enable/disable display of timestamp in log output.\n");
45
+ log("\n");
46
+ log(" -warn regex\n");
47
+ log(" print a warning for all log messages matching the regex.\n");
48
+ log("\n");
49
+ log(" -nowarn regex\n");
50
+ log(" if a warning message matches the regex, it is printed as regular\n");
51
+ log(" message instead.\n");
52
+ log("\n");
53
+ log(" -werror regex\n");
54
+ log(" if a warning message matches the regex, it is printed as error\n");
55
+ log(" message instead and the tool terminates with a nonzero return code.\n");
56
+ log("\n");
57
+ log(" -[no]debug\n");
58
+ log(" globally enable/disable debug log messages.\n");
59
+ log("\n");
60
+ log(" -experimental <feature>\n");
61
+ log(" do not print warnings for the specified experimental feature\n");
62
+ log("\n");
63
+ log(" -expect <type> <regex> <expected_count>\n");
64
+ log(" expect log, warning or error to appear. matched errors will terminate\n");
65
+ log(" with exit code 0.\n");
66
+ log(" Types prefix-log, prefix-warning and prefix-error match the entire\n");
67
+ log(" logged string, including filename if present.\n");
68
+ log("\n");
69
+ log(" -expect-no-warnings\n");
70
+ log(" gives error in case there is at least one warning that is not expected.\n");
71
+ log("\n");
72
+ log(" -check-expected\n");
73
+ log(" verifies that the patterns previously set up by -expect have actually\n");
74
+ log(" been met, then clears the expected log list. If this is not called\n");
75
+ log(" manually, the check will happen at yosys exit time instead.\n");
76
+ log("\n");
77
+ }
78
+
79
+ void execute(std::vector<std::string> args, RTLIL::Design * design) override
80
+ {
81
+ size_t argidx;
82
+ for (argidx = 1; argidx < args.size(); argidx++)
83
+ {
84
+
85
+ if (args[argidx] == "-time") {
86
+ logger().set_log_time(true);
87
+ log("Enabled timestamp in logs.\n");
88
+ continue;
89
+ }
90
+ if (args[argidx] == "-notime") {
91
+ logger().set_log_time(false);
92
+ log("Disabled timestamp in logs.\n");
93
+ continue;
94
+ }
95
+ if (args[argidx] == "-warn" && argidx+1 < args.size()) {
96
+ std::string pattern = args[++argidx];
97
+ if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2);
98
+ try {
99
+ log("Added regex '%s' for warnings to warn list.\n", pattern);
100
+ logger().add_warn(pattern);
101
+ }
102
+ catch (const std::regex_error& e) {
103
+ log_cmd_error("Error in regex expression '%s' !\n", pattern);
104
+ }
105
+ continue;
106
+ }
107
+ if (args[argidx] == "-nowarn" && argidx+1 < args.size()) {
108
+ std::string pattern = args[++argidx];
109
+ if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2);
110
+ try {
111
+ log("Added regex '%s' for warnings to nowarn list.\n", pattern);
112
+ logger().add_nowarn(pattern);
113
+ }
114
+ catch (const std::regex_error& e) {
115
+ log_cmd_error("Error in regex expression '%s' !\n", pattern);
116
+ }
117
+ continue;
118
+ }
119
+ if (args[argidx] == "-werror" && argidx+1 < args.size()) {
120
+ std::string pattern = args[++argidx];
121
+ if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2);
122
+ try {
123
+ log("Added regex '%s' for warnings to werror list.\n", pattern);
124
+ logger().add_werror(pattern);
125
+ }
126
+ catch (const std::regex_error& e) {
127
+ log_cmd_error("Error in regex expression '%s' !\n", pattern);
128
+ }
129
+ continue;
130
+ }
131
+ if (args[argidx] == "-debug") {
132
+ logger().set_force_debug(true);
133
+ log("Enabled debug log messages.\n");
134
+ continue;
135
+ }
136
+ if (args[argidx] == "-nodebug") {
137
+ logger().set_force_debug(false);
138
+ log("Disabled debug log messages.\n");
139
+ continue;
140
+ }
141
+ if (args[argidx] == "-experimental" && argidx+1 < args.size()) {
142
+ std::string value = args[++argidx];
143
+ log("Added '%s' experimental ignore list.\n", value);
144
+ logger().add_experimental_ignore(value);
145
+ continue;
146
+ }
147
+ if (args[argidx] == "-expect" && argidx+3 < args.size()) {
148
+ std::string type = args[++argidx];
149
+ if (type!="error" && type!="warning" && type!="log"
150
+ && type!="prefix-error" && type!="prefix-warning" && type!="prefix-log")
151
+ log_cmd_error("Expect command require type to be 'log', 'warning' or 'error' !\n");
152
+ if ((type=="error" || type=="prefix-error") && logger().expects_error())
153
+ log_cmd_error("Only single error message can be expected !\n");
154
+ std::string pattern = args[++argidx];
155
+ if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2);
156
+ int count = atoi(args[++argidx].c_str());
157
+ if (count<=0)
158
+ log_cmd_error("Number of expected messages must be higher then 0 !\n");
159
+ if ((type=="error" || type=="prefix-error") && count!=1)
160
+ log_cmd_error("Expected error message occurrences must be 1 !\n");
161
+ log("Added regex '%s' to expected %s messages list.\n",
162
+ pattern, type);
163
+ try {
164
+ logger().add_expect(type, pattern, count);
165
+ }
166
+ catch (const std::regex_error& e) {
167
+ log_cmd_error("Error in regex expression '%s' !\n", pattern);
168
+ }
169
+ continue;
170
+ }
171
+ if (args[argidx] == "-expect-no-warnings") {
172
+ logger().set_expect_no_warnings(true);
173
+ continue;
174
+ }
175
+ if (args[argidx] == "-check-expected") {
176
+ logger().check_expected();
177
+ continue;
178
+ }
179
+ break;
180
+ }
181
+ extra_args(args, argidx, design, false);
182
+ }
183
+ } LoggerPass;
184
+
185
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/ltp.cc ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/celltypes.h"
22
+ #include "kernel/sigtools.h"
23
+ #include "kernel/log_help.h"
24
+
25
+ USING_YOSYS_NAMESPACE
26
+ PRIVATE_NAMESPACE_BEGIN
27
+
28
+ struct LtpWorker
29
+ {
30
+ RTLIL::Design *design;
31
+ RTLIL::Module *module;
32
+ SigMap sigmap;
33
+
34
+ dict<SigBit, tuple<int, SigBit, Cell*>> bits;
35
+ dict<SigBit, dict<SigBit, Cell*>> bit2bits;
36
+ dict<SigBit, tuple<SigBit, Cell*>> bit2ff;
37
+
38
+ int maxlvl;
39
+ SigBit maxbit;
40
+ pool<SigBit> busy;
41
+
42
+ LtpWorker(RTLIL::Module *module, bool noff) : design(module->design), module(module), sigmap(module)
43
+ {
44
+ CellTypes ff_celltypes;
45
+
46
+ if (noff) {
47
+ ff_celltypes.setup_internals_mem();
48
+ ff_celltypes.setup_stdcells_mem();
49
+ }
50
+
51
+ for (auto wire : module->selected_wires())
52
+ for (auto bit : sigmap(wire))
53
+ bits[bit] = tuple<int, SigBit, Cell*>(-1, State::Sx, nullptr);
54
+
55
+ for (auto cell : module->selected_cells())
56
+ {
57
+ pool<SigBit> src_bits, dst_bits;
58
+
59
+ for (auto &conn : cell->connections())
60
+ for (auto bit : sigmap(conn.second)) {
61
+ if (cell->input(conn.first))
62
+ src_bits.insert(bit);
63
+ if (cell->output(conn.first))
64
+ dst_bits.insert(bit);
65
+ }
66
+
67
+ if (noff && ff_celltypes.cell_known(cell->type)) {
68
+ for (auto s : src_bits)
69
+ for (auto d : dst_bits) {
70
+ bit2ff[s] = tuple<SigBit, Cell*>(d, cell);
71
+ break;
72
+ }
73
+ continue;
74
+ }
75
+
76
+ for (auto s : src_bits)
77
+ for (auto d : dst_bits)
78
+ bit2bits[s][d] = cell;
79
+ }
80
+
81
+ maxlvl = -1;
82
+ maxbit = State::Sx;
83
+ }
84
+
85
+ void runner(SigBit bit, int level, SigBit from, Cell *via)
86
+ {
87
+ auto &bitinfo = bits.at(bit);
88
+
89
+ if (get<0>(bitinfo) >= level)
90
+ return;
91
+
92
+ if (busy.count(bit) > 0) {
93
+ log_warning("Detected loop at %s in %s\n", log_signal(bit), module);
94
+ return;
95
+ }
96
+
97
+ busy.insert(bit);
98
+ get<0>(bitinfo) = level;
99
+ get<1>(bitinfo) = from;
100
+ get<2>(bitinfo) = via;
101
+
102
+ if (level > maxlvl) {
103
+ maxlvl = level;
104
+ maxbit = bit;
105
+ }
106
+
107
+ if (bit2bits.count(bit)) {
108
+ for (auto &it : bit2bits.at(bit))
109
+ runner(it.first, level+1, bit, it.second);
110
+ }
111
+
112
+ busy.erase(bit);
113
+ }
114
+
115
+ void printpath(SigBit bit)
116
+ {
117
+ auto &bitinfo = bits.at(bit);
118
+ if (get<2>(bitinfo)) {
119
+ printpath(get<1>(bitinfo));
120
+ log("%5d: %s (via %s)\n", get<0>(bitinfo), log_signal(bit), get<2>(bitinfo));
121
+ } else {
122
+ log("%5d: %s\n", get<0>(bitinfo), log_signal(bit));
123
+ }
124
+ }
125
+
126
+ void selectpath(RTLIL::Selection &sel)
127
+ {
128
+ if (maxlvl < 0)
129
+ return;
130
+
131
+ SigBit bit = maxbit;
132
+ while (true) {
133
+ if (!bit.wire)
134
+ break;
135
+
136
+ sel.select(module, bit.wire);
137
+
138
+ auto &bitinfo = bits.at(bit);
139
+ Cell *via = get<2>(bitinfo);
140
+ if(!via)
141
+ break;
142
+ sel.select(module, via);
143
+
144
+ bit = get<1>(bitinfo);
145
+ }
146
+ }
147
+
148
+ void run(bool selectMode, RTLIL::Selection &sel)
149
+ {
150
+ for (auto &it : bits)
151
+ if (get<0>(it.second) < 0)
152
+ runner(it.first, 0, State::Sx, nullptr);
153
+
154
+ if (selectMode) {
155
+ log("\n");
156
+ log("Longest topological path in %s is length %d.\n", module, maxlvl);
157
+ selectpath(sel);
158
+ } else {
159
+ log("\n");
160
+ log("Longest topological path in %s (length=%d):\n", module, maxlvl);
161
+
162
+ if (maxlvl >= 0)
163
+ printpath(maxbit);
164
+
165
+ if (bit2ff.count(maxbit))
166
+ log("%5s: %s (via %s)\n", "ff", log_signal(get<0>(bit2ff.at(maxbit))), get<1>(bit2ff.at(maxbit)));
167
+ }
168
+ }
169
+ };
170
+
171
+ struct LtpPass : public Pass {
172
+ LtpPass() : Pass("ltp", "print longest topological path") { }
173
+ bool formatted_help() override {
174
+ auto *help = PrettyHelp::get_current();
175
+ help->set_group("passes/status");
176
+ return false;
177
+ }
178
+ void help() override
179
+ {
180
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
181
+ log("\n");
182
+ log(" ltp [options] [selection]\n");
183
+ log("\n");
184
+ log("This command prints the longest topological path in the design. (Only considers\n");
185
+ log("paths within a single module, so the design must be flattened.)\n");
186
+ log("\n");
187
+ log(" -noff\n");
188
+ log(" automatically exclude FF cell types\n");
189
+ log("\n");
190
+ log(" -select\n");
191
+ log(" select the path elements instead of printing\n");
192
+ log("\n");
193
+ }
194
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
195
+ {
196
+ bool noff = false;
197
+ bool selectMode = false;
198
+
199
+ log_header(design, "Executing LTP pass (find longest path).\n");
200
+
201
+ size_t argidx;
202
+ for (argidx = 1; argidx < args.size(); argidx++) {
203
+ if (args[argidx] == "-noff") {
204
+ noff = true;
205
+ continue;
206
+ }
207
+ if (args[argidx] == "-select") {
208
+ selectMode = true;
209
+ continue;
210
+ }
211
+ break;
212
+ }
213
+ int origSelectPos = design->selection_stack.size() - 1;
214
+ extra_args(args, argidx, design);
215
+
216
+ auto newSelection = RTLIL::Selection::EmptySelection(design);
217
+
218
+ for (Module *module : design->selected_modules())
219
+ {
220
+ if (module->has_processes_warn())
221
+ continue;
222
+
223
+ LtpWorker worker(module, noff);
224
+ worker.run(selectMode, newSelection);
225
+ }
226
+
227
+ if (selectMode) {
228
+ log_assert(origSelectPos >= 0);
229
+ design->selection_stack[origSelectPos] = newSelection;
230
+ design->selection_stack[origSelectPos].optimize(design);
231
+ }
232
+ }
233
+ } LtpPass;
234
+
235
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/optbarriers.cc ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2024 George Rennie <georgrennie@gmail.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/ffinit.h"
23
+ #include "kernel/topo_scc.h"
24
+
25
+ USING_YOSYS_NAMESPACE
26
+ PRIVATE_NAMESPACE_BEGIN
27
+
28
+ // Standard visitor helper
29
+ template<class... Ts>
30
+ struct overloaded : Ts... { using Ts::operator()...; };
31
+ template<class... Ts>
32
+ overloaded(Ts...) -> overloaded<Ts...>;
33
+
34
+ // This computes a graph of assignment dependencies in a process, which is used
35
+ // to preserve SCCs in the process which are useful for DFF inference
36
+ struct ProcessDependencyWorker {
37
+ ProcessDependencyWorker(const RTLIL::Process& proc) {
38
+ add_process(proc);
39
+ find_sccs();
40
+ }
41
+
42
+ ProcessDependencyWorker(const std::vector<RTLIL::SigSig>& connections) {
43
+ for (const auto& sigsig : connections)
44
+ add_sigsig(sigsig);
45
+ find_sccs();
46
+ }
47
+
48
+ void add_process(const RTLIL::Process& proc) {
49
+ add_caserule(proc.root_case);
50
+
51
+ for (const auto* sync : proc.syncs)
52
+ add_syncrule(*sync);
53
+ }
54
+
55
+ void add_syncrule(const RTLIL::SyncRule& sync) {
56
+ for (const auto& sigsig : sync.actions)
57
+ add_sigsig(sigsig);
58
+ }
59
+
60
+ void add_caserule(const RTLIL::CaseRule& caserule) {
61
+ for (const auto& sigsig : caserule.actions)
62
+ add_sigsig(sigsig);
63
+
64
+ for (const auto* rule : caserule.switches)
65
+ add_switchrule(*rule);
66
+ }
67
+
68
+ void add_switchrule(const RTLIL::SwitchRule& switchrule) {
69
+ for (const auto* rule : switchrule.cases)
70
+ add_caserule(*rule);
71
+ }
72
+
73
+ void add_sigsig(const RTLIL::SigSig& sigsig) {
74
+ for (int i = 0; i < GetSize(sigsig.first); i++) {
75
+ const auto lhs = sigsig.first[i], rhs = sigsig.second[i];
76
+ // Every driven bit is a node, also one only assigned constants
77
+ auto& rhs_bits = dependencies[lhs];
78
+ if (rhs.is_wire())
79
+ rhs_bits.emplace(rhs);
80
+ }
81
+ }
82
+
83
+ // Returns the set of nodes that are on a cycle through this bit - its SCC,
84
+ // or nothing when the bit is on no cycle
85
+ const pool<SigBit>& scc_nodes(const SigBit bit) const {
86
+ const auto it = scc_of.find(bit);
87
+ return it == scc_of.end() ? no_nodes : sccs[it->second];
88
+ }
89
+
90
+ dict<SigBit, pool<SigBit>> dependencies;
91
+ private:
92
+ // A lone bit is on a cycle only with a self-loop
93
+ void find_sccs() {
94
+ idict<SigBit> ids;
95
+ IntGraph graph;
96
+ for (const auto& [lhs, rhs_bits] : dependencies)
97
+ for (const auto& rhs : rhs_bits)
98
+ if (dependencies.count(rhs))
99
+ graph.add_edge(ids(lhs), ids(rhs));
100
+
101
+ TopoSortedSccs(graph, [&](int* begin, int* end) {
102
+ pool<SigBit> scc;
103
+ for (int* it = begin; it != end; it++)
104
+ scc.insert(ids[*it]);
105
+ const SigBit bit = *scc.begin();
106
+ if (GetSize(scc) == 1 && !dependencies.at(bit).count(bit))
107
+ return;
108
+ for (const auto& member : scc)
109
+ scc_of[member] = GetSize(sccs);
110
+ sccs.push_back(std::move(scc));
111
+ }).process_all();
112
+ }
113
+
114
+ dict<SigBit, int> scc_of;
115
+ std::vector<pool<SigBit>> sccs;
116
+ pool<SigBit> no_nodes;
117
+ };
118
+
119
+ struct ResetPathWorker {
120
+ ResetPathWorker(RTLIL::Module* module) {
121
+ std::vector<std::pair<const RTLIL::Process*, pool<SigBit>>> edge_procs;
122
+ for (const auto& [_, proc] : module->processes) {
123
+ pool<SigBit> edges;
124
+ for (const auto* sync : proc->syncs)
125
+ if (sync->type == RTLIL::STp || sync->type == RTLIL::STn || sync->type == RTLIL::STe)
126
+ for (const auto& bit : sync->signal)
127
+ edges.insert(bit);
128
+ if (!edges.empty())
129
+ edge_procs.emplace_back(proc, std::move(edges));
130
+ }
131
+
132
+ // Without edge triggered processes there are no reset paths
133
+ if (edge_procs.empty())
134
+ return;
135
+
136
+ for (auto* cell : module->cells())
137
+ if (cell->type.in(ID($reduce_or), ID($reduce_bool), ID($logic_not), ID($not), ID($eq), ID($eqx), ID($ne), ID($nex)))
138
+ if (GetSize(cell->getPort(ID::Y)) == 1)
139
+ drivers[cell->getPort(ID::Y)[0]] = cell;
140
+
141
+ for (const auto& [proc, edges] : edge_procs)
142
+ visit(proc->root_case, edges);
143
+ }
144
+
145
+ void visit(const RTLIL::CaseRule& caserule, const pool<SigBit>& edges) {
146
+ if (GetSize(caserule.switches) != 1)
147
+ return;
148
+ const auto* sw = caserule.switches[0];
149
+ std::vector<SigBit> trace;
150
+ if (reaches_edge(sw->signal, edges, trace))
151
+ path.insert(trace.begin(), trace.end());
152
+ for (const auto* rule : sw->cases)
153
+ visit(*rule, edges);
154
+ }
155
+
156
+ bool reaches_edge(RTLIL::SigSpec signal, const pool<SigBit>& edges, std::vector<SigBit>& trace) {
157
+ while (GetSize(signal) == 1) {
158
+ const SigBit bit = signal[0];
159
+ if (edges.count(bit))
160
+ return true;
161
+ const auto it = drivers.find(bit);
162
+ if (it == drivers.end() || GetSize(trace) > GetSize(drivers))
163
+ return false;
164
+ trace.push_back(bit);
165
+ signal = next_signal(it->second);
166
+ }
167
+ return false;
168
+ }
169
+
170
+ static RTLIL::SigSpec next_signal(RTLIL::Cell* cell) {
171
+ if (!cell->type.in(ID($eq), ID($eqx), ID($ne), ID($nex)))
172
+ return cell->getPort(ID::A);
173
+ if (cell->getPort(ID::A).is_fully_const())
174
+ return cell->getPort(ID::B);
175
+ if (cell->getPort(ID::B).is_fully_const())
176
+ return cell->getPort(ID::A);
177
+ return RTLIL::SigSpec();
178
+ }
179
+
180
+ dict<SigBit, RTLIL::Cell*> drivers;
181
+ pool<SigBit> path;
182
+ };
183
+
184
+ struct OptBarriersPass : public Pass {
185
+ OptBarriersPass() : Pass("optbarriers", "(experimental) insert optimization barriers")
186
+ {
187
+ experimental();
188
+ }
189
+
190
+ void help() override {
191
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
192
+ log("\n");
193
+ log(" optbarriers [options] [selection]\n");
194
+ log("\n");
195
+ log("Insert optimization barriers to drivers of selected public wires.\n");
196
+ log("\n");
197
+ log("\n");
198
+ log(" -nocells\n");
199
+ log(" don't add optimization barriers to the outputs of cells\n");
200
+ log("\n");
201
+ log(" -noprocs\n");
202
+ log(" don't add optimization barriers to the outputs of processes\n");
203
+ log("\n");
204
+ log(" -noconns\n");
205
+ log(" don't add optimization barriers to the left hand sides of connections\n");
206
+ log("\n");
207
+ log(" -private\n");
208
+ log(" also add optimization barriers to private wires driven by cells and\n");
209
+ log(" connections, excluding private wires driven by processes\n");
210
+ log("\n");
211
+ log(" -remove\n");
212
+ log(" replace selected optimization barriers with connections\n");
213
+ log("\n");
214
+ }
215
+
216
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override {
217
+ log_header(design, "Executing OPTBARRIERS pass (insert optimization barriers).\n");
218
+
219
+ bool nocells_mode = false;
220
+ bool noprocs_mode = false;
221
+ bool noconns_mode = false;
222
+ bool private_mode = false;
223
+ bool remove_mode = false;
224
+
225
+ size_t argidx;
226
+ for (argidx = 1; argidx < args.size(); argidx++) {
227
+ std::string arg = args[argidx];
228
+ if (arg == "-nocells") {
229
+ nocells_mode = true;
230
+ continue;
231
+ }
232
+ if (arg == "-noprocs") {
233
+ noprocs_mode = true;
234
+ continue;
235
+ }
236
+ if (arg == "-noconns") {
237
+ noconns_mode = true;
238
+ continue;
239
+ }
240
+ if (arg == "-private") {
241
+ private_mode = true;
242
+ continue;
243
+ }
244
+ if (arg == "-remove") {
245
+ remove_mode = true;
246
+ continue;
247
+ }
248
+ break;
249
+ }
250
+ extra_args(args, argidx, design);
251
+
252
+ if (remove_mode) {
253
+ log("Replacing optimization barriers with connections.\n");
254
+ remove_barriers(design);
255
+ return;
256
+ }
257
+
258
+ for (auto* module : design->selected_modules()) {
259
+ // We can't just sigmap and iterate through wires for rewriting as
260
+ // we want to maintain the structure in connections, and sigmap
261
+ // will just return a canonical wire which does not have to be one
262
+ // that is directly driving the wire. Therefore for each type of
263
+ // object that could be driving the wires (cells, processes,
264
+ // connections) we rewrite the sigspecs.
265
+
266
+ // Keep track of which wires we have allocated new wires for
267
+ dict<RTLIL::Wire*, RTLIL::Wire*> new_wires;
268
+ // Keep track of bit pairs we need to construct barriers for from
269
+ // Y to A
270
+ dict<RTLIL::SigBit, RTLIL::SigBit> new_barriers;
271
+
272
+ // Nets that already drive a barrier input which must not get a second barrier.
273
+ // Only private wires check this, so only needed in private mode
274
+ SigMap sigmap;
275
+ pool<SigBit> barrier_inputs;
276
+ if (private_mode) {
277
+ sigmap.set(module);
278
+ for (auto* cell : module->cells())
279
+ if (cell->type == ID($barrier))
280
+ for (const auto& bit : sigmap(cell->getPort(ID::A)))
281
+ barrier_inputs.insert(bit);
282
+ }
283
+ const ResetPathWorker reset_path(module);
284
+
285
+ // Skip constants, unselected wires, private wires when not in
286
+ // private mode, input and inout ports, and private pre-barrier bits.
287
+ const auto skip = [&](const SigBit& bit) {
288
+ if (!bit.is_wire())
289
+ return true;
290
+
291
+ if (!design->selected(module, bit.wire))
292
+ return true;
293
+
294
+ if (bit.wire->port_input)
295
+ return true;
296
+
297
+ if (reset_path.path.count(bit))
298
+ return true;
299
+
300
+ if (!bit.wire->name.isPublic() && (!private_mode || barrier_inputs.count(sigmap(bit))))
301
+ return true;
302
+
303
+ return false;
304
+ };
305
+
306
+ const auto rewrite_sigspec = [&](const SigSpec& sig) {
307
+ RTLIL::SigSpec new_output;
308
+ for (const auto& bit : sig) {
309
+ if (skip(bit)) {
310
+ new_output.append(bit);
311
+ continue;
312
+ }
313
+
314
+ // Add a wire to drive if one does not already exist
315
+ auto* new_wire = new_wires.at(bit.wire, nullptr);
316
+ if (!new_wire) {
317
+ new_wire = module->addWire(NEW_ID_SUFFIX(bit.wire->name.str()), GetSize(bit.wire));
318
+ new_wires.emplace(bit.wire, new_wire);
319
+ }
320
+
321
+ // Rewrite output to drive new wire, and schedule adding
322
+ // a barrier bit from new wire to original
323
+ const SigBit new_bit(new_wire, bit.offset);
324
+ new_output.append(new_bit);
325
+ new_barriers.emplace(bit, new_bit);
326
+ }
327
+
328
+ return new_output;
329
+ };
330
+
331
+ // Rewrite processes. It is not as simple as changing all LHS
332
+ // expressions to drive barriers if required, as this prevents
333
+ // proc passes from optimizing self feedback which is important to
334
+ // prevent false comb paths when generating FFs. We only care about
335
+ // the assignments/connections within processes, and want to maintain
336
+ // the property that if a bit that is to be rewritten to use a
337
+ // barrier can be assigned transitively to itself, the value that is
338
+ // assigned should be the value before the barrier.
339
+ //
340
+ // To do this we first enumerate the assignment dependency graph
341
+ // for the process - marking which bits drive any other bit. We
342
+ // then look for strongly connected components containing barrier
343
+ // bits. These correspond to potential paths where the bit can be
344
+ // driven by itself and so should see the pre-barrier value. For
345
+ // each of the bits on this path we want to construct a parallel
346
+ // version that appears in all the same process assignments but is
347
+ // driven originally by the pre-barrier value.
348
+ //
349
+ // For example, consider the following set of assignments appear
350
+ // somewhere in the process and we want to add a barrier to b:
351
+ // a <- b
352
+ // b <- a
353
+ // There is a path from b to itself through a, so we add wire b\b to
354
+ // represent the pre-barrier version of b and a\b to represent
355
+ // the version of a that sees a pre-barrier version of b. We then
356
+ // correspondingly add these paths to the assignments and a barrier:
357
+ // {a\b, a} <- {b\b, b}
358
+ // b\b <- a\b
359
+ // b\b -$barrier> b
360
+ //
361
+ // This has retained that b\b is transitively driven by itself, but
362
+ // a is still driven by b, the post-barrier version of b
363
+ if (!noprocs_mode)
364
+ for (const auto& proc : module->processes) {
365
+ // A map from each bit driven by the original process to the
366
+ // set of variants required for it. If a bit doesn't appear in
367
+ // variants it is only needed in the original form it appears
368
+ // in the process.
369
+ //
370
+ // To get bit a\b from the above example you would index
371
+ // variants[a][b]
372
+ dict<SigBit, dict<SigBit, SigBit>> variants;
373
+
374
+ {
375
+ // We want to minimize the number of wires we have to create
376
+ // for each bit in variants, so for variants[a][b] we create
377
+ // a unique wire with size GetSize(a.wire) for each tuple
378
+ // of a.wire, b.wire, a.offset - b.offset rather than for
379
+ // every pair (a, b).
380
+ using IdxTuple = std::tuple<Wire*, Wire*, int>;
381
+ dict<IdxTuple, Wire*> variant_wires;
382
+
383
+ // Collect all assignment dependencies in the process
384
+ ProcessDependencyWorker dep_worker(*proc.second);
385
+
386
+ // Enumerate driven bits that need barriers added
387
+ for (const auto& [variant_bit, _] : dep_worker.dependencies) {
388
+ // Private bits driven by processes are frontend temporaries
389
+ if (skip(variant_bit) || !variant_bit.wire->name.isPublic())
390
+ continue;
391
+
392
+ // Collect the bits that are in an SCC with this bit and
393
+ // thus need to have variants constructed that see the
394
+ // pre-barrier value
395
+ for (const auto& lhs_bit : dep_worker.scc_nodes(variant_bit)) {
396
+ // Don't add a new wire for the variant_bit itself as this
397
+ // should be driven by a wire generated by rewrite_sigspec below
398
+ if (lhs_bit == variant_bit)
399
+ continue;
400
+
401
+ const int offset = lhs_bit.offset - variant_bit.offset;
402
+ const IdxTuple idx{lhs_bit.wire, variant_bit.wire, offset};
403
+ auto it = variant_wires.find(idx);
404
+
405
+ // Create a new wire to represent this offset combination
406
+ // if needed
407
+ if (it == variant_wires.end()) {
408
+ const auto name = NEW_ID_SUFFIX(lhs_bit.wire->name.str());
409
+ auto* new_wire = module->addWire(name, GetSize(lhs_bit.wire));
410
+ it = variant_wires.emplace(idx, new_wire).first;
411
+ }
412
+
413
+ variants[lhs_bit].emplace(variant_bit, SigBit(it->second, lhs_bit.offset));
414
+ }
415
+
416
+ // Even if a bit doesn't appear in any SCCs we want to rewrite it if it
417
+ // isn't skipped
418
+ variants[variant_bit].emplace(variant_bit, rewrite_sigspec(variant_bit));
419
+ }
420
+ }
421
+
422
+ const auto variant = [&](const SigBit a, const SigBit b) {
423
+ const auto it1 = variants.find(a);
424
+ // There are no variants of a required, so a definitely isn't
425
+ // transitively driven by b
426
+ if (it1 == variants.end())
427
+ return a;
428
+
429
+ const auto it2 = it1->second.find(b);
430
+ // a isn't be transitively driven by b
431
+ if (it2 == it1->second.end())
432
+ return a;
433
+
434
+ // a can be transitively driven by b so return the variant
435
+ // of a that sees pre-barrier b
436
+ return it2->second;
437
+ };
438
+
439
+ const auto proc_rewriter = overloaded{
440
+ // Don't do anything for input sigspecs, these are not connections
441
+ [&](const SigSpec&) {},
442
+ // Rewrite connections to drive barrier and see pre-barrier
443
+ // values if needed
444
+ [&](SigSpec& lhs, SigSpec& rhs) {
445
+ for (int i = 0; i < GetSize(lhs); i++) {
446
+ const auto lhs_bit = lhs[i], rhs_bit = rhs[i];
447
+
448
+ for (const auto& [variant_bit, variant_lhs_bit] : variants[lhs_bit]) {
449
+ // For the existing connections, update the lhs to be pre-barrier
450
+ // variant_lhs_bit and rhs to be the variant of itself that sees
451
+ // the pre-barrier version of variant_bit
452
+ if (variant_bit == lhs_bit) {
453
+ lhs[i] = variant_lhs_bit;
454
+ rhs[i] = variant(rhs_bit, variant_bit);
455
+ continue;
456
+ }
457
+
458
+ // For new variants of lhs_bit that we need to exist, set the
459
+ // rhs bit to the variant of rhs_bit that sees the pre_barrier
460
+ // version of variant_bit
461
+ lhs.append(variant_lhs_bit);
462
+ rhs.append(variant(rhs_bit, variant_bit));
463
+ }
464
+ }
465
+ }
466
+ };
467
+
468
+ proc.second->rewrite_sigspecs2(proc_rewriter);
469
+ }
470
+
471
+ // Rewrite cell outputs
472
+ if (!nocells_mode)
473
+ for (auto* cell : module->cells())
474
+ if (cell->type != ID($barrier))
475
+ for (const auto& [name, sig] : cell->connections())
476
+ if (cell->output(name) && !cell->input(name))
477
+ cell->setPort(name, rewrite_sigspec(sig));
478
+
479
+ // Add all the scheduled barriers. To minimize the number of cells,
480
+ // first construct a sigspec of all bits, then sort and unify before
481
+ // creating barriers
482
+ SigSpec barrier_y;
483
+ for (const auto&[y_bit, _] : new_barriers)
484
+ barrier_y.append(y_bit);
485
+ barrier_y.sort_and_unify();
486
+
487
+ bool added_barriers = !barrier_y.empty();
488
+ for (const auto& sig_y : barrier_y.chunks()) {
489
+ log_assert(sig_y.is_wire());
490
+ SigSpec sig_a;
491
+ for (int i = 0; i < GetSize(sig_y); i++)
492
+ sig_a.append(new_barriers[sig_y[i]]);
493
+ module->addBarrier(NEW_ID, sig_a, sig_y);
494
+ }
495
+
496
+ // Rewrite connections
497
+ if (!noconns_mode) {
498
+ // A connection on a cycle of connections would become a barrier loop
499
+ const ProcessDependencyWorker conn_deps(module->connections());
500
+ std::vector<RTLIL::SigSig> new_connections;
501
+ for (const auto& conn : module->connections()) {
502
+ RTLIL::SigSig skip_conn, barrier_conn;
503
+
504
+ for (int i = 0; i < GetSize(conn.first); i++) {
505
+ bool keep_conn = skip(conn.first[i]) || !conn_deps.scc_nodes(conn.first[i]).empty();
506
+ auto& sigsig = keep_conn ? skip_conn : barrier_conn;
507
+ sigsig.first.append(conn.first[i]);
508
+ sigsig.second.append(conn.second[i]);
509
+ }
510
+
511
+ if (!skip_conn.first.empty())
512
+ new_connections.emplace_back(std::move(skip_conn));
513
+
514
+ if (!barrier_conn.first.empty()) {
515
+ module->addBarrier(NEW_ID, barrier_conn.second, barrier_conn.first);
516
+ added_barriers = true;
517
+ }
518
+ }
519
+ module->new_connections(new_connections);
520
+ }
521
+
522
+ // Init values belong to the driver side of the barriers
523
+ if (added_barriers) {
524
+ SigMap init_sigmap(module);
525
+ FfInitVals initvals(&init_sigmap, module);
526
+ initvals.move_barrier_inits(module);
527
+ }
528
+ }
529
+ }
530
+
531
+ void remove_barriers(RTLIL::Design* design) {
532
+ for (auto* module : design->selected_modules()) {
533
+ std::vector<RTLIL::Cell*> barriers;
534
+
535
+ for (auto* cell : module->selected_cells())
536
+ if (cell->type == ID($barrier))
537
+ barriers.emplace_back(cell);
538
+
539
+ for (auto* cell : barriers) {
540
+ const auto lhs = cell->getPort(ID::Y), rhs = cell->getPort(ID::A);
541
+ module->connect(lhs, rhs);
542
+ module->remove(cell);
543
+ }
544
+ }
545
+ }
546
+
547
+ } OptBarriersPass;
548
+
549
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/plugin.cc ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2014 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/log_help.h"
22
+
23
+ #ifdef YOSYS_ENABLE_PLUGINS
24
+ # include <dlfcn.h>
25
+ # include <filesystem>
26
+ namespace fs = std::filesystem;
27
+ #endif
28
+
29
+ #ifdef YOSYS_ENABLE_PYTHON
30
+ # include <Python.h>
31
+ # include <pybind11/pybind11.h>
32
+ namespace py = pybind11;
33
+ #endif
34
+
35
+ YOSYS_NAMESPACE_BEGIN
36
+
37
+ std::map<std::string, void*> loaded_plugins;
38
+ #ifdef YOSYS_ENABLE_PYTHON
39
+ std::map<std::string, void*> loaded_python_plugins;
40
+ #endif
41
+ std::map<std::string, std::string> loaded_plugin_aliases;
42
+
43
+ #ifdef YOSYS_ENABLE_PLUGINS
44
+
45
+ static constexpr const char *path_delimiters = fs::path::preferred_separator == '\\' ? ";" : ":" ;
46
+
47
+ inline const std::vector<fs::path> get_plugin_search_paths() {
48
+ std::vector<fs::path> result;
49
+ const char *yosys_plugin_path = std::getenv("YOSYS_PLUGIN_PATH");
50
+ if (yosys_plugin_path != nullptr && strlen(yosys_plugin_path)) {
51
+ // make mutable. std::string also manages allocation as a bonus
52
+ // guaranteed contiguous in c++>=11
53
+ std::string copy{yosys_plugin_path};
54
+ char *token = nullptr;
55
+ char *rest = &copy[0];
56
+ while ((token = strtok_r(rest, path_delimiters, &rest))) {
57
+ result.push_back(fs::path(token));
58
+ }
59
+ }
60
+ result.push_back(fs::path(proc_share_dirname()) / "plugins"); // lowest priority
61
+ return result;
62
+ }
63
+
64
+ void load_plugin(std::string filename, std::vector<std::string> aliases)
65
+ {
66
+ std::string orig_filename = filename;
67
+ rewrite_filename(filename);
68
+
69
+ // Would something like this better be put in `rewrite_filename`?
70
+ if (filename.find("/") == std::string::npos)
71
+ filename = "./" + filename;
72
+
73
+
74
+ #ifdef YOSYS_ENABLE_PYTHON
75
+ const bool is_loaded = loaded_plugins.count(orig_filename) && loaded_python_plugins.count(orig_filename);
76
+ #else
77
+ const bool is_loaded = loaded_plugins.count(orig_filename);
78
+ #endif
79
+
80
+ fs::path full_path = fs::absolute(filename);
81
+
82
+ if (!is_loaded) {
83
+ // Check if we're loading a python script
84
+ if (full_path.extension() == ".py") {
85
+ #ifdef YOSYS_ENABLE_PYTHON
86
+ fs::path plugin_python_path = full_path.parent_path();
87
+ fs::path basename = full_path.stem();
88
+
89
+ py::object sys = py::module_::import("sys");
90
+ sys.attr("path").attr("insert")(0, py::str(plugin_python_path.c_str()));
91
+
92
+ try {
93
+ auto module_container = py::module_::import(basename.c_str());
94
+ loaded_python_plugins[orig_filename] = module_container.ptr();
95
+ } catch (py::error_already_set &e) {
96
+ log_cmd_error("Can't load python module `%s': %s\n", basename, e.what());
97
+ return;
98
+ }
99
+ Pass::init_register();
100
+ #else
101
+ log_error(
102
+ "\n This version of Yosys cannot load python plugins.\n"
103
+ " Ensure Yosys is built with Python support to do so.\n"
104
+ );
105
+ #endif
106
+ } else {
107
+ // Otherwise we assume it's a native plugin
108
+ void *hdl = dlopen(filename.c_str(), RTLD_LAZY|RTLD_LOCAL);
109
+
110
+ // We were unable to open the file, try to do so from plugin search
111
+ // paths
112
+ if (hdl == nullptr && orig_filename.find('/') == std::string::npos) {
113
+ const std::vector<fs::path> search_paths = get_plugin_search_paths();
114
+ for (const auto &search_path: search_paths) {
115
+ fs::path potential_path = search_path / orig_filename;
116
+ if (potential_path.extension() != ".so") {
117
+ potential_path = search_path / (orig_filename + ".so");
118
+ }
119
+ hdl = dlopen(potential_path.string().c_str(), RTLD_LAZY | RTLD_LOCAL);
120
+ if (hdl != nullptr) {
121
+ break;
122
+ }
123
+ }
124
+ }
125
+
126
+ if (hdl == nullptr)
127
+ log_cmd_error("Can't load module `%s': %s\n", filename, dlerror());
128
+
129
+ loaded_plugins[orig_filename] = hdl;
130
+ Pass::init_register();
131
+ }
132
+ }
133
+
134
+ for (auto &alias : aliases)
135
+ loaded_plugin_aliases[alias] = orig_filename;
136
+ }
137
+ #else
138
+ void load_plugin(std::string, std::vector<std::string>)
139
+ {
140
+ log_error(
141
+ "\n This version of Yosys cannot load plugins at runtime.\n"
142
+ " Some plugins may have been included at build time.\n"
143
+ " Use `yosys -H' to see the available built-in and plugin commands.\n"
144
+ );
145
+ }
146
+ #endif
147
+
148
+ struct PluginPass : public Pass {
149
+ PluginPass() : Pass("plugin", "load and list loaded plugins") { }
150
+ bool formatted_help() override {
151
+ auto *help = PrettyHelp::get_current();
152
+ help->set_group("passes/status");
153
+ return false;
154
+ }
155
+ void help() override
156
+ {
157
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
158
+ log("\n");
159
+ log(" plugin [options]\n");
160
+ log("\n");
161
+ log("Load and list loaded plugins.\n");
162
+ log("\n");
163
+ log(" -i <plugin_filename>\n");
164
+ log(" Load (install) the specified plugin.\n");
165
+ log("\n");
166
+ log(" -a <alias_name>\n");
167
+ log(" Register the specified alias name for the loaded plugin\n");
168
+ log("\n");
169
+ log(" -l\n");
170
+ log(" List loaded plugins\n");
171
+ log("\n");
172
+ }
173
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
174
+ {
175
+ std::string plugin_filename;
176
+ std::vector<std::string> plugin_aliases;
177
+ bool list_mode = false;
178
+
179
+ size_t argidx;
180
+ for (argidx = 1; argidx < args.size(); argidx++)
181
+ {
182
+ if ((args[argidx] == "-i") && argidx+1 < args.size() && plugin_filename.empty()) {
183
+ plugin_filename = args[++argidx];
184
+ continue;
185
+ }
186
+ if ((args[argidx] == "-a") && argidx+1 < args.size()) {
187
+ plugin_aliases.push_back(args[++argidx]);
188
+ continue;
189
+ }
190
+ if (args[argidx] == "-l") {
191
+ list_mode = true;
192
+ continue;
193
+ }
194
+ break;
195
+ }
196
+ extra_args(args, argidx, design, false);
197
+
198
+ if (!plugin_filename.empty())
199
+ load_plugin(plugin_filename, plugin_aliases);
200
+
201
+ if (list_mode)
202
+ {
203
+ log("\n");
204
+ #ifdef YOSYS_ENABLE_PYTHON
205
+ if (loaded_plugins.empty() and loaded_python_plugins.empty())
206
+ #else
207
+ if (loaded_plugins.empty())
208
+ #endif
209
+ log("No plugins loaded.\n");
210
+ else
211
+ log("Loaded plugins:\n");
212
+
213
+ for (auto &it : loaded_plugins)
214
+ log(" %s\n", it.first);
215
+
216
+ #ifdef YOSYS_ENABLE_PYTHON
217
+ for (auto &it : loaded_python_plugins)
218
+ log(" %s\n", it.first);
219
+ #endif
220
+
221
+ if (!loaded_plugin_aliases.empty()) {
222
+ log("\n");
223
+ int max_alias_len = 1;
224
+ for (auto &it : loaded_plugin_aliases)
225
+ max_alias_len = max(max_alias_len, GetSize(it.first));
226
+ for (auto &it : loaded_plugin_aliases)
227
+ log("Alias: %-*s %s\n", max_alias_len, it.first, it.second);
228
+ }
229
+ }
230
+ }
231
+ } PluginPass;
232
+
233
+ YOSYS_NAMESPACE_END
chips/yosys/passes/cmds/portarcs.cc ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2024 Martin Povišer <povik@cutebit.org>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+
21
+ #include "kernel/timinginfo.h"
22
+ #include "kernel/rtlil.h"
23
+ #include "kernel/utils.h"
24
+ #include "kernel/celltypes.h"
25
+ #include "kernel/log_help.h"
26
+
27
+ PRIVATE_NAMESPACE_BEGIN
28
+ USING_YOSYS_NAMESPACE
29
+
30
+ static RTLIL::SigBit canonical_bit(RTLIL::SigBit bit)
31
+ {
32
+ RTLIL::Wire *w;
33
+ while ((w = bit.wire) != NULL && !w->port_input &&
34
+ w->driverCell()->type.in(ID($buf), ID($_BUF_))) {
35
+ bit = w->driverCell()->getPort(ID::A)[bit.offset];
36
+ }
37
+ return bit;
38
+ }
39
+
40
+ struct PortarcsPass : Pass {
41
+ PortarcsPass() : Pass("portarcs", "derive port arcs for propagation delay") {}
42
+ bool formatted_help() override {
43
+ auto *help = PrettyHelp::get_current();
44
+ help->set_group("passes/status");
45
+ return false;
46
+ }
47
+
48
+ void help() override
49
+ {
50
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
51
+ log("\n");
52
+ log(" portarcs [options] [selection]\n");
53
+ log("\n");
54
+ log("This command characterizes the combinational content of selected modules and\n");
55
+ log("derives timing arcs going from module inputs to module outputs representing the\n");
56
+ log("propagation delay of the module.\n");
57
+ log("\n");
58
+ log(" -draw\n");
59
+ log(" plot the computed delay table to the terminal\n");
60
+ log("\n");
61
+ log(" -icells\n");
62
+ log(" assign unit delay to gates from the internal Yosys cell library\n");
63
+ log("\n");
64
+ log(" -write\n");
65
+ log(" write the computed arcs back into the module as $specify2 instances\n");
66
+ log("\n");
67
+ }
68
+
69
+ void execute(std::vector<std::string> args, RTLIL::Design *d) override
70
+ {
71
+ log_header(d, "Executing PORTARCS pass. (derive propagation arcs)\n");
72
+
73
+ size_t argidx;
74
+ bool icells_mode = false, write_mode = false, draw_mode = false;
75
+ for (argidx = 1; argidx < args.size(); argidx++) {
76
+ if (args[argidx] == "-icells")
77
+ icells_mode = true;
78
+ else if (args[argidx] == "-write")
79
+ write_mode = true;
80
+ else if (args[argidx] == "-draw")
81
+ draw_mode = true;
82
+ else
83
+ break;
84
+ }
85
+ extra_args(args, argidx, d);
86
+
87
+ d->bufNormalize(true);
88
+ TimingInfo tinfo(d);
89
+
90
+ if (icells_mode) {
91
+ CellTypes ct;
92
+ ct.setup_stdcells_eval();
93
+ for (auto [id, type] : ct.cell_types) {
94
+ auto &tdata = tinfo.data[id];
95
+ tdata.has_inputs = true;
96
+ for (auto inp : type.inputs)
97
+ for (auto out : type.outputs)
98
+ tdata.comb[TimingInfo::BitBit({inp, 0}, {out, 0})] = 1000;
99
+ }
100
+ }
101
+
102
+ for (auto m : d->selected_whole_modules_warn()) {
103
+ bool ambiguous_ports = false;
104
+ SigSpec inputs, outputs;
105
+ for (auto port : m->ports) {
106
+ Wire *w = m->wire(port);
107
+ log_assert(w->port_input || w->port_output);
108
+ if (w->port_input && w->port_output) {
109
+ log_warning("Module '%s' with ambiguous direction on port %s ignored.\n",
110
+ m, w);
111
+ ambiguous_ports = true;
112
+ break;
113
+ }
114
+ if (w->port_input)
115
+ inputs.append(w);
116
+ else
117
+ outputs.append(w);
118
+ }
119
+ if (ambiguous_ports)
120
+ continue;
121
+
122
+ SigSpec ordering;
123
+ {
124
+ TopoSort<SigBit> sort;
125
+
126
+ for (auto cell : m->cells())
127
+ // Ignore all bufnorm helper cells
128
+ if (!cell->type.in(ID($buf), ID($input_port), ID($connect), ID($tribuf))) {
129
+ auto tdata = tinfo.find(cell->type);
130
+ if (tdata == tinfo.end())
131
+ log_cmd_error("Missing timing data for module '%s'.\n", cell->type.unescape());
132
+ for (auto [edge, delay] : tdata->second.comb) {
133
+ auto from = edge.first.get_connection(cell);
134
+ auto to = edge.second.get_connection(cell);
135
+ if (from && to) {
136
+ auto from_c = canonical_bit(from.value());
137
+ if (from_c.wire)
138
+ sort.edge(from_c, to.value());
139
+ }
140
+ }
141
+ }
142
+
143
+ if (!sort.sort())
144
+ log_error("Failed to sort instances in module %s.\n", m);
145
+
146
+ ordering = sort.sorted;
147
+ }
148
+
149
+ dict<SigBit, int*> annotations;
150
+ std::vector<std::unique_ptr<int[]>> allocated;
151
+ std::vector<int*> recycling;
152
+
153
+ auto alloc_for_bit = [&](SigBit bit) {
154
+ if (!recycling.empty()) {
155
+ annotations[bit] = recycling.back();
156
+ recycling.pop_back();
157
+ } else {
158
+ int *p = new int[std::max(1, inputs.size())];
159
+ allocated.emplace_back(p);
160
+ annotations[bit] = p;
161
+ }
162
+ };
163
+
164
+ for (auto bit : outputs) {
165
+ SigBit bit_c = canonical_bit(bit);
166
+ alloc_for_bit(bit_c);
167
+
168
+ // consistency check
169
+ annotations.at(bit_c)[0] = (intptr_t) bit_c.wire;
170
+ }
171
+
172
+ for (int i = ordering.size() - 1; i >= 0; i--) {
173
+ SigBit bit = ordering[i];
174
+
175
+ if (!bit.wire->port_input) {
176
+ auto cell = bit.wire->driverCell();
177
+ auto tdata = tinfo.find(cell->type);
178
+ log_assert(tdata != tinfo.end());
179
+ for (auto [edge, delay] : tdata->second.comb) {
180
+ auto from = edge.first.get_connection(cell);
181
+ auto to = edge.second.get_connection(cell);
182
+ if (from && to && to.value() == bit) {
183
+ auto from_c = canonical_bit(from.value());
184
+ if (from_c.wire) {
185
+ if (!annotations.count(from_c)) {
186
+ alloc_for_bit(from_c);
187
+
188
+ // consistency check
189
+ annotations.at(from_c)[0] = (intptr_t) from_c.wire;
190
+ } else {
191
+ // consistency check
192
+ log_assert(annotations.at(from_c)[0] == ((int) (intptr_t) from_c.wire));
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ if (annotations.count(bit)) {
200
+ // consistency check
201
+ log_assert(annotations.at(bit)[0] == ((int) (intptr_t) bit.wire));
202
+ } else {
203
+ alloc_for_bit(bit);
204
+ }
205
+
206
+ recycling.push_back(annotations.at(ordering[i]));
207
+ }
208
+ log_debug("Allocated %lux%d\n", allocated.size(), inputs.size());
209
+
210
+ for (auto bit : outputs) {
211
+ int *p = annotations.at(canonical_bit(bit));
212
+ for (int i = 0; i < inputs.size(); i++)
213
+ p[i] = -1;
214
+ }
215
+
216
+ for (int i = 0; i < ordering.size(); i++) {
217
+ SigBit bit = ordering[i];
218
+ int *p = annotations.at(bit);
219
+ if (bit.wire->port_input) {
220
+ for (int j = 0; j < inputs.size(); j++)
221
+ p[j] = (j == i) ? 0 : -1;
222
+ } else {
223
+ for (int j = 0; j < inputs.size(); j++)
224
+ p[j] = -1;
225
+
226
+ auto cell = ordering[i].wire->driverCell();
227
+ auto tdata = tinfo.find(cell->type);
228
+ log_assert(tdata != tinfo.end());
229
+ for (auto [edge, delay] : tdata->second.comb) {
230
+ auto from = edge.first.get_connection(cell);
231
+ auto to = edge.second.get_connection(cell);
232
+ if (from && to && to.value() == ordering[i]) {
233
+ auto from_c = canonical_bit(from.value());
234
+ if (from_c.wire) {
235
+ int *q = annotations.at(from_c);
236
+ for (int j = 0; j < inputs.size(); j++)
237
+ if (q[j] >= 0)
238
+ p[j] = std::max(p[j], q[j] + delay);
239
+ }
240
+ }
241
+ }
242
+ }
243
+ }
244
+
245
+ if (draw_mode) {
246
+ auto bit_str = [](SigBit bit) {
247
+ return stringf("%s%d", bit.wire, bit.offset);
248
+ };
249
+
250
+ std::vector<std::string> headings;
251
+ int top_length = 0;
252
+ for (auto bit : inputs) {
253
+ headings.push_back(bit_str(bit));
254
+ top_length = std::max(top_length, (int) headings.back().size());
255
+ }
256
+
257
+ int max_delay = 0;
258
+ for (auto bit : outputs) {
259
+ int *p = annotations.at(canonical_bit(bit));
260
+ for (auto i = 0; i < inputs.size(); i++)
261
+ if (p[i] > max_delay)
262
+ max_delay = p[i];
263
+ }
264
+
265
+ if (max_delay == 0)
266
+ max_delay = 1;
267
+
268
+ log("Delay legend:\n");
269
+ log("\n");
270
+ std::string message = " ";
271
+ for (int i = 0; i < 24; i++)
272
+ message += stringf("\033[48;5;%dm ", 232+i);
273
+ log("%s\033[0m\n", message);
274
+ log(" |%22s|\n", "");
275
+ log(" 0%22s%d\n", "", max_delay);
276
+ for (int k = top_length - 1; k >= 0; k--) {
277
+ message = stringf(" %10s ", "");
278
+ for (auto &h : headings)
279
+ message += (k < (int) h.size()) ? h[k] : ' ';
280
+ log("%s\n", message);
281
+ }
282
+ log("\n");
283
+
284
+ for (auto bit : outputs) {
285
+ message = stringf(" %10s ", bit_str(bit));
286
+ int *p = annotations.at(canonical_bit(bit));
287
+ for (auto i = 0; i < inputs.size(); i++)
288
+ message += stringf("\033[48;5;%dm ", 232 + ((std::max(p[i], 0) * 24) - 1) / max_delay);
289
+ log("%s\033[0m\n", message);
290
+ }
291
+ }
292
+
293
+ if (write_mode) {
294
+ for (auto bit : outputs) {
295
+ int *p = annotations.at(canonical_bit(bit));
296
+ for (auto i = 0; i < inputs.size(); i++) {
297
+ if (p[i] >= 0) {
298
+ Cell *spec = m->addCell(NEW_ID, ID($specify2));
299
+ spec->setParam(ID::SRC_WIDTH, 1);
300
+ spec->setParam(ID::DST_WIDTH, 1);
301
+ spec->setParam(ID::T_FALL_MAX, p[i]);
302
+ spec->setParam(ID::T_FALL_TYP, p[i]);
303
+ spec->setParam(ID::T_FALL_MIN, p[i]);
304
+ spec->setParam(ID::T_RISE_MAX, p[i]);
305
+ spec->setParam(ID::T_RISE_TYP, p[i]);
306
+ spec->setParam(ID::T_RISE_MIN, p[i]);
307
+ spec->setParam(ID::SRC_DST_POL, false);
308
+ spec->setParam(ID::SRC_DST_PEN, false);
309
+ spec->setParam(ID::FULL, false);
310
+ spec->setPort(ID::EN, Const(1, 1));
311
+ spec->setPort(ID::SRC, inputs[i]);
312
+ spec->setPort(ID::DST, bit);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ }
318
+ d->bufNormalize(false);
319
+ }
320
+ } PortarcsPass;
321
+
322
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/portlist.cc ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct PortlistPass : public Pass {
28
+ PortlistPass() : Pass("portlist", "list (top-level) ports") { }
29
+ bool formatted_help() override {
30
+ auto *help = PrettyHelp::get_current();
31
+ help->set_group("passes/status");
32
+ return false;
33
+ }
34
+ void help() override
35
+ {
36
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
37
+ log("\n");
38
+ log(" portlist [options] [selection]\n");
39
+ log("\n");
40
+ log("This command lists all module ports found in the selected modules.\n");
41
+ log("\n");
42
+ log("If no selection is provided then it lists the ports on the top module.\n");
43
+ log("\n");
44
+ log(" -m\n");
45
+ log(" print verilog blackbox module definitions instead of port lists\n");
46
+ log("\n");
47
+ }
48
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
49
+ {
50
+ bool m_mode = false;
51
+
52
+ size_t argidx;
53
+ for (argidx = 1; argidx < args.size(); argidx++) {
54
+ if (args[argidx] == "-m") {
55
+ m_mode = true;
56
+ continue;
57
+ }
58
+ break;
59
+ }
60
+
61
+ bool first_module = true;
62
+
63
+ auto handle_module = [&](RTLIL::Module *module) {
64
+ vector<string> ports;
65
+ if (first_module)
66
+ first_module = false;
67
+ else
68
+ log("\n");
69
+ for (auto port : module->ports) {
70
+ auto *w = module->wire(port);
71
+ ports.push_back(stringf("%s [%d:%d] %s", w->port_input ? w->port_output ? "inout" : "input" : "output",
72
+ w->upto ? w->start_offset : w->start_offset + w->width - 1,
73
+ w->upto ? w->start_offset + w->width - 1 : w->start_offset,
74
+ w));
75
+ }
76
+ log("module %s%s\n", module, m_mode ? " (" : "");
77
+ for (int i = 0; i < GetSize(ports); i++)
78
+ log("%s%s\n", ports[i], m_mode && i+1 < GetSize(ports) ? "," : "");
79
+ if (m_mode) {
80
+ log(");\n");
81
+ log("endmodule\n");
82
+ }
83
+ };
84
+
85
+ if (argidx == args.size())
86
+ {
87
+ auto *top = design->top_module();
88
+ if (top == nullptr)
89
+ log_cmd_error("Can't find top module in current design!\n");
90
+ handle_module(top);
91
+ }
92
+ else
93
+ {
94
+ extra_args(args, argidx, design);
95
+ for (auto module : design->selected_modules())
96
+ handle_module(module);
97
+ }
98
+ }
99
+ } PortlistPass;
100
+
101
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/printattrs.cc ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2020 Alberto Gonzalez <boqwxp@airmail.cc>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/log_help.h"
22
+
23
+ USING_YOSYS_NAMESPACE
24
+ PRIVATE_NAMESPACE_BEGIN
25
+
26
+ struct PrintAttrsPass : public Pass {
27
+ PrintAttrsPass() : Pass("printattrs", "print attributes of selected objects") { }
28
+ bool formatted_help() override {
29
+ auto *help = PrettyHelp::get_current();
30
+ help->set_group("passes/status");
31
+ return false;
32
+ }
33
+ void help() override
34
+ {
35
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
36
+ log("\n");
37
+ log(" printattrs [selection]\n");
38
+ log("\n");
39
+ log("Print all attributes of the selected objects.\n");
40
+ log("\n");
41
+ log("\n");
42
+ }
43
+
44
+ static std::string get_indent_str(const unsigned int indent) {
45
+ return stringf("%*s", indent, "");
46
+ }
47
+
48
+ static void log_const(PooledName s, const RTLIL::Const &x, const unsigned int indent) {
49
+ if (x.flags & RTLIL::CONST_FLAG_STRING)
50
+ log("%s(* %s=\"%s\" *)\n", get_indent_str(indent), s.unescape(), x.decode_string());
51
+ else if (x.flags == RTLIL::CONST_FLAG_NONE || x.flags == RTLIL::CONST_FLAG_SIGNED)
52
+ log("%s(* %s=%s *)\n", get_indent_str(indent), s.unescape(), x.as_string());
53
+ else
54
+ log_assert(x.flags & RTLIL::CONST_FLAG_STRING || x.flags == RTLIL::CONST_FLAG_NONE); //intended to fail
55
+ }
56
+
57
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
58
+ {
59
+ size_t argidx = 1;
60
+ extra_args(args, argidx, design);
61
+
62
+ unsigned int indent = 0;
63
+ for (auto mod : design->selected_modules())
64
+ {
65
+ if (design->selected_whole_module(mod)) {
66
+ log("%s%s\n", get_indent_str(indent), mod);
67
+ indent += 2;
68
+ for (auto &it : mod->attributes)
69
+ log_const(PooledName(design, it.first), it.second, indent);
70
+ }
71
+
72
+ for (auto cell : mod->selected_cells()) {
73
+ log("%s%s\n", get_indent_str(indent), cell);
74
+ indent += 2;
75
+ for (auto &it : cell->attributes)
76
+ log_const(PooledName(design, it.first), it.second, indent);
77
+ indent -= 2;
78
+ }
79
+
80
+ for (auto wire : mod->selected_wires()) {
81
+ log("%s%s\n", get_indent_str(indent), wire);
82
+ indent += 2;
83
+ for (auto &it : wire->attributes)
84
+ log_const(PooledName(design, it.first), it.second, indent);
85
+ indent -= 2;
86
+ }
87
+
88
+ if (design->selected_whole_module(mod))
89
+ indent -= 2;
90
+ }
91
+
92
+ log("\n");
93
+ }
94
+ } PrintAttrsPass;
95
+
96
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/rename.cc ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/rtlil.h"
22
+ #include "kernel/log.h"
23
+ #include "backends/verilog/verilog_backend.h"
24
+ #include "kernel/twine.h"
25
+
26
+ USING_YOSYS_NAMESPACE
27
+ PRIVATE_NAMESPACE_BEGIN
28
+
29
+ static void rename_in_module(RTLIL::Module *module, std::string from_name, std::string to_name, bool flag_output)
30
+ {
31
+ from_name = RTLIL::escape_id(from_name);
32
+ to_name = RTLIL::escape_id(to_name);
33
+
34
+ IdString to_ref = module->twines().find(to_name);
35
+ if (module->count_id(to_ref))
36
+ log_cmd_error("There is already an object `%s' in module `%s'.\n", RTLIL::unescape_id(to_name), module);
37
+
38
+ IdString from_ref = module->twines().find(from_name);
39
+ RTLIL::Wire *wire_to_rename = module->wire(from_ref);
40
+ RTLIL::Cell *cell_to_rename = module->cell(from_ref);
41
+
42
+ if (wire_to_rename != nullptr) {
43
+ log("Renaming wire %s to %s in module %s.\n", wire_to_rename, RTLIL::unescape_id(to_name), module);
44
+ module->rename(wire_to_rename, to_name);
45
+ if (wire_to_rename->port_id || flag_output) {
46
+ if (flag_output)
47
+ wire_to_rename->port_output = true;
48
+ module->fixup_ports();
49
+ }
50
+ return;
51
+ }
52
+
53
+ if (cell_to_rename != nullptr) {
54
+ if (flag_output)
55
+ log_cmd_error("Called with -output but the specified object is a cell.\n");
56
+ log("Renaming cell %s to %s in module %s.\n", cell_to_rename, RTLIL::unescape_id(to_name), module);
57
+ module->rename(cell_to_rename, to_name);
58
+ return;
59
+ }
60
+
61
+ log_cmd_error("Object `%s' not found!\n", RTLIL::unescape_id(from_name));
62
+ }
63
+
64
+ static IdString derive_name_from_src(RTLIL::Module *module, const std::string &src, int counter)
65
+ {
66
+ std::string src_base = src.substr(0, src.find('|'));
67
+ if (src_base.empty())
68
+ return module->twines().add(stringf("$%d", counter));
69
+ IdString base = module->twines().add("\\" + src_base);
70
+ return module->twines().add(base, stringf("$%d", counter));
71
+ }
72
+
73
+ static IdString derive_name_from_cell_output_wire(const RTLIL::Cell *cell, string suffix, bool move_to_cell)
74
+ {
75
+ // Find output
76
+ const SigSpec *output = nullptr;
77
+ int num_outputs = 0;
78
+ for (auto &connection : cell->connections()) {
79
+ if (cell->output(connection.first)) {
80
+ output = &connection.second;
81
+ num_outputs++;
82
+ }
83
+ }
84
+
85
+ if (num_outputs != 1) // Skip cells thad drive multiple outputs
86
+ return cell->name;
87
+
88
+ std::string name = "";
89
+ for (auto &chunk : output->chunks()) {
90
+ // Skip cells that drive privately named wires
91
+ if (!chunk.wire || chunk.wire->name.str()[0] == '$')
92
+ return cell->name;
93
+
94
+ if (name != "")
95
+ name += "$";
96
+
97
+ name += chunk.wire->name.str();
98
+ if (chunk.wire->width != chunk.width) {
99
+ int lhs = chunk.wire->to_hdl_index(chunk.offset + chunk.width - 1);
100
+ int rhs = chunk.wire->to_hdl_index(chunk.offset);
101
+
102
+ if (lhs != rhs)
103
+ name += stringf("[%d:%d]", lhs, rhs);
104
+ else
105
+ name += stringf("[%d]", lhs);
106
+ }
107
+ }
108
+
109
+ RTLIL::Wire *wire;
110
+
111
+ if (move_to_cell) {
112
+ IdString name_ref = cell->twines().find(name);
113
+ if (!(wire = cell->module->wire(name_ref)) || !(wire->port_input || wire->port_output))
114
+ return cell->twines().add(std::move(name));
115
+ }
116
+
117
+ if (suffix.empty()) {
118
+ suffix = cell->type.str();
119
+ }
120
+ return cell->twines().add(name + suffix);
121
+ }
122
+
123
+ static bool rename_witness(RTLIL::Design *design, dict<RTLIL::Module *, int> &cache, RTLIL::Module *module)
124
+ {
125
+ auto cached = cache.find(module);
126
+ if (cached != cache.end()) {
127
+ if (cached->second == -1)
128
+ log_error("Cannot rename witness signals in a design containing recursive instantiations.\n");
129
+ return cached->second;
130
+ }
131
+ cache.emplace(module, -1);
132
+
133
+ std::vector<std::pair<Cell *, IdString>> renames;
134
+
135
+ bool has_witness_signals = false;
136
+ for (auto cell : module->cells())
137
+ {
138
+ RTLIL::Module *impl = design->module(cell->type);
139
+ if (impl != nullptr) {
140
+ bool witness_in_cell = rename_witness(design, cache, impl);
141
+ has_witness_signals |= witness_in_cell;
142
+ if (witness_in_cell && !cell->name.isPublic()) {
143
+ std::string name = cell->name.str().substr(1);
144
+ for (auto &c : name)
145
+ if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_')
146
+ c = '_';
147
+ auto new_id = module->uniquify("\\_witness_." + name);
148
+ cell->set_hdlname_attribute({ "_witness_", strstr(module->twines().str(new_id).c_str(), ".") + 1 });
149
+ renames.emplace_back(cell, new_id);
150
+ }
151
+ }
152
+
153
+ if (cell->type.in(ID($anyconst), ID($anyseq), ID($anyinit), ID($allconst), ID($allseq))) {
154
+ has_witness_signals = true;
155
+ IdString QY;
156
+ bool clk2fflogic = false;
157
+ if (cell->type == ID($anyinit))
158
+ QY = (clk2fflogic = cell->get_bool_attribute(ID(clk2fflogic))) ? ID::D : ID::Q;
159
+ else
160
+ QY = ID::Y;
161
+ auto sig_out = cell->getPort(QY);
162
+
163
+ for (auto chunk : sig_out.chunks()) {
164
+ if (chunk.is_wire() && !chunk.wire->name.isPublic()) {
165
+ std::string name = stringf("%s_%s", cell->type.str().substr(1), cell->name.str().substr(1));
166
+ for (auto &c : name)
167
+ if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_')
168
+ c = '_';
169
+ auto new_id = module->uniquify("\\_witness_." + name);
170
+ auto new_wire = module->addWire(new_id, GetSize(sig_out));
171
+ new_wire->set_hdlname_attribute({ "_witness_", strstr(module->twines().str(new_id).c_str(), ".") + 1 });
172
+ if (clk2fflogic)
173
+ module->connect({new_wire, sig_out});
174
+ else
175
+ module->connect({sig_out, new_wire});
176
+ cell->setPort(QY, new_wire);
177
+ break;
178
+ }
179
+ }
180
+ }
181
+
182
+
183
+ if (cell->type.in(ID($assert), ID($assume), ID($cover), ID($live), ID($fair), ID($check))) {
184
+ has_witness_signals = true;
185
+ if (cell->name.isPublic())
186
+ continue;
187
+ std::string name = stringf("%s_%s", cell->type.str().substr(1), cell->name.str().substr(1));
188
+ for (auto &c : name)
189
+ if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_')
190
+ c = '_';
191
+ auto new_id = module->uniquify("\\_witness_." + name);
192
+ renames.emplace_back(cell, new_id);
193
+ cell->set_hdlname_attribute({ "_witness_", strstr(module->twines().str(new_id).c_str(), ".") + 1 });
194
+ }
195
+ }
196
+ for (auto rename : renames) {
197
+ module->rename(rename.first, rename.second);
198
+ }
199
+
200
+ cache[module] = has_witness_signals;
201
+ return has_witness_signals;
202
+ }
203
+
204
+ static std::string renamed_unescaped(const std::string& str)
205
+ {
206
+ std::string new_str = "";
207
+
208
+ if ('0' <= str[0] && str[0] <= '9')
209
+ new_str = '_' + new_str;
210
+
211
+ for (char c : str) {
212
+ if (VERILOG_BACKEND::char_is_verilog_escaped(c))
213
+ new_str += '_';
214
+ else
215
+ new_str += c;
216
+ }
217
+
218
+ if (VERILOG_BACKEND::verilog_keywords().count(str))
219
+ new_str += "_";
220
+
221
+ return new_str;
222
+ }
223
+
224
+ struct RenamePass : public Pass {
225
+ RenamePass() : Pass("rename", "rename object in the design") { }
226
+ void help() override
227
+ {
228
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
229
+ log("\n");
230
+ log(" rename old_name new_name\n");
231
+ log("\n");
232
+ log("Rename the specified object. Note that selection patterns are not supported\n");
233
+ log("by this command.\n");
234
+ log("\n");
235
+ log("\n");
236
+ log("\n");
237
+ log(" rename -output old_name new_name\n");
238
+ log("\n");
239
+ log("Like above, but also make the wire an output. This will fail if the object is\n");
240
+ log("not a wire.\n");
241
+ log("\n");
242
+ log("\n");
243
+ log(" rename -src [selection]\n");
244
+ log("\n");
245
+ log("Assign names auto-generated from the src attribute to all selected wires and\n");
246
+ log("cells with private names.\n");
247
+ log("\n");
248
+ log("\n");
249
+ log(" rename -wire [selection] [-move-to-cell] [-suffix <suffix>]\n");
250
+ log("\n");
251
+ log("Assign auto-generated names based on the wires they drive to all selected\n");
252
+ log("cells with private names. Ignores cells driving privatly named wires.\n");
253
+ log("By default, the cell is named after the wire with the cell type as suffix.\n");
254
+ log("The -suffix option can be used to set the suffix to the given string instead.\n");
255
+ log("\n");
256
+ log("The -move-to-cell option can be used to name the cell after the wire without\n");
257
+ log("any suffix. If this would lead to conflicts, the suffix is added to the wire\n");
258
+ log("instead. For cells driving ports, the -move-to-cell option is ignored.\n");
259
+ log("\n");
260
+ log("\n");
261
+ log(" rename -enumerate [-pattern <pattern>] [selection]\n");
262
+ log("\n");
263
+ log("Assigns auto-generated names to objects used in formal verification\n");
264
+ log("that do not have a public name. This applies to all formal property\n");
265
+ log("cells, $any*/$all* output wires, and their containing cells.\n");
266
+ log("\n");
267
+ log("\n");
268
+ log(" rename -witness\n");
269
+ log("\n");
270
+ log("Assigns auto-generated names to objects used in formal verification\n");
271
+ log("that do not have a public name. This applies to all formal property\n");
272
+ log("cells ($assert, $assume, $cover, $live, $fair, $check), $any*/$all*\n");
273
+ log("output wires, and their containing cells.\n");
274
+ log("\n");
275
+ log("\n");
276
+ log(" rename -hide [selection]\n");
277
+ log("\n");
278
+ log("Assign private names (the ones with $-prefix) to all selected wires and cells\n");
279
+ log("with public names. This ignores all selected ports.\n");
280
+ log("\n");
281
+ log("\n");
282
+ log(" rename -top new_name\n");
283
+ log("\n");
284
+ log("Rename top module.\n");
285
+ log("\n");
286
+ log("\n");
287
+ log(" rename -scramble-name [-seed <seed>] [selection]\n");
288
+ log("\n");
289
+ log("Assign randomly-generated names to all selected wires and cells. The seed option\n");
290
+ log("can be used to change the random number generator seed from the default, but it\n");
291
+ log("must be non-zero.\n");
292
+ log("\n");
293
+ log("\n");
294
+ log(" rename -unescape [selection]\n");
295
+ log("\n");
296
+ log("Rename all selected public wires and cells that have to be escaped in Verilog.\n");
297
+ log("Replaces characters with underscores or adds additional underscores and numbers.\n");
298
+ log("\n");
299
+ }
300
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
301
+ {
302
+ std::string pattern_prefix = "_", pattern_suffix = "_";
303
+ std::string cell_suffix = "";
304
+ bool flag_src = false;
305
+ bool flag_wire = false;
306
+ bool flag_move_to_cell = false;
307
+ bool flag_enumerate = false;
308
+ bool flag_witness = false;
309
+ bool flag_hide = false;
310
+ bool flag_top = false;
311
+ bool flag_output = false;
312
+ bool flag_scramble_name = false;
313
+ bool flag_unescape = false;
314
+ bool got_mode = false;
315
+ unsigned int seed = 1;
316
+
317
+ size_t argidx;
318
+ for (argidx = 1; argidx < args.size(); argidx++)
319
+ {
320
+ std::string arg = args[argidx];
321
+ if (arg == "-src" && !got_mode) {
322
+ flag_src = true;
323
+ got_mode = true;
324
+ continue;
325
+ }
326
+ if (arg == "-output" && !got_mode) {
327
+ flag_output = true;
328
+ got_mode = true;
329
+ continue;
330
+ }
331
+ if (arg == "-wire" && !got_mode) {
332
+ flag_wire = true;
333
+ got_mode = true;
334
+ continue;
335
+ }
336
+ if (arg == "-enumerate" && !got_mode) {
337
+ flag_enumerate = true;
338
+ got_mode = true;
339
+ continue;
340
+ }
341
+ if (arg == "-witness" && !got_mode) {
342
+ flag_witness = true;
343
+ got_mode = true;
344
+ continue;
345
+ }
346
+ if (arg == "-hide" && !got_mode) {
347
+ flag_hide = true;
348
+ got_mode = true;
349
+ continue;
350
+ }
351
+ if (arg == "-top" && !got_mode) {
352
+ flag_top = true;
353
+ got_mode = true;
354
+ continue;
355
+ }
356
+ if (arg == "-scramble-name" && !got_mode) {
357
+ flag_scramble_name = true;
358
+ got_mode = true;
359
+ continue;
360
+ }
361
+ if (arg == "-unescape" && !got_mode) {
362
+ flag_unescape = true;
363
+ got_mode = true;
364
+ continue;
365
+ }
366
+ if (arg == "-move-to-cell" && flag_wire && !flag_move_to_cell) {
367
+ flag_move_to_cell = true;
368
+ continue;
369
+ }
370
+ if (arg == "-pattern" && argidx+1 < args.size() && args[argidx+1].find('%') != std::string::npos) {
371
+ int pos = args[++argidx].find('%');
372
+ pattern_prefix = args[argidx].substr(0, pos);
373
+ pattern_suffix = args[argidx].substr(pos+1);
374
+ continue;
375
+ }
376
+ if (arg == "-suffix" && argidx + 1 < args.size()) {
377
+ cell_suffix = args[++argidx];
378
+ continue;
379
+ }
380
+ if (arg == "-seed" && argidx+1 < args.size()) {
381
+ seed = std::stoi(args[++argidx]);
382
+ continue;
383
+ }
384
+ break;
385
+ }
386
+
387
+ if (flag_src)
388
+ {
389
+ extra_args(args, argidx, design);
390
+
391
+ for (auto module : design->selected_modules())
392
+ {
393
+ int counter = 0;
394
+ dict<RTLIL::Wire *, IdString> new_wire_names;
395
+ dict<RTLIL::Cell *, IdString> new_cell_names;
396
+
397
+ for (auto wire : module->selected_wires())
398
+ if (!wire->name.isPublic())
399
+ new_wire_names.emplace(wire, module->uniquify(derive_name_from_src(module, wire->get_src_attribute(), counter++)));
400
+
401
+ for (auto cell : module->selected_cells())
402
+ if (!cell->name.isPublic())
403
+ new_cell_names.emplace(cell, module->uniquify(derive_name_from_src(module, cell->get_src_attribute(), counter++)));
404
+
405
+ for (auto &it : new_wire_names)
406
+ module->rename(it.first, it.second);
407
+
408
+ for (auto &it : new_cell_names)
409
+ module->rename(it.first, it.second);
410
+ }
411
+ }
412
+ else
413
+ if (flag_wire)
414
+ {
415
+ extra_args(args, argidx, design);
416
+
417
+ for (auto module : design->selected_modules()) {
418
+ dict<RTLIL::Cell *, IdString> new_cell_names;
419
+ for (auto cell : module->selected_cells())
420
+ if (!cell->name.isPublic())
421
+ new_cell_names[cell] = derive_name_from_cell_output_wire(cell, cell_suffix, flag_move_to_cell);
422
+ for (auto &[cell, new_name] : new_cell_names) {
423
+ if (flag_move_to_cell) {
424
+ RTLIL::Wire *found_wire = module->wire(new_name);
425
+ if (found_wire) {
426
+ std::string wire_suffix = cell_suffix;
427
+ if (wire_suffix.empty()) {
428
+ for (auto const &[port, _] : cell->connections()) {
429
+ if (cell->output(port)) {
430
+ wire_suffix += stringf("%s.%s", cell->type, module->twines().str(port).substr(1));
431
+ break;
432
+ }
433
+ }
434
+ }
435
+ module->rename(found_wire, found_wire->name.str() + wire_suffix);
436
+ }
437
+ }
438
+ module->rename(cell, new_name);
439
+ }
440
+ }
441
+ }
442
+ else
443
+ if (flag_enumerate)
444
+ {
445
+ extra_args(args, argidx, design);
446
+
447
+ for (auto module : design->selected_modules())
448
+ {
449
+ int counter = 0;
450
+ dict<RTLIL::Wire *, IdString> new_wire_names;
451
+ dict<RTLIL::Cell *, IdString> new_cell_names;
452
+
453
+ for (auto wire : module->selected_wires())
454
+ if (!wire->name.isPublic()) {
455
+ std::string buf;
456
+ do buf = stringf("\\%s%d%s", pattern_prefix, counter++, pattern_suffix);
457
+ while (module->wire(buf) != nullptr);
458
+ new_wire_names[wire] = design->twines().add(std::move(buf));
459
+ }
460
+
461
+ for (auto cell : module->selected_cells())
462
+ if (!cell->name.isPublic()) {
463
+ std::string buf;
464
+ do buf = stringf("\\%s%d%s", pattern_prefix, counter++, pattern_suffix);
465
+ while (module->cell(buf) != nullptr);
466
+ new_cell_names[cell] = design->twines().add(std::move(buf));
467
+ }
468
+
469
+ for (auto &it : new_wire_names)
470
+ module->rename(it.first, it.second);
471
+
472
+ for (auto &it : new_cell_names)
473
+ module->rename(it.first, it.second);
474
+ }
475
+ }
476
+ else
477
+ if (flag_witness)
478
+ {
479
+ extra_args(args, argidx, design, false);
480
+
481
+ RTLIL::Module *module = design->top_module();
482
+
483
+ if (module == nullptr)
484
+ log_cmd_error("No top module found!\n");
485
+
486
+ dict<RTLIL::Module *, int> cache;
487
+ rename_witness(design, cache, module);
488
+ }
489
+ else
490
+ if (flag_hide)
491
+ {
492
+ extra_args(args, argidx, design);
493
+
494
+ for (auto module : design->selected_modules())
495
+ {
496
+ dict<RTLIL::Wire *, IdString> new_wire_names;
497
+ dict<RTLIL::Cell *, IdString> new_cell_names;
498
+
499
+ for (auto wire : module->selected_wires())
500
+ if (wire->name.isPublic() && wire->port_id == 0)
501
+ new_wire_names[wire] = module->twines().add(NEW_ID);
502
+
503
+ for (auto cell : module->selected_cells())
504
+ if (cell->name.isPublic())
505
+ new_cell_names[cell] = module->twines().add(NEW_ID);
506
+
507
+ for (auto &it : new_wire_names)
508
+ module->rename(it.first, it.second);
509
+
510
+ for (auto &it : new_cell_names)
511
+ module->rename(it.first, it.second);
512
+ }
513
+ }
514
+ else
515
+ if (flag_top)
516
+ {
517
+ if (argidx+1 != args.size())
518
+ log_cmd_error("Invalid number of arguments!\n");
519
+
520
+ IdString new_name = design->twines().add(RTLIL::escape_id(args[argidx]));
521
+ RTLIL::Module *module = design->top_module();
522
+
523
+ if (module == nullptr)
524
+ log_cmd_error("No top module found!\n");
525
+
526
+ log("Renaming module %s to %s.\n", module, PooledName(design, new_name).unescape());
527
+ design->rename(module, new_name);
528
+ }
529
+ else
530
+ if (flag_scramble_name)
531
+ {
532
+ extra_args(args, argidx, design);
533
+
534
+ if (seed == 0)
535
+ log_error("Seed for -scramble-name cannot be zero.\n");
536
+
537
+ for (auto module : design->selected_modules())
538
+ {
539
+ if (module->memories.size() != 0 || module->processes.size() != 0) {
540
+ log_warning("Skipping module %s with unprocessed memories or processes\n", module);
541
+ continue;
542
+ }
543
+
544
+ dict<RTLIL::Wire *, IdString> new_wire_names;
545
+ dict<RTLIL::Cell *, IdString> new_cell_names;
546
+
547
+ for (auto wire : module->selected_wires())
548
+ if (wire->port_id == 0) {
549
+ seed = mkhash_xorshift(seed);
550
+ new_wire_names[wire] = module->twines().add(stringf("$_%u_", seed));
551
+ }
552
+
553
+ for (auto cell : module->selected_cells()) {
554
+ seed = mkhash_xorshift(seed);
555
+ new_cell_names[cell] = module->twines().add(stringf("$_%u_", seed));
556
+ }
557
+
558
+ for (auto &it : new_wire_names)
559
+ module->rename(it.first, it.second);
560
+
561
+ for (auto &it : new_cell_names)
562
+ module->rename(it.first, it.second);
563
+ }
564
+ }
565
+ else if (flag_unescape)
566
+ {
567
+ extra_args(args, argidx, design);
568
+
569
+ for (auto module : design->selected_modules())
570
+ {
571
+ dict<RTLIL::Wire *, IdString> new_wire_names;
572
+ dict<RTLIL::Cell *, IdString> new_cell_names;
573
+
574
+ for (auto wire : module->selected_wires()) {
575
+ auto name = wire->name.str();
576
+ if (name[0] != '\\')
577
+ continue;
578
+ name = name.substr(1);
579
+ if (!VERILOG_BACKEND::id_is_verilog_escaped(name))
580
+ continue;
581
+ new_wire_names[wire] = module->uniquify("\\" + renamed_unescaped(name));
582
+ auto new_name = module->twines().str(new_wire_names[wire]).substr(1);
583
+ if (VERILOG_BACKEND::id_is_verilog_escaped(new_name))
584
+ log_error("Failed to rename wire %s -> %s\n", name, new_name);
585
+ }
586
+
587
+ for (auto cell : module->selected_cells()) {
588
+ auto name = cell->name.str();
589
+ if (name[0] != '\\')
590
+ continue;
591
+ name = name.substr(1);
592
+ if (!VERILOG_BACKEND::id_is_verilog_escaped(name))
593
+ continue;
594
+ new_cell_names[cell] = module->uniquify("\\" + renamed_unescaped(name));
595
+ auto new_name = module->twines().str(new_cell_names[cell]).substr(1);
596
+ if (VERILOG_BACKEND::id_is_verilog_escaped(new_name))
597
+ log_error("Failed to rename cell %s -> %s\n", name, new_name);
598
+ }
599
+
600
+ for (auto &it : new_wire_names)
601
+ module->rename(it.first, it.second);
602
+
603
+ for (auto &it : new_cell_names)
604
+ module->rename(it.first, it.second);
605
+
606
+ module->fixup_ports();
607
+ }
608
+ }
609
+ else
610
+ {
611
+ if (argidx+2 != args.size())
612
+ log_cmd_error("Invalid number of arguments!\n");
613
+
614
+ std::string from_name = args[argidx++];
615
+ std::string to_name = args[argidx++];
616
+
617
+ if (!design->selected_active_module.empty())
618
+ {
619
+ if (design->module(design->selected_active_module) != nullptr)
620
+ rename_in_module(design->module(design->selected_active_module), from_name, to_name, flag_output);
621
+ }
622
+ else
623
+ {
624
+ if (flag_output)
625
+ log_cmd_error("Mode -output requires that there is an active module selected.\n");
626
+
627
+ RTLIL::Module *module_to_rename = nullptr;
628
+ for (auto module : design->modules()) {
629
+ std::string module_name_str = module->name.str();
630
+ if (module_name_str == from_name || RTLIL::unescape_id(module_name_str) == from_name) {
631
+ module_to_rename = module;
632
+ break;
633
+ }
634
+ }
635
+
636
+ if (module_to_rename != nullptr) {
637
+ to_name = RTLIL::escape_id(to_name);
638
+ log("Renaming module %s to %s.\n", module_to_rename->name, to_name);
639
+ design->rename(module_to_rename, to_name);
640
+ } else
641
+ log_cmd_error("Object `%s' not found!\n", from_name);
642
+ }
643
+ }
644
+ }
645
+ } RenamePass;
646
+
647
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/scatter.cc ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/celltypes.h"
22
+ #include "kernel/rtlil.h"
23
+ #include "kernel/log.h"
24
+
25
+ USING_YOSYS_NAMESPACE
26
+ PRIVATE_NAMESPACE_BEGIN
27
+
28
+ struct ScatterPass : public Pass {
29
+ ScatterPass() : Pass("scatter", "add additional intermediate nets") { }
30
+ void help() override
31
+ {
32
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
33
+ log("\n");
34
+ log(" scatter [selection]\n");
35
+ log("\n");
36
+ log("This command adds additional intermediate nets on all cell ports. This is used\n");
37
+ log("for testing the correct use of the SigMap helper in passes. If you don't know\n");
38
+ log("what this means: don't worry -- you only need this pass when testing your own\n");
39
+ log("extensions to Yosys.\n");
40
+ log("\n");
41
+ log("Use the opt_clean command to get rid of the additional nets.\n");
42
+ log("\n");
43
+ }
44
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
45
+ {
46
+ CellTypes ct(design);
47
+ extra_args(args, 1, design);
48
+
49
+ for (auto module : design->selected_modules())
50
+ {
51
+ for (auto cell : module->cells()) {
52
+ dict<RTLIL::IdString, RTLIL::SigSig> new_connections;
53
+ for (auto conn : cell->connections())
54
+ new_connections.emplace(conn.first, RTLIL::SigSig(conn.second, module->addWire(NEW_ID, GetSize(conn.second))));
55
+ for (auto &it : new_connections) {
56
+ if (ct.cell_output(cell->type, it.first))
57
+ module->connect(RTLIL::SigSig(it.second.first, it.second.second));
58
+ else
59
+ module->connect(RTLIL::SigSig(it.second.second, it.second.first));
60
+ cell->setPort(it.first, it.second.second);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ } ScatterPass;
66
+
67
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/scc.cc ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ // [[CITE]] Tarjan's strongly connected components algorithm
21
+ // Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137/0201010
22
+ // http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
23
+
24
+ #include "kernel/yosys.h"
25
+ #include "kernel/celltypes.h"
26
+ #include "kernel/sigtools.h"
27
+ #include "kernel/log_help.h"
28
+
29
+ USING_YOSYS_NAMESPACE
30
+ PRIVATE_NAMESPACE_BEGIN
31
+
32
+ struct SccWorker
33
+ {
34
+ RTLIL::Design *design;
35
+ RTLIL::Module *module;
36
+ SigMap sigmap;
37
+ CellTypes ct, specifyCells;
38
+
39
+ pool<RTLIL::Cell*> workQueue;
40
+ dict<RTLIL::Cell*, pool<RTLIL::Cell*>> cellToNextCell;
41
+ dict<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;
42
+
43
+ dict<RTLIL::Cell*, std::pair<int, int>> cellLabels;
44
+ dict<RTLIL::Cell*, int> cellDepth;
45
+ pool<RTLIL::Cell*> cellsOnStack;
46
+ std::vector<RTLIL::Cell*> cellStack;
47
+ int labelCounter;
48
+
49
+ dict<RTLIL::Cell*, int> cell2scc;
50
+ std::vector<pool<RTLIL::Cell*>> sccList;
51
+
52
+ void run(RTLIL::Cell *cell, int depth, int maxDepth)
53
+ {
54
+ log_assert(workQueue.count(cell) > 0);
55
+
56
+ workQueue.erase(cell);
57
+ cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
58
+ labelCounter++;
59
+
60
+ cellsOnStack.insert(cell);
61
+ cellStack.push_back(cell);
62
+
63
+ if (maxDepth >= 0)
64
+ cellDepth[cell] = depth;
65
+
66
+ for (auto nextCell : cellToNextCell[cell])
67
+ if (cellLabels.count(nextCell) == 0) {
68
+ run(nextCell, depth+1, maxDepth);
69
+ cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
70
+ } else
71
+ if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
72
+ cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
73
+ }
74
+
75
+ if (cellLabels[cell].first == cellLabels[cell].second)
76
+ {
77
+ if (cellStack.back() == cell)
78
+ {
79
+ cellStack.pop_back();
80
+ cellsOnStack.erase(cell);
81
+ }
82
+ else
83
+ {
84
+ std::string message = "Found an SCC:";
85
+ pool<RTLIL::Cell*> scc;
86
+ while (cellsOnStack.count(cell) > 0) {
87
+ RTLIL::Cell *c = cellStack.back();
88
+ cellStack.pop_back();
89
+ cellsOnStack.erase(c);
90
+ message += stringf(" %s", c);
91
+ cell2scc[c] = sccList.size();
92
+ scc.insert(c);
93
+ }
94
+ sccList.push_back(scc);
95
+ log("%s\n", message);
96
+ }
97
+ }
98
+ }
99
+
100
+ SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, bool specifyMode, int maxDepth) :
101
+ design(design), module(module), sigmap(module)
102
+ {
103
+ if (module->processes.size() > 0) {
104
+ log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name);
105
+ return;
106
+ }
107
+
108
+ if (allCellTypes) {
109
+ ct.setup(design);
110
+ } else {
111
+ ct.setup_internals();
112
+ ct.setup_stdcells();
113
+ }
114
+
115
+ // Discover boxes with specify rules in them, for special handling.
116
+ if (specifyMode) {
117
+ for (auto mod : design->modules())
118
+ if (mod->get_blackbox_attribute(false))
119
+ for (auto cell : mod->cells())
120
+ if (cell->type == ID($specify2))
121
+ {
122
+ specifyCells.setup_module(mod);
123
+ break;
124
+ }
125
+ }
126
+
127
+ SigPool selectedSignals;
128
+ SigSet<RTLIL::Cell*> sigToNextCells;
129
+
130
+ for (auto &it : module->wires_)
131
+ if (design->selected(module, it.second))
132
+ selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));
133
+
134
+ for (auto &it : module->cells_)
135
+ {
136
+ RTLIL::Cell *cell = it.second;
137
+
138
+ if (!design->selected(module, cell))
139
+ continue;
140
+
141
+ if (!allCellTypes && !ct.cell_known(cell->type) && !specifyCells.cell_known(cell->type))
142
+ continue;
143
+
144
+ workQueue.insert(cell);
145
+
146
+ RTLIL::SigSpec inputSignals, outputSignals;
147
+
148
+ if (specifyCells.cell_known(cell->type)) {
149
+ // Use specify rules of the type `(X => Y) = NN` to look for asynchronous paths in boxes.
150
+ for (auto subcell : design->module(cell->type)->cells())
151
+ {
152
+ if (subcell->type != ID($specify2))
153
+ continue;
154
+
155
+ for (auto bit : subcell->getPort(ID::SRC))
156
+ {
157
+ if (!bit.wire || !cell->hasPort(bit.wire->name))
158
+ continue;
159
+ inputSignals.append(sigmap(cell->getPort(bit.wire->name)));
160
+ }
161
+
162
+ for (auto bit : subcell->getPort(ID::DST))
163
+ {
164
+ if (!bit.wire || !cell->hasPort(bit.wire->name))
165
+ continue;
166
+ outputSignals.append(sigmap(cell->getPort(bit.wire->name)));
167
+ }
168
+ }
169
+ } else {
170
+ for (auto &conn : cell->connections())
171
+ {
172
+ bool isInput = true, isOutput = true;
173
+
174
+ if (ct.cell_known(cell->type)) {
175
+ isInput = ct.cell_input(cell->type, conn.first);
176
+ isOutput = ct.cell_output(cell->type, conn.first);
177
+ }
178
+
179
+ RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
180
+ sig.sort_and_unify();
181
+
182
+ if (isInput)
183
+ inputSignals.append(sig);
184
+ if (isOutput)
185
+ outputSignals.append(sig);
186
+ }
187
+ }
188
+
189
+ inputSignals.sort_and_unify();
190
+ outputSignals.sort_and_unify();
191
+
192
+ cellToPrevSig[cell] = inputSignals;
193
+ cellToNextSig[cell] = outputSignals;
194
+ sigToNextCells.insert(inputSignals, cell);
195
+ }
196
+
197
+ for (auto cell : workQueue)
198
+ {
199
+ sigToNextCells.find(cellToNextSig[cell], cellToNextCell[cell]);
200
+
201
+ if (!nofeedbackMode && cellToNextCell[cell].count(cell)) {
202
+ std::string message = "Found an SCC:";
203
+ pool<RTLIL::Cell*> scc;
204
+ message += stringf(" %s", cell);
205
+ cell2scc[cell] = sccList.size();
206
+ scc.insert(cell);
207
+ sccList.push_back(scc);
208
+ log("%s\n", message);
209
+ }
210
+ }
211
+
212
+ labelCounter = 0;
213
+ cellLabels.clear();
214
+
215
+ while (!workQueue.empty())
216
+ {
217
+ RTLIL::Cell *cell = *workQueue.begin();
218
+ log_assert(cellStack.size() == 0);
219
+ cellDepth.clear();
220
+
221
+ run(cell, 0, maxDepth);
222
+ }
223
+
224
+ log("Found %d SCCs in module %s.\n", int(sccList.size()), module);
225
+ }
226
+
227
+ void select(RTLIL::Selection &sel)
228
+ {
229
+ for (int i = 0; i < int(sccList.size()); i++)
230
+ {
231
+ pool<RTLIL::Cell*> &cells = sccList[i];
232
+ RTLIL::SigSpec prevsig, nextsig, sig;
233
+
234
+ for (auto cell : cells) {
235
+ sel.selected_members[module->name].insert(cell->name);
236
+ prevsig.append(cellToPrevSig[cell]);
237
+ nextsig.append(cellToNextSig[cell]);
238
+ }
239
+
240
+ prevsig.sort_and_unify();
241
+ nextsig.sort_and_unify();
242
+ sig = prevsig.extract(nextsig);
243
+
244
+ for (auto &chunk : sig.chunks())
245
+ if (chunk.wire != NULL)
246
+ sel.selected_members[module->name].insert(chunk.wire->name);
247
+ }
248
+ }
249
+ };
250
+
251
+ struct SccPass : public Pass {
252
+ SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
253
+ bool formatted_help() override {
254
+ auto *help = PrettyHelp::get_current();
255
+ help->set_group("passes/status");
256
+ return false;
257
+ }
258
+ void help() override
259
+ {
260
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
261
+ log("\n");
262
+ log(" scc [options] [selection]\n");
263
+ log("\n");
264
+ log("This command identifies strongly connected components (aka logic loops) in the\n");
265
+ log("design.\n");
266
+ log("\n");
267
+ log(" -expect <num>\n");
268
+ log(" expect to find exactly <num> SCCs. A different number of SCCs will\n");
269
+ log(" produce an error.\n");
270
+ log("\n");
271
+ log(" -max_depth <num>\n");
272
+ log(" limit to loops not longer than the specified number of cells. This\n");
273
+ log(" can e.g. be useful in identifying small local loops in a module that\n");
274
+ log(" implements one large SCC.\n");
275
+ log("\n");
276
+ log(" -nofeedback\n");
277
+ log(" do not count cells that have their output fed back into one of their\n");
278
+ log(" inputs as single-cell scc.\n");
279
+ log("\n");
280
+ log(" -all_cell_types\n");
281
+ log(" Usually this command only considers internal non-memory cells. With\n");
282
+ log(" this option set, all cells are considered. For unknown cells all ports\n");
283
+ log(" are assumed to be bidirectional 'inout' ports.\n");
284
+ log("\n");
285
+ log(" -set_attr <name> <value>\n");
286
+ log(" set the specified attribute on all cells that are part of a logic\n");
287
+ log(" loop. the special token {} in the value is replaced with a unique\n");
288
+ log(" identifier for the logic loop.\n");
289
+ log("\n");
290
+ log(" -select\n");
291
+ log(" replace the current selection with a selection of all cells and wires\n");
292
+ log(" that are part of a found logic loop\n");
293
+ log("\n");
294
+ log(" -specify\n");
295
+ log(" examine specify rules to detect logic loops in whitebox/blackbox cells\n");
296
+ log("\n");
297
+ }
298
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
299
+ {
300
+ dict<std::string, std::string> setAttr;
301
+ bool allCellTypes = false;
302
+ bool selectMode = false;
303
+ bool nofeedbackMode = false;
304
+ bool specifyMode = false;
305
+ int maxDepth = -1;
306
+ int expect = -1;
307
+
308
+ log_header(design, "Executing SCC pass (detecting logic loops).\n");
309
+
310
+ size_t argidx;
311
+ for (argidx = 1; argidx < args.size(); argidx++) {
312
+ if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
313
+ maxDepth = atoi(args[++argidx].c_str());
314
+ continue;
315
+ }
316
+ if (args[argidx] == "-expect" && argidx+1 < args.size()) {
317
+ expect = atoi(args[++argidx].c_str());
318
+ continue;
319
+ }
320
+ if (args[argidx] == "-nofeedback") {
321
+ nofeedbackMode = true;
322
+ continue;
323
+ }
324
+ if (args[argidx] == "-all_cell_types") {
325
+ allCellTypes = true;
326
+ continue;
327
+ }
328
+ if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
329
+ setAttr[args[argidx+1]] = args[argidx+2];
330
+ argidx += 2;
331
+ continue;
332
+ }
333
+ if (args[argidx] == "-select") {
334
+ selectMode = true;
335
+ continue;
336
+ }
337
+ if (args[argidx] == "-specify") {
338
+ specifyMode = true;
339
+ continue;
340
+ }
341
+ break;
342
+ }
343
+ int origSelectPos = design->selection_stack.size() - 1;
344
+ extra_args(args, argidx, design);
345
+
346
+ auto newSelection = RTLIL::Selection::EmptySelection(design);
347
+ int scc_counter = 0;
348
+
349
+ for (auto mod : design->selected_modules())
350
+ {
351
+ SccWorker worker(design, mod, nofeedbackMode, allCellTypes, specifyMode, maxDepth);
352
+
353
+ if (!setAttr.empty())
354
+ {
355
+ for (const auto &cells : worker.sccList)
356
+ {
357
+ for (auto attr : setAttr)
358
+ {
359
+ IdString attr_name = design->twines().add(RTLIL::escape_id(attr.first));
360
+ string attr_valstr = attr.second;
361
+ string index = stringf("%d", scc_counter);
362
+
363
+ for (size_t pos = 0; (pos = attr_valstr.find("{}", pos)) != string::npos; pos += index.size())
364
+ attr_valstr.replace(pos, 2, index);
365
+
366
+ Const attr_value(attr_valstr);
367
+
368
+ for (auto cell : cells)
369
+ cell->attributes[attr_name] = attr_value;
370
+ }
371
+
372
+ scc_counter++;
373
+ }
374
+ }
375
+ else
376
+ {
377
+ scc_counter += GetSize(worker.sccList);
378
+ }
379
+
380
+ if (selectMode)
381
+ worker.select(newSelection);
382
+ }
383
+
384
+ if (expect >= 0) {
385
+ if (scc_counter == expect)
386
+ log("Found and expected %d SCCs.\n", scc_counter);
387
+ else
388
+ log_error("Found %d SCCs but expected %d.\n", scc_counter, expect);
389
+ } else
390
+ log("Found %d SCCs.\n", scc_counter);
391
+
392
+ if (selectMode) {
393
+ log_assert(origSelectPos >= 0);
394
+ design->selection_stack[origSelectPos] = newSelection;
395
+ design->selection_stack[origSelectPos].optimize(design);
396
+ }
397
+ }
398
+ } SccPass;
399
+
400
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/scratchpad.cc ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ * 2019 N. Engelhardt <nak@yosyshq.com>
6
+ *
7
+ * Permission to use, copy, modify, and/or distribute this software for any
8
+ * purpose with or without fee is hereby granted, provided that the above
9
+ * copyright notice and this permission notice appear in all copies.
10
+ *
11
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18
+ *
19
+ */
20
+
21
+ #include "kernel/yosys.h"
22
+ #include "kernel/log_help.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct ScratchpadPass : public Pass {
28
+ ScratchpadPass() : Pass("scratchpad", "get/set values in the scratchpad") { }
29
+ bool formatted_help() override {
30
+ auto *help = PrettyHelp::get_current();
31
+ help->set_group("passes/status");
32
+ return false;
33
+ }
34
+ void help() override
35
+ {
36
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
37
+ log("\n");
38
+ log(" scratchpad [options]\n");
39
+ log("\n");
40
+ log("This pass allows reading and modifying values from the scratchpad of the current\n");
41
+ log("design. Options:\n");
42
+ log("\n");
43
+ log(" -get <identifier>\n");
44
+ log(" print the value saved in the scratchpad under the given identifier.\n");
45
+ log("\n");
46
+ log(" -set <identifier> <value>\n");
47
+ log(" save the given value in the scratchpad under the given identifier.\n");
48
+ log("\n");
49
+ log(" -unset <identifier>\n");
50
+ log(" remove the entry for the given identifier from the scratchpad.\n");
51
+ log("\n");
52
+ log(" -copy <identifier_from> <identifier_to>\n");
53
+ log(" copy the value of the first identifier to the second identifier.\n");
54
+ log("\n");
55
+ log(" -assert <identifier> <value>\n");
56
+ log(" assert that the entry for the given identifier is set to the given\n");
57
+ log(" value.\n");
58
+ log("\n");
59
+ log(" -assert-set <identifier>\n");
60
+ log(" assert that the entry for the given identifier exists.\n");
61
+ log("\n");
62
+ log(" -assert-unset <identifier>\n");
63
+ log(" assert that the entry for the given identifier does not exist.\n");
64
+ log("\n");
65
+ log("The identifier may not contain whitespace. By convention, it is usually prefixed\n");
66
+ log("by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\n");
67
+ log("contains whitespace, it must be enclosed in double quotes.\n");
68
+ log("\n");
69
+ }
70
+
71
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
72
+ {
73
+ size_t argidx;
74
+ for (argidx = 1; argidx < args.size(); argidx++)
75
+ {
76
+ if (args[argidx] == "-get" && argidx+1 < args.size()) {
77
+ string identifier = args[++argidx];
78
+ if (design->scratchpad.count(identifier)) {
79
+ log("%s\n", design->scratchpad_get_string(identifier));
80
+ } else if (RTLIL::constpad.count(identifier)) {
81
+ log("%s\n", RTLIL::constpad.at(identifier));
82
+ } else {
83
+ log("\"%s\" not set\n", identifier);
84
+ }
85
+ continue;
86
+ }
87
+ if (args[argidx] == "-set" && argidx+2 < args.size()) {
88
+ string identifier = args[++argidx];
89
+ if (RTLIL::constpad.count(identifier))
90
+ log_error("scratchpad entry \"%s\" is a global constant\n", identifier);
91
+ string value = args[++argidx];
92
+ if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2);
93
+ design->scratchpad_set_string(identifier, value);
94
+ continue;
95
+ }
96
+ if (args[argidx] == "-unset" && argidx+1 < args.size()) {
97
+ string identifier = args[++argidx];
98
+ design->scratchpad_unset(identifier);
99
+ continue;
100
+ }
101
+ if (args[argidx] == "-copy" && argidx+2 < args.size()) {
102
+ string identifier_from = args[++argidx];
103
+ string identifier_to = args[++argidx];
104
+ string value;
105
+ if (design->scratchpad.count(identifier_from))
106
+ value = design->scratchpad_get_string(identifier_from);
107
+ else if (RTLIL::constpad.count(identifier_from))
108
+ value = RTLIL::constpad.at(identifier_from);
109
+ else
110
+ log_error("\"%s\" not set\n", identifier_from);
111
+ if (RTLIL::constpad.count(identifier_to))
112
+ log_error("scratchpad entry \"%s\" is a global constant\n", identifier_to);
113
+ design->scratchpad_set_string(identifier_to, value);
114
+ continue;
115
+ }
116
+ if (args[argidx] == "-assert" && argidx+2 < args.size()) {
117
+ string identifier = args[++argidx];
118
+ string expected = args[++argidx];
119
+ if (expected.front() == '\"' && expected.back() == '\"') expected = expected.substr(1, expected.size() - 2);
120
+ if (design->scratchpad.count(identifier) == 0)
121
+ log_error("scratchpad entry '%s' is not defined\n", identifier);
122
+ string value = design->scratchpad_get_string(identifier);
123
+ if (value != expected) {
124
+ log_error("scratchpad entry '%s' is set to '%s' instead of the asserted '%s'\n",
125
+ identifier, value, expected);
126
+ }
127
+ continue;
128
+ }
129
+ if (args[argidx] == "-assert-set" && argidx+1 < args.size()) {
130
+ string identifier = args[++argidx];
131
+ if (design->scratchpad.count(identifier) == 0)
132
+ log_error("scratchpad entry '%s' is not defined\n", identifier);
133
+ continue;
134
+ }
135
+ if (args[argidx] == "-assert-unset" && argidx+1 < args.size()) {
136
+ string identifier = args[++argidx];
137
+ if (design->scratchpad.count(identifier) > 0)
138
+ log_error("scratchpad entry '%s' is defined\n", identifier);
139
+ continue;
140
+ }
141
+ break;
142
+ }
143
+ extra_args(args, argidx, design, false);
144
+ }
145
+ } ScratchpadPass;
146
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/sdc/CMakeLists.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ yosys_pass(sdc
2
+ sdc.cc
3
+ LIBRARIES
4
+ $<${YOSYS_ENABLE_TCL}:PkgConfig::tcl>
5
+ DATA_DIR
6
+ sdc
7
+ DATA_FILES
8
+ graph-stubs.sdc
9
+ )
chips/yosys/passes/cmds/sdc/graph-stubs.sdc ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ proc unknown {args} {
2
+ # Check if it's a getter
3
+ if {[llength $args] > 0} {
4
+ set first_arg [lindex $args 0]
5
+ if {[string match "get_*" $first_arg]} {
6
+ # It's a getter, has it been redirected from specialized C++ code?
7
+ if {[llength $args] > 1} {
8
+ set second_arg [lindex $args 1]
9
+ if {$second_arg ne "-getter-validated"} {
10
+ error "Unknown getter: $first_arg"
11
+ }
12
+ } else {
13
+ error "Unknown getter: $first_arg"
14
+ }
15
+ }
16
+ }
17
+ # TODO this safety feature could be optional via a global
18
+
19
+ global sdc_call_index
20
+ global sdc_calls
21
+ if {![info exists sdc_call_index]} {
22
+ set sdc_call_index 0
23
+ }
24
+ if {![info exists sdc_calls]} {
25
+ set sdc_calls {}
26
+ }
27
+ set ret "YOSYS_SDC_MAGIC_NODE_$sdc_call_index"
28
+ incr sdc_call_index
29
+ lappend sdc_calls $args
30
+ # puts "unknown $args, returning YOSYS_SDC_MAGIC_NODE_$sdc_call_index"
31
+ return $ret
32
+ }
33
+ proc list {args} {
34
+ return [unknown "list" {*}$args]
35
+ }
36
+ proc get_clocks {args} {
37
+ # get_clocks isn't a design object getter
38
+ # because clocks aren't design objects, just aliases
39
+ # so the referred to clock pin already are being tracked
40
+ # as arguments of uninterpreted create_clock command or similar
41
+ return [unknown "get_clocks" "-getter-validated" {*}$args]
42
+ }
chips/yosys/passes/cmds/sdc/sdc.cc ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "kernel/yosys_config.h"
2
+ #ifdef YOSYS_ENABLE_TCL
3
+
4
+ #include "kernel/register.h"
5
+ #include "kernel/rtlil.h"
6
+ #include "kernel/log.h"
7
+ #include <tcl.h>
8
+ #include <list>
9
+ #include <optional>
10
+ #include <iostream>
11
+
12
+ #if TCL_MAJOR_VERSION < 9
13
+ typedef int YS_Tcl_Size;
14
+ #else
15
+ typedef Tcl_Size YS_Tcl_Size;
16
+ #endif
17
+
18
+ USING_YOSYS_NAMESPACE
19
+ PRIVATE_NAMESPACE_BEGIN
20
+
21
+ struct TclCall {
22
+ Tcl_Interp *interp;
23
+ int objc;
24
+ Tcl_Obj* const* objv;
25
+ };
26
+
27
+ static int redirect_unknown(TclCall call);
28
+ static size_t get_node_count(Tcl_Interp* interp);
29
+
30
+ struct BitSelection {
31
+ bool all = false;
32
+ std::vector<bool> bits = {};
33
+ void set_all() {
34
+ bits.clear();
35
+ all = true;
36
+ }
37
+ void clear() {
38
+ bits.clear();
39
+ all = false;
40
+ }
41
+ void set(size_t idx) {
42
+ if (all)
43
+ return;
44
+ if (idx >= bits.size())
45
+ bits.resize(idx + 1);
46
+ bits[idx] = true;
47
+ }
48
+ void merge(const BitSelection& other) {
49
+ if (all)
50
+ return;
51
+ if (other.all) {
52
+ set_all();
53
+ return;
54
+ }
55
+ if (other.bits.size() > bits.size())
56
+ bits.resize(other.bits.size());
57
+ for (size_t other_idx = 0; other_idx < other.bits.size(); other_idx++) {
58
+ bool other_bit = other.bits[other_idx];
59
+ if (other_bit)
60
+ set(other_idx);
61
+ }
62
+ }
63
+ void dump() {
64
+ if (!all) {
65
+ for (size_t i = 0; i < bits.size(); i++)
66
+ if (bits[i])
67
+ log("\t\t [%zu]\n", i);
68
+ } else {
69
+ log("\t\t FULL\n");
70
+ }
71
+ }
72
+ bool is_set(size_t idx) const {
73
+ if (all)
74
+ return true;
75
+ if (idx >= bits.size())
76
+ return false;
77
+ return bits[idx];
78
+ }
79
+ // TODO actually use this
80
+ void compress(size_t size) {
81
+ if (bits.size() < size)
82
+ return;
83
+ for (size_t i = 0; i < size; i++)
84
+ if (!bits[i])
85
+ return;
86
+ bits.clear();
87
+ bits.shrink_to_fit();
88
+ all = true;
89
+ }
90
+ };
91
+
92
+ struct SdcObjects {
93
+ enum CollectMode {
94
+ // getter-side object tracking with minimal features
95
+ SimpleGetter,
96
+ // getter-side object tracking with everything
97
+ FullGetter,
98
+ // constraint-side tracking
99
+ FullConstraint,
100
+ } collect_mode;
101
+ using CellPin = std::pair<Cell*, IdString>;
102
+ Design* design;
103
+ std::vector<std::pair<std::string, Wire*>> design_ports;
104
+ std::vector<std::pair<std::string, Cell*>> design_cells;
105
+ std::vector<std::pair<std::string, CellPin>> design_pins;
106
+ std::vector<std::pair<std::string, Wire*>> design_nets;
107
+
108
+ using PortPattern = std::tuple<std::string, Wire*, BitSelection>;
109
+ using PinPattern = std::tuple<std::string, SdcObjects::CellPin, BitSelection>;
110
+ std::vector<std::vector<PortPattern>> resolved_port_pattern_sets;
111
+ std::vector<std::vector<PinPattern>> resolved_pin_pattern_sets;
112
+ // TODO
113
+
114
+ dict<std::pair<std::string, Wire*>, BitSelection> constrained_ports;
115
+ pool<std::pair<std::string, Cell*>> constrained_cells;
116
+ dict<std::pair<std::string, CellPin>, BitSelection> constrained_pins;
117
+ dict<std::pair<std::string, Wire*>, BitSelection> constrained_nets;
118
+
119
+ void sniff_module(std::list<std::string>& hierarchy, Module* mod) {
120
+ std::string prefix;
121
+ for (auto mod_name : hierarchy) {
122
+ if (prefix.length())
123
+ prefix += "/"; // TODO seperator?
124
+ prefix += mod_name;
125
+ }
126
+
127
+ for (auto* wire : mod->wires()) {
128
+ std::string name = wire->name.str();
129
+ log_assert(name.length());
130
+ // TODO: really skip internal wires?
131
+ if (name[0] == '$')
132
+ continue;
133
+ name = name.substr(1);
134
+ std::string path = prefix;
135
+ if (path.length())
136
+ path += "/";
137
+ path += name;
138
+ design_nets.push_back(std::make_pair(path, wire));
139
+ }
140
+
141
+ for (auto* cell : mod->cells()) {
142
+ std::string name = cell->name.str();
143
+ // TODO: really skip internal cells?
144
+ if (name[0] == '$')
145
+ continue;
146
+ name = name.substr(1);
147
+ std::string path = prefix;
148
+ if (path.length())
149
+ path += "/";
150
+ path += name;
151
+ design_cells.push_back(std::make_pair(path, cell));
152
+ for (auto& pin : cell->connections()) {
153
+ IdString pin_name = pin.first;
154
+ std::string pin_name_sdc = path + "/" + design->twines().str(pin.first);
155
+ design_pins.push_back(std::make_pair(pin_name_sdc, std::make_pair(cell, pin_name)));
156
+ }
157
+ if (auto sub_mod = mod->design->module(cell->type)) {
158
+ hierarchy.push_back(name);
159
+ sniff_module(hierarchy, sub_mod);
160
+ hierarchy.pop_back();
161
+ }
162
+ }
163
+ }
164
+ SdcObjects(Design* design) : design(design) {
165
+ Module* top = design->top_module();
166
+ if (!top)
167
+ log_error("Top module couldn't be determined. Check 'top' attribute usage\n");
168
+ for (auto port : top->ports) {
169
+ RTLIL::Wire *wire = top->wire(port);
170
+ if (!wire) {
171
+ // This should not be possible. See https://github.com/YosysHQ/yosys/pull/5594#issue-3791198573
172
+ log_error("Port %s doesn't exist\n", PooledName(design, port).unescape());
173
+ }
174
+ design_ports.push_back(std::make_pair(design->twines().str(port), wire));
175
+ }
176
+ std::list<std::string> hierarchy{};
177
+ sniff_module(hierarchy, top);
178
+ }
179
+ ~SdcObjects() = default;
180
+
181
+ template <typename T, typename U>
182
+ void build_normal_result(Tcl_Interp* interp, std::vector<std::tuple<std::string, T, BitSelection>>&& resolved, U& tgt, std::function<size_t(T&)> width, Tcl_Obj*& result) {
183
+ if (!result)
184
+ result = Tcl_NewListObj(resolved.size(), nullptr);
185
+ for (auto [name, obj, matching_bits] : resolved) {
186
+ for (size_t i = 0; i < width(obj); i++)
187
+ if (matching_bits.is_set(i)) {
188
+ Tcl_ListObjAppendElement(interp, result, Tcl_NewStringObj(name.c_str(), name.size()));
189
+ break;
190
+ }
191
+
192
+ }
193
+ size_t node_count = get_node_count(interp);
194
+ tgt.emplace_back(std::move(resolved));
195
+ log("%zu %zu\n", node_count, tgt.size());
196
+ log_assert(node_count == tgt.size());
197
+ }
198
+ template <typename T>
199
+ void merge_as_constrained(std::vector<std::tuple<std::string, T, BitSelection>>&& resolved) {
200
+ for (auto [name, obj, matching_bits] : resolved) {
201
+ merge_or_init(std::make_pair(name, obj), constrained_pins, matching_bits);
202
+ }
203
+ }
204
+ void dump() {
205
+ std::sort(design_ports.begin(), design_ports.end());
206
+ std::sort(design_cells.begin(), design_cells.end());
207
+ std::sort(design_pins.begin(), design_pins.end());
208
+ std::sort(design_nets.begin(), design_nets.end());
209
+ constrained_ports.sort();
210
+ constrained_cells.sort();
211
+ constrained_pins.sort();
212
+ constrained_nets.sort();
213
+ // log("Design ports:\n");
214
+ // for (auto name : design_ports) {
215
+ // log("\t%s\n", name);
216
+ // }
217
+ // log("Design cells:\n");
218
+ // for (auto [name, cell] : design_cells) {
219
+ // (void)cell;
220
+ // log("\t%s\n", name);
221
+ // }
222
+ // log("Design pins:\n");
223
+ // for (auto [name, pin] : design_pins) {
224
+ // (void)pin;
225
+ // log("\t%s\n", name);
226
+ // }
227
+ // log("Design nets:\n");
228
+ // for (auto [name, net] : design_nets) {
229
+ // (void)net;
230
+ // log("\t%s\n", name);
231
+ // }
232
+ // log("\n");
233
+ log("Constrained ports:\n");
234
+ for (auto [ref, bits] : constrained_ports) {
235
+ auto [name, port] = ref;
236
+ (void)port;
237
+ log("\t%s\n", name);
238
+ bits.dump();
239
+ }
240
+ log("Constrained cells:\n");
241
+ for (auto& [name, cell] : constrained_cells) {
242
+ (void)cell;
243
+ log("\t%s\n", name);
244
+ }
245
+ log("Constrained pins:\n");
246
+ for (auto& [ref, bits] : constrained_pins) {
247
+ auto [name, pin] = ref;
248
+ (void)pin;
249
+ log("\t%s\n", name);
250
+ bits.dump();
251
+ }
252
+ log("Constrained nets:\n");
253
+ for (auto& [ref, bits] : constrained_nets) {
254
+ auto [name, net] = ref;
255
+ (void)net;
256
+ log("\t%s\n", name);
257
+ bits.dump();
258
+ }
259
+ log("\n");
260
+ }
261
+
262
+ class KeepHierarchyWorker {
263
+ std::unordered_set<Module*> tracked_modules = {};
264
+ Design* design = nullptr;
265
+ bool mark(Module* mod) {
266
+ for (auto* cell : mod->cells()) {
267
+ if (auto* submod = design->module(cell->type))
268
+ if (mark(submod)) {
269
+ mod->set_bool_attribute(ID::keep_hierarchy);
270
+ return true;
271
+ }
272
+ }
273
+
274
+ if (tracked_modules.count(mod)) {
275
+ mod->set_bool_attribute(ID::keep_hierarchy);
276
+ return true;
277
+ }
278
+
279
+ return false;
280
+ }
281
+ public:
282
+ KeepHierarchyWorker(SdcObjects* objects, Design* d) : design(d) {
283
+ for (auto [ref, _] : objects->constrained_ports) {
284
+ tracked_modules.insert(ref.second->module);
285
+ }
286
+ for (auto& [_, cell] : objects->constrained_cells) {
287
+ tracked_modules.insert(cell->module);
288
+ }
289
+ for (auto& [ref, _] : objects->constrained_pins) {
290
+ tracked_modules.insert(ref.second.first->module);
291
+ }
292
+ for (auto& [ref, _] : objects->constrained_nets) {
293
+ tracked_modules.insert(ref.second->module);
294
+ }
295
+ log_debug("keep_hierarchy tracked modules:\n");
296
+ for (auto* mod : tracked_modules)
297
+ log_debug("\t%s\n", mod->name);
298
+ }
299
+ bool mark() {
300
+ return mark(design->top_module());
301
+ }
302
+ };
303
+ void keep_hierarchy() {
304
+ (void)KeepHierarchyWorker(this, design).mark();
305
+ }
306
+ };
307
+
308
+ // TODO vectors
309
+ // TODO cell arrays?
310
+ struct MatchConfig {
311
+ enum MatchMode {
312
+ WILDCARD,
313
+ REGEX,
314
+ } match;
315
+ bool match_case;
316
+ enum HierMode {
317
+ FLAT,
318
+ TREE,
319
+ } hier;
320
+ MatchConfig(bool regexp_flag, bool nocase_flag, bool hierarchical_flag) :
321
+ match(regexp_flag ? REGEX : WILDCARD),
322
+ match_case(!nocase_flag),
323
+ hier(hierarchical_flag ? FLAT : TREE) { }
324
+ };
325
+
326
+ static std::pair<bool, BitSelection> matches(std::string name, const std::string& pat, const MatchConfig& config) {
327
+ (void)config;
328
+ bool got_bit_index = false;;
329
+ int bit_idx;
330
+ std::string pat_base = pat;
331
+ size_t pos = pat.rfind('[');
332
+ if (pos != std::string::npos) {
333
+ got_bit_index = true;
334
+ pat_base = pat.substr(0, pos);
335
+ std::string bit_selector = pat.substr(pos + 1, pat.rfind(']') - pos - 1);
336
+ for (auto c : bit_selector)
337
+ if (!std::isdigit(c))
338
+ log_error("Unsupported bit selector %s in SDC pattern %s\n",
339
+ bit_selector, pat);
340
+ bit_idx = std::stoi(bit_selector);
341
+
342
+ }
343
+ BitSelection bits = {};
344
+ if (name == pat_base) {
345
+ if (got_bit_index) {
346
+ bits.set(bit_idx);
347
+ return std::make_pair(true, bits);
348
+ } else {
349
+ bits.set_all();
350
+ return std::make_pair(true, bits);
351
+
352
+ }
353
+ } else {
354
+ return std::make_pair(false, bits);
355
+ }
356
+ }
357
+
358
+ static int getter_graph_node(TclCall call) {
359
+ // Insert -getter-validated as first argument for passing to unknown
360
+ // to distinguish resolved and unknown getters.
361
+ // For example, if call is ["get_foo", "-bar"]
362
+ // then newCall is ["get_foo", "-getter-validated", "-bar"]
363
+ Tcl_Obj* validity_tag = Tcl_NewStringObj("-getter-validated", -1);
364
+ Tcl_IncrRefCount(validity_tag);
365
+ std::vector<Tcl_Obj*> newObjv(call.objc + 1);
366
+ log_assert(call.objc > 0);
367
+ newObjv[0] = call.objv[0];
368
+ newObjv[1] = validity_tag;
369
+ for (int i = 1; i < call.objc; ++i) {
370
+ newObjv[i + 1] = call.objv[i];
371
+ }
372
+ // Send the vector to the Tcl land
373
+ Tcl_Obj** allocatedObjv = (Tcl_Obj**)Tcl_Alloc((call.objc + 1) * sizeof(Tcl_Obj*));
374
+ for (int i = 0; i < call.objc + 1; ++i) {
375
+ allocatedObjv[i] = newObjv[i];
376
+ }
377
+ TclCall newCall {
378
+ .interp = call.interp,
379
+ .objc = call.objc + 1,
380
+ .objv = allocatedObjv
381
+ };
382
+ // Finally, redirect to unknown handler
383
+ return redirect_unknown(newCall);
384
+ }
385
+
386
+ static int redirect_unknown(TclCall call) {
387
+ // TODO redirect to different command
388
+ Tcl_Obj *newCmd = Tcl_NewStringObj("unknown", -1);
389
+ auto newObjc = call.objc + 1;
390
+ Tcl_Obj** newObjv = (Tcl_Obj**)Tcl_Alloc(newObjc * sizeof(Tcl_Obj*));
391
+ newObjv[0] = newCmd;
392
+ for (int i = 1; i < newObjc; i++) {
393
+ newObjv[i] = call.objv[i - 1];
394
+ }
395
+ int result = Tcl_EvalObjv(call.interp, newObjc, newObjv, 0);
396
+ Tcl_DecrRefCount(newCmd);
397
+ Tcl_Free((char*) newObjv);
398
+ return result;
399
+ }
400
+
401
+
402
+ struct SdcGraphNode {
403
+ using Child = std::variant<SdcGraphNode*, std::string>;
404
+ std::vector<Child> children;
405
+ SdcGraphNode() = default;
406
+ void addChild(SdcGraphNode* child) {
407
+ children.push_back(child);
408
+ }
409
+ void addChild(std::string tcl_string) {
410
+ children.push_back(tcl_string);
411
+ }
412
+ void dump(std::ostream& os) const {
413
+ bool first = true;
414
+ for (auto child : children) {
415
+ if (first) {
416
+ first = false;
417
+ } else {
418
+ os << " ";
419
+ }
420
+ if (auto* s = std::get_if<std::string>(&child))
421
+ os << *s;
422
+ else if (SdcGraphNode*& c = *std::get_if<SdcGraphNode*>(&child)) {
423
+ os << "[";
424
+ c->dump(os);
425
+ os << "]";
426
+ } else {
427
+ log_assert(false);
428
+ }
429
+ }
430
+ }
431
+ };
432
+
433
+ static size_t get_node_count(Tcl_Interp* interp) {
434
+ const char* idx_raw = Tcl_GetVar(interp, "sdc_call_index", TCL_GLOBAL_ONLY);
435
+ log_assert(idx_raw);
436
+ std::string idx(idx_raw);
437
+ for (auto c : idx)
438
+ if (!std::isdigit(c))
439
+ log_error("sdc_call_index non-numeric value %s\n", idx);
440
+ return std::stoi(idx);
441
+ }
442
+
443
+ std::vector<std::vector<std::string>> gather_nested_calls(Tcl_Interp* interp) {
444
+
445
+ Tcl_Obj* listObj = Tcl_GetVar2Ex(interp, "sdc_calls", nullptr, TCL_GLOBAL_ONLY);
446
+ YS_Tcl_Size listLength;
447
+
448
+ std::vector<std::vector<std::string>> sdc_calls;
449
+ if (Tcl_ListObjLength(interp, listObj, &listLength) == TCL_OK) {
450
+ for (int i = 0; i < listLength; i++) {
451
+ Tcl_Obj* subListObj;
452
+ std::vector<std::string> subList;
453
+ if (Tcl_ListObjIndex(interp, listObj, i, &subListObj) != TCL_OK) {
454
+ log_error("broken list of lists\n");
455
+ }
456
+ YS_Tcl_Size subListLength;
457
+ if (Tcl_ListObjLength(interp, subListObj, &subListLength) == TCL_OK) {
458
+ // Valid list - extract elements
459
+ for (int j = 0; j < subListLength; j++) {
460
+ Tcl_Obj* elementObj;
461
+ if (Tcl_ListObjIndex(interp, subListObj, j, &elementObj) == TCL_OK) {
462
+ const char* elementStr = Tcl_GetString(elementObj);
463
+ subList.push_back(std::string(elementStr));
464
+ }
465
+ }
466
+ } else {
467
+ // Single element, not a list
468
+ const char* elementStr = Tcl_GetString(subListObj);
469
+ subList.push_back(std::string(elementStr));
470
+ }
471
+ sdc_calls.push_back(subList);
472
+ }
473
+ }
474
+ log_assert(sdc_calls.size() == get_node_count(interp));
475
+ return sdc_calls;
476
+ }
477
+
478
+ std::vector<SdcGraphNode> build_graph(const std::vector<std::vector<std::string>>& sdc_calls) {
479
+ size_t node_count = sdc_calls.size();
480
+ std::vector<SdcGraphNode> graph(node_count);
481
+ for (size_t i = 0; i < node_count; i++) {
482
+ auto& new_node = graph[i];
483
+ for (size_t j = 0; j < sdc_calls[i].size(); j++) {
484
+ auto arg = sdc_calls[i][j];
485
+ const std::string prefix = "YOSYS_SDC_MAGIC_NODE_";
486
+ auto pos = arg.find(prefix);
487
+ if (pos != std::string::npos) {
488
+ std::string rest = arg.substr(pos + prefix.length());
489
+ for (auto c : rest)
490
+ if (!std::isdigit(c))
491
+ log_error("weird thing %s in %s\n", rest, arg);
492
+ size_t arg_node_idx = std::stoi(rest);
493
+ log_assert(arg_node_idx < graph.size());
494
+ new_node.addChild(&graph[arg_node_idx]);
495
+ } else {
496
+ new_node.addChild(arg);
497
+ }
498
+
499
+ }
500
+ }
501
+ return graph;
502
+ }
503
+
504
+ std::vector<bool> node_ownership(const std::vector<SdcGraphNode>& graph) {
505
+ std::vector<bool> has_parent(graph.size());
506
+ for (auto node : graph) {
507
+ for (auto child : node.children) {
508
+ if (SdcGraphNode** pp = std::get_if<SdcGraphNode*>(&child)) {
509
+ size_t idx = std::distance(&graph.front(), (const SdcGraphNode*)*pp);
510
+ log_assert(idx < has_parent.size());
511
+ has_parent[idx] = true;
512
+ }
513
+ }
514
+ }
515
+ return has_parent;
516
+ }
517
+
518
+ void dump_sdc_graph(const std::vector<SdcGraphNode>& graph, const std::vector<bool>& has_parent) {
519
+ for (size_t i = 0; i < graph.size(); i++) {
520
+ if (!has_parent[i]) {
521
+ graph[i].dump(std::cout);
522
+ std::cout << "\n";
523
+ }
524
+ }
525
+ }
526
+
527
+ void inspect_globals(Tcl_Interp* interp, bool dump_mode) {
528
+ std::vector<std::vector<std::string>> sdc_calls = gather_nested_calls(interp);
529
+ std::vector<SdcGraphNode> graph = build_graph(sdc_calls);
530
+ if (dump_mode)
531
+ dump_sdc_graph(graph, node_ownership(graph));
532
+ }
533
+
534
+ // patterns -> (pattern-object-bit)s
535
+ template <typename T, typename U>
536
+ std::vector<std::tuple<std::string, T, BitSelection>>
537
+ find_matching(U objects, const MatchConfig& config, const std::vector<std::string> &patterns, const char* obj_type)
538
+ {
539
+ std::vector<std::tuple<std::string, T, BitSelection>> resolved;
540
+ for (auto pat : patterns) {
541
+ bool found = false;
542
+ for (auto [name, obj] : objects) {
543
+ auto [does_match, matching_bits] = matches(name, pat, config);
544
+ if (does_match) {
545
+ found = true;
546
+ resolved.push_back(std::make_tuple(name, obj, matching_bits));
547
+ // TODO add a continue statement, conditional on config
548
+ }
549
+ }
550
+ if (!found)
551
+ log_warning("No matches in design for %s %s\n", obj_type, pat);
552
+ }
553
+ return resolved;
554
+ }
555
+
556
+ struct TclOpts {
557
+ const char* name;
558
+ std::initializer_list<const char*> legals;
559
+ TclOpts(const char* name, std::initializer_list<const char*> legals) : name(name), legals(legals) {}
560
+ bool parse_opt(Tcl_Obj* obj, const char* opt_name) {
561
+ char* arg = Tcl_GetString(obj);
562
+ std::string expected = std::string("-") + opt_name;
563
+ if (expected == arg) {
564
+ if (!std::find_if(legals.begin(), legals.end(),
565
+ [&opt_name](const char* str) { return opt_name == str; }))
566
+ log_cmd_error("Illegal argument %s for %s.\n", expected, name);
567
+ return true;
568
+ }
569
+ return false;
570
+ }
571
+ };
572
+
573
+ struct GetterOpts : TclOpts {
574
+ bool hierarchical_flag = false;
575
+ bool regexp_flag = false;
576
+ bool nocase_flag = false;
577
+ std::string separator = "/";
578
+ Tcl_Obj* of_objects = nullptr;
579
+ std::vector<std::string> patterns = {};
580
+ GetterOpts(const char* name, std::initializer_list<const char*> legals) : TclOpts(name, legals) {}
581
+ template<typename T>
582
+ bool parse_flag(Tcl_Obj* obj, const char* flag_name, T& flag_var) {
583
+ bool ret = parse_opt(obj, flag_name);
584
+ if (ret)
585
+ flag_var = true;
586
+ return ret;
587
+ }
588
+ void parse(int objc, Tcl_Obj* const objv[]) {
589
+ int i = 1;
590
+ for (; i < objc; i++) {
591
+ if (parse_flag(objv[i], "hierarchical", hierarchical_flag)) continue;
592
+ if (parse_flag(objv[i], "hier", hierarchical_flag)) continue;
593
+ if (parse_flag(objv[i], "regexp", regexp_flag)) continue;
594
+ if (parse_flag(objv[i], "nocase", nocase_flag)) continue;
595
+ if (parse_opt(objv[i], "hsc")) {
596
+ log_assert(i + 1 < objc);
597
+ separator = Tcl_GetString(objv[++i]);
598
+ continue;
599
+ }
600
+ if (parse_opt(objv[i], "of_objects")) {
601
+ log_assert(i + 1 < objc);
602
+ of_objects = objv[++i];
603
+ continue;
604
+ }
605
+ break;
606
+ }
607
+ for (; i < objc; i++) {
608
+ patterns.push_back(Tcl_GetString(objv[i]));
609
+ }
610
+ };
611
+ void check_simple() {
612
+ if (regexp_flag || hierarchical_flag || nocase_flag || separator != "/" || of_objects) {
613
+ log_error("%s got unexpected flags in simple mode\n", name);
614
+ }
615
+ if (patterns.size() != 1)
616
+ log_error("%s got unexpected number of patterns in simple mode: %zu\n", name, patterns.size());
617
+ }
618
+ void check_simple_sep() {
619
+ if (separator != "/")
620
+ log_error("Only '/' accepted as separator\n");
621
+ }
622
+ };
623
+
624
+ template <typename T>
625
+ void merge_or_init(const T& key, dict<T, BitSelection>& dst, const BitSelection& src) {
626
+ if (dst.count(key) == 0) {
627
+ dst[key] = src;
628
+ } else {
629
+ dst[key].merge(src);
630
+ }
631
+ }
632
+
633
+ static int sdc_get_pins_cmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[])
634
+ {
635
+ auto* objects = (SdcObjects*)data;
636
+ GetterOpts opts("get_pins", {"hierarchical", "hier", "regexp", "nocase", "hsc", "of_objects"});
637
+ opts.parse(objc, objv);
638
+ if (objects->collect_mode == SdcObjects::CollectMode::SimpleGetter)
639
+ opts.check_simple();
640
+ opts.check_simple_sep();
641
+
642
+ MatchConfig config(opts.regexp_flag, opts.nocase_flag, opts.hierarchical_flag);
643
+ std::vector<std::tuple<std::string, SdcObjects::CellPin, BitSelection>> resolved;
644
+ const auto& pins = objects->design_pins;
645
+ resolved = find_matching<SdcObjects::CellPin, decltype(pins)>(pins, config, opts.patterns, "pin");
646
+
647
+ return getter_graph_node(TclCall{interp, objc, objv});
648
+ }
649
+
650
+ static int sdc_get_ports_cmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[])
651
+ {
652
+ auto* objects = (SdcObjects*)data;
653
+ GetterOpts opts("get_ports", {"regexp", "nocase"});
654
+ opts.parse(objc, objv);
655
+ if (objects->collect_mode == SdcObjects::CollectMode::SimpleGetter)
656
+ opts.check_simple();
657
+
658
+ MatchConfig config(opts.regexp_flag, opts.nocase_flag, false);
659
+ std::vector<std::tuple<std::string, Wire*, BitSelection>> resolved;
660
+ const auto& ports = objects->design_ports;
661
+ resolved = find_matching<Wire*, decltype(ports)>(ports, config, opts.patterns, "port");
662
+
663
+ for (auto [name, wire, matching_bits] : resolved) {
664
+ if (objects->collect_mode != SdcObjects::CollectMode::FullConstraint)
665
+ merge_or_init(std::make_pair(name, wire), objects->constrained_ports, matching_bits);
666
+ }
667
+
668
+ return getter_graph_node(TclCall{interp, objc, objv});
669
+ }
670
+
671
+ static int sdc_get_nets_cmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[])
672
+ {
673
+ auto* objects = (SdcObjects*)data;
674
+ GetterOpts opts("get_nets", {"hierarchical", "hier", "regexp", "nocase", "hsc", "of_objects"});
675
+ opts.parse(objc, objv);
676
+ if (objects->collect_mode == SdcObjects::CollectMode::SimpleGetter)
677
+ opts.check_simple();
678
+
679
+ MatchConfig config(opts.regexp_flag, opts.nocase_flag, false);
680
+ std::vector<std::tuple<std::string, Wire*, BitSelection>> resolved;
681
+ const auto& ports = objects->design_nets;
682
+ resolved = find_matching<Wire*, decltype(ports)>(ports, config, opts.patterns, "net");
683
+
684
+ for (auto [name, wire, matching_bits] : resolved) {
685
+ if (objects->collect_mode != SdcObjects::CollectMode::FullConstraint)
686
+ merge_or_init(std::make_pair(name, wire), objects->constrained_nets, matching_bits);
687
+ }
688
+
689
+ return getter_graph_node(TclCall{interp, objc, objv});
690
+ }
691
+
692
+ class SDCInterpreter
693
+ {
694
+ private:
695
+ Tcl_Interp* interp = nullptr;
696
+ public:
697
+ std::unique_ptr<SdcObjects> objects;
698
+ ~SDCInterpreter() {
699
+ if (interp)
700
+ Tcl_DeleteInterp(interp);
701
+ }
702
+ static SDCInterpreter& get() {
703
+ static SDCInterpreter instance;
704
+ return instance;
705
+ }
706
+ Tcl_Interp* fresh_interp(Design* design) {
707
+ if (interp)
708
+ Tcl_DeleteInterp(interp);
709
+
710
+ interp = Tcl_CreateInterp();
711
+ if (Tcl_Init(interp)!=TCL_OK)
712
+ log_error("Tcl_Init() call failed - %s\n",Tcl_ErrnoMsg(Tcl_GetErrno()));
713
+
714
+ objects = std::make_unique<SdcObjects>(design);
715
+ objects->collect_mode = SdcObjects::CollectMode::SimpleGetter;
716
+ Tcl_CreateObjCommand(interp, "get_pins", sdc_get_pins_cmd, (ClientData) objects.get(), NULL);
717
+ Tcl_CreateObjCommand(interp, "get_nets", sdc_get_nets_cmd, (ClientData) objects.get(), NULL);
718
+ Tcl_CreateObjCommand(interp, "get_ports", sdc_get_ports_cmd, (ClientData) objects.get(), NULL);
719
+ return interp;
720
+ }
721
+ };
722
+
723
+ // Also see TclPass
724
+ struct SdcPass : public Pass {
725
+ void help() override
726
+ {
727
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
728
+ log("\n");
729
+ log(" sdc [options] file\n");
730
+ log("\n");
731
+ log("Read the SDC file for the current design.\n");
732
+ log("\n");
733
+ log(" -dump\n");
734
+ log(" Dump the referenced design objects.\n");
735
+ log("\n");
736
+ log(" -dump-graph\n");
737
+ log(" Dump the uninterpreted call graph.\n");
738
+ log("\n");
739
+ log(" -keep_hierarchy\n");
740
+ log(" Add keep_hierarchy attributes while retaining SDC validity.\n");
741
+ log("\n");
742
+ }
743
+ SdcPass() : Pass("sdc", "Read an SDC file") { }
744
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override {
745
+ log_header(design, "Executing SDC pass.\n");
746
+ log_experimental("sdc");
747
+ size_t argidx;
748
+ bool dump_mode = false;
749
+ bool dump_graph_mode = false;
750
+ bool keep_hierarchy_mode = false;
751
+ std::vector<std::string> stubs_paths;
752
+ for (argidx = 1; argidx < args.size(); argidx++) {
753
+ if (args[argidx] == "-dump") {
754
+ dump_mode = true;
755
+ continue;
756
+ } else if (args[argidx] == "-dump-graph") {
757
+ dump_graph_mode = true;
758
+ continue;
759
+ } else if (args[argidx] == "-keep_hierarchy") {
760
+ keep_hierarchy_mode = true;
761
+ continue;
762
+ } else if (args[argidx] == "-stubs" && argidx+1 < args.size()) {
763
+ stubs_paths.push_back(args[++argidx]);
764
+ continue;
765
+ }
766
+ break;
767
+ }
768
+ if (argidx >= args.size())
769
+ log_cmd_error("Missing SDC file.\n");
770
+
771
+ std::string sdc_path = args[argidx++];
772
+ if (argidx < args.size())
773
+ log_cmd_error("Unexpected extra positional argument %s after SDC file %s.\n", args[argidx], sdc_path);
774
+ SDCInterpreter& sdc = SDCInterpreter::get();
775
+ Tcl_Interp *interp = sdc.fresh_interp(design);
776
+ Tcl_Preserve(interp);
777
+ std::string stub_path = "+/sdc/graph-stubs.sdc";
778
+ rewrite_filename(stub_path);
779
+ if (Tcl_EvalFile(interp, stub_path.c_str()) != TCL_OK)
780
+ log_cmd_error("SDC interpreter returned an error in stub preamble file: %s\n", Tcl_GetStringResult(interp));
781
+ for (auto path : stubs_paths)
782
+ if (Tcl_EvalFile(interp, path.c_str()) != TCL_OK)
783
+ log_cmd_error("SDC interpreter returned an error in OpenSTA stub file %s: %s\n", path, Tcl_GetStringResult(interp));
784
+ if (Tcl_EvalFile(interp, sdc_path.c_str()) != TCL_OK)
785
+ log_cmd_error("SDC interpreter returned an error: %s\n", Tcl_GetStringResult(interp));
786
+ if (dump_mode)
787
+ sdc.objects->dump();
788
+ if (keep_hierarchy_mode)
789
+ sdc.objects->keep_hierarchy();
790
+ inspect_globals(interp, dump_graph_mode);
791
+ Tcl_Release(interp);
792
+ }
793
+ } SdcPass;
794
+
795
+ YOSYS_NAMESPACE_END
796
+ #endif
chips/yosys/passes/cmds/select.cc ADDED
@@ -0,0 +1,1851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/rtlil.h"
21
+ #include "kernel/twine.h"
22
+ #include "kernel/yosys.h"
23
+ #include "kernel/newcelltypes.h"
24
+ #include "kernel/sigtools.h"
25
+ #include "kernel/log_help.h"
26
+
27
+ USING_YOSYS_NAMESPACE
28
+ PRIVATE_NAMESPACE_BEGIN
29
+
30
+
31
+ static bool match_ids(const std::string &id, const std::string &pattern)
32
+ {
33
+ if (id == pattern)
34
+ return true;
35
+
36
+ const char *id_c = id.c_str();
37
+ const char *pat_c = pattern.c_str();
38
+ size_t id_size = id.size();
39
+ size_t pat_size = pattern.size();
40
+
41
+ if (*id_c == '\\' && id_size == 1 + pat_size && memcmp(id_c + 1, pat_c, pat_size) == 0)
42
+ return true;
43
+ if (patmatch(pat_c, id_c))
44
+ return true;
45
+ if (*id_c == '\\' && patmatch(pat_c, id_c + 1))
46
+ return true;
47
+ if (*id_c == '$' && *pat_c == '$') {
48
+ const char *q = strrchr(id_c, '$');
49
+ if (pattern == q)
50
+ return true;
51
+ }
52
+ return false;
53
+ }
54
+
55
+ static bool match_attr_val(const RTLIL::Const &value, const std::string &pattern, char match_op)
56
+ {
57
+ if (match_op == 0)
58
+ return true;
59
+
60
+ if ((value.flags & RTLIL::CONST_FLAG_STRING) == 0)
61
+ {
62
+ RTLIL::SigSpec sig_value;
63
+
64
+ if (!RTLIL::SigSpec::parse(sig_value, nullptr, pattern))
65
+ return false;
66
+
67
+ RTLIL::Const pattern_value = sig_value.as_const();
68
+
69
+ if (match_op == '=')
70
+ return value == pattern_value;
71
+ if (match_op == '!')
72
+ return value != pattern_value;
73
+ if (match_op == '<')
74
+ return value.as_int() < pattern_value.as_int();
75
+ if (match_op == '>')
76
+ return value.as_int() > pattern_value.as_int();
77
+ if (match_op == '[')
78
+ return value.as_int() <= pattern_value.as_int();
79
+ if (match_op == ']')
80
+ return value.as_int() >= pattern_value.as_int();
81
+ }
82
+ else
83
+ {
84
+ std::string value_str = value.decode_string();
85
+
86
+ if (match_op == '=')
87
+ if (patmatch(pattern.c_str(), value.decode_string().c_str()))
88
+ return true;
89
+
90
+ if (match_op == '=')
91
+ return value_str == pattern;
92
+ if (match_op == '!')
93
+ return value_str != pattern;
94
+ if (match_op == '<')
95
+ return value_str < pattern;
96
+ if (match_op == '>')
97
+ return value_str > pattern;
98
+ if (match_op == '[')
99
+ return value_str <= pattern;
100
+ if (match_op == ']')
101
+ return value_str >= pattern;
102
+ }
103
+
104
+ log_abort();
105
+ }
106
+
107
+ static bool match_attr(const TwinePool &pool, const dict<IdString, RTLIL::Const> &attributes, const std::string &name_pat, const std::string &value_pat, char match_op)
108
+ {
109
+ if (name_pat.find('*') != std::string::npos || name_pat.find('?') != std::string::npos || name_pat.find('[') != std::string::npos) {
110
+ for (auto &it : attributes) {
111
+ std::string name = pool.str(it.first);
112
+ if (patmatch(name_pat.c_str(), name.c_str()) && match_attr_val(it.second, value_pat, match_op))
113
+ return true;
114
+ if (name.size() > 0 && name[0] == '\\' && patmatch(name_pat.c_str(), name.c_str() + 1) && match_attr_val(it.second, value_pat, match_op))
115
+ return true;
116
+ }
117
+ } else {
118
+ if (name_pat.size() > 0 && (name_pat[0] == '\\' || name_pat[0] == '$')) {
119
+ IdString key = pool.find(name_pat);
120
+ if (key != IdString::Null && attributes.count(key) && match_attr_val(attributes.at(key), value_pat, match_op))
121
+ return true;
122
+ }
123
+ IdString key = pool.find("\\" + name_pat);
124
+ if (key != IdString::Null && attributes.count(key) && match_attr_val(attributes.at(key), value_pat, match_op))
125
+ return true;
126
+ }
127
+ return false;
128
+ }
129
+
130
+ static bool match_attr(const TwinePool &pool, const dict<IdString, RTLIL::Const> &attributes, const std::string &match_expr)
131
+ {
132
+ size_t pos = match_expr.find_first_of("<!=>");
133
+
134
+ if (pos != std::string::npos) {
135
+ if (match_expr.compare(pos, 2, "!=") == 0)
136
+ return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+2), '!');
137
+ if (match_expr.compare(pos, 2, "<=") == 0)
138
+ return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+2), '[');
139
+ if (match_expr.compare(pos, 2, ">=") == 0)
140
+ return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+2), ']');
141
+ return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+1), match_expr[pos]);
142
+ }
143
+
144
+ return match_attr(pool, attributes, match_expr, std::string(), 0);
145
+ }
146
+
147
+ static void select_all(RTLIL::Design *design, RTLIL::Selection &lhs)
148
+ {
149
+ if (!lhs.selects_all())
150
+ return;
151
+ lhs.current_design = design;
152
+ lhs.selected_modules.clear();
153
+ for (auto mod : design->modules()) {
154
+ if (!lhs.selects_boxes && mod->get_blackbox_attribute())
155
+ continue;
156
+ lhs.selected_modules.insert(mod->name);
157
+ }
158
+ lhs.full_selection = false;
159
+ lhs.complete_selection = false;
160
+ }
161
+
162
+ static void select_op_neg(RTLIL::Design *design, RTLIL::Selection &lhs)
163
+ {
164
+ if (lhs.selects_all()) {
165
+ lhs.clear();
166
+ return;
167
+ }
168
+
169
+ if (lhs.selected_modules.size() == 0 && lhs.selected_members.size() == 0) {
170
+ if (lhs.selects_boxes)
171
+ lhs.complete_selection = true;
172
+ else
173
+ lhs.full_selection = true;
174
+ return;
175
+ }
176
+
177
+ auto new_sel = RTLIL::Selection::EmptySelection();
178
+
179
+ for (auto mod : design->modules())
180
+ {
181
+ if (!lhs.selects_boxes && mod->get_blackbox_attribute())
182
+ continue;
183
+ if (lhs.selected_whole_module(mod->name))
184
+ continue;
185
+ if (!lhs.selected_module(mod->name)) {
186
+ new_sel.selected_modules.insert(mod->name);
187
+ continue;
188
+ }
189
+
190
+ for (auto wire : mod->wires())
191
+ if (!lhs.selected_member(mod->name, wire->name))
192
+ new_sel.selected_members[mod->name].insert(wire->name);
193
+ for (auto &it : mod->memories)
194
+ if (!lhs.selected_member(mod->name, it.first))
195
+ new_sel.selected_members[mod->name].insert(it.first);
196
+ for (auto cell : mod->cells())
197
+ if (!lhs.selected_member(mod->name, cell->name))
198
+ new_sel.selected_members[mod->name].insert(cell->name);
199
+ for (auto &it : mod->processes)
200
+ if (!lhs.selected_member(mod->name, it.first))
201
+ new_sel.selected_members[mod->name].insert(it.first);
202
+ }
203
+
204
+ lhs.selected_modules.swap(new_sel.selected_modules);
205
+ lhs.selected_members.swap(new_sel.selected_members);
206
+ }
207
+
208
+ static int my_xorshift32_rng() {
209
+ static uint32_t x32 = 314159265;
210
+ x32 ^= x32 << 13;
211
+ x32 ^= x32 >> 17;
212
+ x32 ^= x32 << 5;
213
+ return x32 & 0x0fffffff;
214
+ }
215
+
216
+ static void select_op_random(RTLIL::Design *design, RTLIL::Selection &lhs, int count)
217
+ {
218
+ vector<pair<IdString, IdString>> objects;
219
+
220
+ for (auto mod : design->modules())
221
+ {
222
+ if (!lhs.selected_module(mod->name))
223
+ continue;
224
+
225
+ for (auto cell : mod->cells()) {
226
+ if (lhs.selected_member(mod->name, cell->name))
227
+ objects.push_back(make_pair(mod->name, cell->name));
228
+ }
229
+
230
+ for (auto wire : mod->wires()) {
231
+ if (lhs.selected_member(mod->name, wire->name))
232
+ objects.push_back(make_pair(mod->name, wire->name));
233
+ }
234
+ }
235
+
236
+ lhs = RTLIL::Selection(false, lhs.selects_boxes, design);
237
+
238
+ while (!objects.empty() && count-- > 0)
239
+ {
240
+ int idx = my_xorshift32_rng() % GetSize(objects);
241
+ lhs.selected_members[objects[idx].first].insert(objects[idx].second);
242
+ objects[idx] = objects.back();
243
+ objects.pop_back();
244
+ }
245
+
246
+ lhs.optimize(design);
247
+ }
248
+
249
+ static void select_op_submod(RTLIL::Design *design, RTLIL::Selection &lhs)
250
+ {
251
+ for (auto mod : design->modules())
252
+ {
253
+ if (lhs.selected_whole_module(mod->name))
254
+ {
255
+ for (auto cell : mod->cells())
256
+ {
257
+ if (design->module(cell->type) == nullptr)
258
+ continue;
259
+ lhs.selected_modules.insert(cell->type);
260
+ }
261
+ }
262
+ }
263
+ }
264
+
265
+ static void select_op_cells_to_modules(RTLIL::Design *design, RTLIL::Selection &lhs)
266
+ {
267
+ RTLIL::Selection new_sel(false, lhs.selects_boxes, design);
268
+ for (auto mod : design->modules())
269
+ if (lhs.selected_module(mod->name))
270
+ for (auto cell : mod->cells())
271
+ if (lhs.selected_member(mod->name, cell->name) && (design->module(cell->type) != nullptr))
272
+ new_sel.selected_modules.insert(cell->type);
273
+ lhs = new_sel;
274
+ }
275
+
276
+ static void select_op_module_to_cells(RTLIL::Design *design, RTLIL::Selection &lhs)
277
+ {
278
+ RTLIL::Selection new_sel(false, lhs.selects_boxes, design);
279
+ for (auto mod : design->modules())
280
+ for (auto cell : mod->cells())
281
+ if ((design->module(cell->type) != nullptr) && lhs.selected_whole_module(cell->type))
282
+ new_sel.selected_members[mod->name].insert(cell->name);
283
+ lhs = new_sel;
284
+ }
285
+
286
+ static void select_op_fullmod(RTLIL::Design *design, RTLIL::Selection &lhs)
287
+ {
288
+ lhs.optimize(design);
289
+ for (auto &it : lhs.selected_members)
290
+ lhs.selected_modules.insert(it.first);
291
+ lhs.selected_members.clear();
292
+ }
293
+
294
+ static void select_op_alias(RTLIL::Design *design, RTLIL::Selection &lhs)
295
+ {
296
+ for (auto mod : design->modules())
297
+ {
298
+ if (!lhs.selects_boxes && mod->get_blackbox_attribute())
299
+ continue;
300
+ if (lhs.selected_whole_module(mod->name))
301
+ continue;
302
+ if (!lhs.selected_module(mod->name))
303
+ continue;
304
+
305
+ SigMap sigmap(mod);
306
+ SigPool selected_bits;
307
+
308
+ for (auto wire : mod->wires())
309
+ if (lhs.selected_member(mod->name, wire->name))
310
+ selected_bits.add(sigmap(wire));
311
+
312
+ for (auto wire : mod->wires())
313
+ if (!lhs.selected_member(mod->name, wire->name) && selected_bits.check_any(sigmap(wire)))
314
+ lhs.selected_members[mod->name].insert(wire->name);
315
+ }
316
+ }
317
+
318
+ static void select_op_union(RTLIL::Design* design, RTLIL::Selection &lhs, const RTLIL::Selection &rhs)
319
+ {
320
+ if (lhs.complete_selection)
321
+ return;
322
+ else if (rhs.complete_selection) {
323
+ lhs.complete_selection = true;
324
+ lhs.optimize(design);
325
+ return;
326
+ }
327
+
328
+ if (rhs.selects_boxes) {
329
+ if (lhs.full_selection) {
330
+ select_all(design, lhs);
331
+ }
332
+ lhs.selects_boxes = true;
333
+ }
334
+ else if (lhs.full_selection)
335
+ return;
336
+
337
+ if (rhs.full_selection) {
338
+ if (lhs.selects_boxes) {
339
+ auto new_rhs = RTLIL::Selection(rhs);
340
+ select_all(design, new_rhs);
341
+ for (auto mod : new_rhs.selected_modules)
342
+ lhs.selected_modules.insert(mod);
343
+ } else {
344
+ lhs.clear();
345
+ lhs.full_selection = true;
346
+ }
347
+ return;
348
+ }
349
+
350
+ for (auto &it : rhs.selected_members)
351
+ for (auto &it2 : it.second)
352
+ lhs.selected_members[it.first].insert(it2);
353
+
354
+ for (auto &it : rhs.selected_modules) {
355
+ lhs.selected_modules.insert(it);
356
+ lhs.selected_members.erase(it);
357
+ }
358
+ }
359
+
360
+ static void select_op_union_all(RTLIL::Design *design, std::vector<RTLIL::Selection> &work_stack)
361
+ {
362
+ while (work_stack.size() > 1) {
363
+ select_op_union(design, work_stack.front(), work_stack.back());
364
+ work_stack.pop_back();
365
+ }
366
+ }
367
+
368
+ static void select_op_diff(RTLIL::Design *design, RTLIL::Selection &lhs, const RTLIL::Selection &rhs)
369
+ {
370
+ if (rhs.complete_selection) {
371
+ lhs.clear();
372
+ return;
373
+ }
374
+
375
+ if (rhs.full_selection) {
376
+ if (lhs.selects_boxes) {
377
+ auto new_rhs = RTLIL::Selection(rhs);
378
+ select_all(design, new_rhs);
379
+ select_all(design, lhs);
380
+ for (auto mod : new_rhs.selected_modules) {
381
+ lhs.selected_modules.erase(mod);
382
+ lhs.selected_members.erase(mod);
383
+ }
384
+ } else {
385
+ lhs.clear();
386
+ }
387
+ return;
388
+ }
389
+
390
+ if (rhs.empty() || lhs.empty())
391
+ return;
392
+
393
+ select_all(design, lhs);
394
+
395
+ for (auto &it : rhs.selected_modules) {
396
+ lhs.selected_modules.erase(it);
397
+ lhs.selected_members.erase(it);
398
+ }
399
+
400
+ for (auto &it : rhs.selected_members)
401
+ {
402
+ if (design->module(it.first) == nullptr)
403
+ continue;
404
+
405
+ RTLIL::Module *mod = design->module(it.first);
406
+
407
+ if (lhs.selected_modules.count(mod->name) > 0)
408
+ {
409
+ for (auto wire : mod->wires())
410
+ lhs.selected_members[mod->name].insert(wire->name);
411
+ for (auto &it : mod->memories)
412
+ lhs.selected_members[mod->name].insert(it.first);
413
+ for (auto cell : mod->cells())
414
+ lhs.selected_members[mod->name].insert(cell->name);
415
+ for (auto &it : mod->processes)
416
+ lhs.selected_members[mod->name].insert(it.first);
417
+ lhs.selected_modules.erase(mod->name);
418
+ }
419
+
420
+ if (lhs.selected_members.count(mod->name) == 0)
421
+ continue;
422
+
423
+ for (auto &it2 : it.second)
424
+ lhs.selected_members[mod->name].erase(it2);
425
+ }
426
+ }
427
+
428
+ static void select_op_intersect(RTLIL::Design *design, RTLIL::Selection &lhs, const RTLIL::Selection &rhs)
429
+ {
430
+ if (rhs.complete_selection)
431
+ return;
432
+
433
+ if (rhs.full_selection && !lhs.selects_boxes)
434
+ return;
435
+
436
+ if (lhs.empty())
437
+ return;
438
+
439
+ if (rhs.empty()) {
440
+ lhs.clear();
441
+ return;
442
+ }
443
+
444
+ select_all(design, lhs);
445
+
446
+ std::vector<RTLIL::IdString> del_list;
447
+
448
+ for (auto mod_name : lhs.selected_modules) {
449
+ if (rhs.selected_whole_module(mod_name))
450
+ continue;
451
+ if (rhs.selected_module(mod_name))
452
+ for (auto memb_name : rhs.selected_members.at(mod_name))
453
+ lhs.selected_members[mod_name].insert(memb_name);
454
+ del_list.push_back(mod_name);
455
+ }
456
+ for (auto &it : del_list)
457
+ lhs.selected_modules.erase(it);
458
+
459
+ del_list.clear();
460
+ for (auto &it : lhs.selected_members) {
461
+ if (rhs.selected_whole_module(it.first))
462
+ continue;
463
+ if (!rhs.selected_module(it.first)) {
464
+ del_list.push_back(it.first);
465
+ continue;
466
+ }
467
+ std::vector<RTLIL::IdString> del_list2;
468
+ for (auto &it2 : it.second)
469
+ if (!rhs.selected_member(it.first, it2))
470
+ del_list2.push_back(it2);
471
+ for (auto &it2 : del_list2)
472
+ it.second.erase(it2);
473
+ if (it.second.size() == 0)
474
+ del_list.push_back(it.first);
475
+ }
476
+ for (auto &it : del_list)
477
+ lhs.selected_members.erase(it);
478
+ }
479
+
480
+ namespace {
481
+ struct expand_rule_t {
482
+ char mode;
483
+ std::set<std::string> cell_types, port_names;
484
+ };
485
+ }
486
+
487
+ static int parse_comma_list(std::set<std::string> &tokens, const std::string &str, size_t pos, std::string stopchar)
488
+ {
489
+ stopchar += ',';
490
+ while (1) {
491
+ size_t endpos = str.find_first_of(stopchar, pos);
492
+ if (endpos == std::string::npos)
493
+ endpos = str.size();
494
+ if (endpos != pos)
495
+ tokens.insert(RTLIL::escape_id(str.substr(pos, endpos-pos)));
496
+ pos = endpos;
497
+ if (pos == str.size() || str[pos] != ',')
498
+ return pos;
499
+ pos++;
500
+ }
501
+ }
502
+
503
+ static int select_op_expand(RTLIL::Design *design, RTLIL::Selection &lhs, std::vector<expand_rule_t> &rules, std::set<RTLIL::IdString> &limits, int max_objects, char mode, NewCellTypes &ct, bool eval_only)
504
+ {
505
+ int sel_objects = 0;
506
+ bool is_input, is_output;
507
+ for (auto mod : design->modules())
508
+ {
509
+ if (lhs.selected_whole_module(mod->name) || !lhs.selected_module(mod->name))
510
+ continue;
511
+
512
+ std::set<RTLIL::Wire*> selected_wires;
513
+ auto selected_members = lhs.selected_members[mod->name];
514
+
515
+ for (auto wire : mod->wires())
516
+ if (lhs.selected_member(mod->name, wire->name) && limits.count(wire->name) == 0)
517
+ selected_wires.insert(wire);
518
+
519
+ for (auto &conn : mod->connections())
520
+ {
521
+ std::vector<RTLIL::SigBit> conn_lhs = conn.first.to_sigbit_vector();
522
+ std::vector<RTLIL::SigBit> conn_rhs = conn.second.to_sigbit_vector();
523
+
524
+ for (size_t i = 0; i < conn_lhs.size(); i++) {
525
+ if (conn_lhs[i].wire == nullptr || conn_rhs[i].wire == nullptr)
526
+ continue;
527
+ if (mode != 'i' && selected_wires.count(conn_rhs[i].wire) && selected_members.count(conn_lhs[i].wire->name) == 0)
528
+ lhs.selected_members[mod->name].insert(conn_lhs[i].wire->name), sel_objects++, max_objects--;
529
+ if (mode != 'o' && selected_wires.count(conn_lhs[i].wire) && selected_members.count(conn_rhs[i].wire->name) == 0)
530
+ lhs.selected_members[mod->name].insert(conn_rhs[i].wire->name), sel_objects++, max_objects--;
531
+ }
532
+ }
533
+
534
+ auto &twines = design->twines();
535
+ for (auto cell : mod->cells())
536
+ for (auto &conn : cell->connections())
537
+ {
538
+ char last_mode = '-';
539
+ if (eval_only && !yosys_celltypes.cell_evaluable(cell->type))
540
+ goto exclude_match;
541
+ for (auto &rule : rules) {
542
+ last_mode = rule.mode;
543
+ if (rule.cell_types.size() > 0 && rule.cell_types.count(cell->type) == 0)
544
+ continue;
545
+ if (rule.port_names.size() > 0 && rule.port_names.count(twines.str(conn.first)) == 0)
546
+ continue;
547
+ if (rule.mode == '+')
548
+ goto include_match;
549
+ else
550
+ goto exclude_match;
551
+ }
552
+ if (last_mode == '+')
553
+ goto exclude_match;
554
+ include_match:
555
+ is_input = mode == 'x' || ct.cell_input(cell->type, conn.first);
556
+ is_output = mode == 'x' || ct.cell_output(cell->type, conn.first);
557
+ for (auto &chunk : conn.second.chunks())
558
+ if (chunk.wire != nullptr) {
559
+ if (max_objects != 0 && selected_wires.count(chunk.wire) > 0 && selected_members.count(cell->name) == 0)
560
+ if (mode == 'x' || (mode == 'i' && is_output) || (mode == 'o' && is_input))
561
+ lhs.selected_members[mod->name].insert(cell->name), sel_objects++, max_objects--;
562
+ if (max_objects != 0 && selected_members.count(cell->name) > 0 && limits.count(cell->name) == 0 && selected_members.count(chunk.wire->name) == 0)
563
+ if (mode == 'x' || (mode == 'i' && is_input) || (mode == 'o' && is_output))
564
+ lhs.selected_members[mod->name].insert(chunk.wire->name), sel_objects++, max_objects--;
565
+ }
566
+ exclude_match:;
567
+ }
568
+ }
569
+
570
+ return sel_objects;
571
+ }
572
+
573
+ static void select_op_expand(RTLIL::Design *design, std::vector<RTLIL::Selection> &work_stack, const std::string &arg, char mode, bool eval_only)
574
+ {
575
+ int pos = (mode == 'x' ? 2 : 3) + (eval_only ? 1 : 0);
576
+ int levels = 1, rem_objects = -1;
577
+ std::vector<expand_rule_t> rules;
578
+ std::set<RTLIL::IdString> limits;
579
+
580
+ NewCellTypes ct;
581
+
582
+ if (mode != 'x')
583
+ ct.setup(design);
584
+
585
+ if (pos < int(arg.size()) && arg[pos] == '*') {
586
+ levels = 1'000'000;
587
+ pos++;
588
+ } else
589
+ if (pos < int(arg.size()) && '0' <= arg[pos] && arg[pos] <= '9') {
590
+ size_t endpos = arg.find_first_not_of("0123456789", pos);
591
+ if (endpos == std::string::npos)
592
+ endpos = arg.size();
593
+ levels = atoi(arg.substr(pos, endpos-pos).c_str());
594
+ pos = endpos;
595
+ }
596
+
597
+ if (pos < int(arg.size()) && arg[pos] == '.') {
598
+ size_t endpos = arg.find_first_not_of("0123456789", ++pos);
599
+ if (endpos == std::string::npos)
600
+ endpos = arg.size();
601
+ if (int(endpos) > pos)
602
+ rem_objects = atoi(arg.substr(pos, endpos-pos).c_str());
603
+ pos = endpos;
604
+ }
605
+
606
+ while (pos < int(arg.size())) {
607
+ if (arg[pos] != ':' || pos+1 == int(arg.size()))
608
+ log_cmd_error("Syntax error in expand operator '%s'.\n", arg);
609
+ pos++;
610
+ if (arg[pos] == '+' || arg[pos] == '-') {
611
+ expand_rule_t rule;
612
+ rule.mode = arg[pos++];
613
+ pos = parse_comma_list(rule.cell_types, arg, pos, "[:");
614
+ if (pos < int(arg.size()) && arg[pos] == '[') {
615
+ pos = parse_comma_list(rule.port_names, arg, pos+1, "]:");
616
+ if (pos < int(arg.size()) && arg[pos] == ']')
617
+ pos++;
618
+ }
619
+ rules.push_back(rule);
620
+ } else {
621
+ size_t endpos = arg.find(':', pos);
622
+ if (endpos == std::string::npos)
623
+ endpos = arg.size();
624
+ if (int(endpos) > pos) {
625
+ std::string str = arg.substr(pos, endpos-pos);
626
+ if (str[0] == '@') {
627
+ str = RTLIL::escape_id(str.substr(1));
628
+ IdString sel_name = design->twines().find(str);
629
+ if (sel_name != IdString::Null && design->selection_vars.count(sel_name) > 0) {
630
+ for (auto i1 : design->selection_vars.at(sel_name).selected_members)
631
+ for (auto i2 : i1.second)
632
+ limits.insert(i2);
633
+ } else
634
+ log_cmd_error("Selection %s is not defined!\n", RTLIL::unescape_id(str));
635
+ } else
636
+ limits.insert(design->twines().add(RTLIL::escape_id(str)));
637
+ }
638
+ pos = endpos;
639
+ }
640
+ }
641
+
642
+ #if 0
643
+ log("expand by %d levels (max. %d objects):\n", levels, rem_objects);
644
+ for (auto &rule : rules) {
645
+ log(" rule (%c):\n", rule.mode);
646
+ if (rule.cell_types.size() > 0) {
647
+ std::string message = " cell types:";
648
+ for (auto &it : rule.cell_types)
649
+ message += stringf(" %s", it);
650
+ log("%s\n", message);
651
+ }
652
+ if (rule.port_names.size() > 0) {
653
+ std::string message = " port names:";
654
+ for (auto &it : rule.port_names)
655
+ message += stringf(" %s", it);
656
+ log("%s\n", message);
657
+ }
658
+ }
659
+ if (limits.size() > 0) {
660
+ std::string message = " limits:";
661
+ for (auto &it : limits)
662
+ message += stringf(" %s", it);
663
+ log("%s\n", message);
664
+ }
665
+ #endif
666
+
667
+ while (levels-- > 0 && rem_objects != 0) {
668
+ int num_objects = select_op_expand(design, work_stack.back(), rules, limits, rem_objects, mode, ct, eval_only);
669
+ if (num_objects == 0)
670
+ break;
671
+ rem_objects -= num_objects;
672
+ }
673
+
674
+ if (rem_objects == 0)
675
+ log_warning("reached configured limit at `%s'.\n", arg);
676
+ }
677
+
678
+ static void select_filter_active_mod(RTLIL::Design *design, RTLIL::Selection &sel)
679
+ {
680
+ if (design->selected_active_module.empty())
681
+ return;
682
+
683
+ if (sel.full_selection) {
684
+ sel.clear();
685
+ sel.selected_modules.insert(design->selected_active_module);
686
+ return;
687
+ }
688
+
689
+ std::vector<RTLIL::IdString> del_list;
690
+ for (auto mod_name : sel.selected_modules)
691
+ if (mod_name != design->selected_active_module)
692
+ del_list.push_back(mod_name);
693
+ for (auto &it : sel.selected_members)
694
+ if (it.first != design->selected_active_module)
695
+ del_list.push_back(it.first);
696
+ for (auto mod_name : del_list) {
697
+ sel.selected_modules.erase(mod_name);
698
+ sel.selected_members.erase(mod_name);
699
+ }
700
+ }
701
+
702
+ static void select_stmt(RTLIL::Design *design, std::vector<RTLIL::Selection> &work_stack, std::string arg, bool disable_empty_warning = false)
703
+ {
704
+ std::string arg_mod, arg_memb;
705
+ std::unordered_map<std::string, bool> arg_mod_found;
706
+ std::unordered_map<std::string, bool> arg_memb_found;
707
+
708
+ auto isprefixed = [](const string &s) {
709
+ return GetSize(s) >= 2 && ((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z')) && s[1] == ':';
710
+ };
711
+
712
+ if (arg.size() == 0)
713
+ return;
714
+
715
+ if (arg[0] == '%') {
716
+ if (arg == "%") {
717
+ work_stack.push_back(design->selection());
718
+ } else
719
+ if (arg == "%%") {
720
+ select_op_union_all(design, work_stack);
721
+ } else
722
+ if (arg == "%n") {
723
+ if (work_stack.size() < 1)
724
+ log_cmd_error("Must have at least one element on the stack for operator %%n.\n");
725
+ select_op_neg(design, work_stack[work_stack.size()-1]);
726
+ } else
727
+ if (arg == "%u") {
728
+ if (work_stack.size() < 2)
729
+ log_cmd_error("Must have at least two elements on the stack for operator %%u.\n");
730
+ select_op_union(design, work_stack[work_stack.size()-2], work_stack[work_stack.size()-1]);
731
+ work_stack.pop_back();
732
+ } else
733
+ if (arg == "%d") {
734
+ if (work_stack.size() < 2)
735
+ log_cmd_error("Must have at least two elements on the stack for operator %%d.\n");
736
+ select_op_diff(design, work_stack[work_stack.size()-2], work_stack[work_stack.size()-1]);
737
+ work_stack.pop_back();
738
+ } else
739
+ if (arg == "%D") {
740
+ if (work_stack.size() < 2)
741
+ log_cmd_error("Must have at least two elements on the stack for operator %%D.\n");
742
+ select_op_diff(design, work_stack[work_stack.size()-1], work_stack[work_stack.size()-2]);
743
+ work_stack[work_stack.size()-2] = work_stack[work_stack.size()-1];
744
+ work_stack.pop_back();
745
+ } else
746
+ if (arg == "%i") {
747
+ if (work_stack.size() < 2)
748
+ log_cmd_error("Must have at least two elements on the stack for operator %%i.\n");
749
+ select_op_intersect(design, work_stack[work_stack.size()-2], work_stack[work_stack.size()-1]);
750
+ work_stack.pop_back();
751
+ } else
752
+ if (arg.size() >= 2 && arg[0] == '%' && arg[1] == 'R') {
753
+ if (work_stack.size() < 1)
754
+ log_cmd_error("Must have at least one element on the stack for operator %%R.\n");
755
+ int count = arg.size() > 2 ? atoi(arg.c_str() + 2) : 1;
756
+ select_op_random(design, work_stack[work_stack.size()-1], count);
757
+ } else
758
+ if (arg == "%s") {
759
+ if (work_stack.size() < 1)
760
+ log_cmd_error("Must have at least one element on the stack for operator %%s.\n");
761
+ select_op_submod(design, work_stack[work_stack.size()-1]);
762
+ } else
763
+ if (arg == "%M") {
764
+ if (work_stack.size() < 1)
765
+ log_cmd_error("Must have at least one element on the stack for operator %%M.\n");
766
+ select_op_cells_to_modules(design, work_stack[work_stack.size()-1]);
767
+ } else
768
+ if (arg == "%C") {
769
+ if (work_stack.size() < 1)
770
+ log_cmd_error("Must have at least one element on the stack for operator %%C.\n");
771
+ select_op_module_to_cells(design, work_stack[work_stack.size()-1]);
772
+ } else
773
+ if (arg == "%c") {
774
+ if (work_stack.size() < 1)
775
+ log_cmd_error("Must have at least one element on the stack for operator %%c.\n");
776
+ work_stack.push_back(work_stack.back());
777
+ } else
778
+ if (arg == "%m") {
779
+ if (work_stack.size() < 1)
780
+ log_cmd_error("Must have at least one element on the stack for operator %%m.\n");
781
+ select_op_fullmod(design, work_stack[work_stack.size()-1]);
782
+ } else
783
+ if (arg == "%a") {
784
+ if (work_stack.size() < 1)
785
+ log_cmd_error("Must have at least one element on the stack for operator %%a.\n");
786
+ select_op_alias(design, work_stack[work_stack.size()-1]);
787
+ } else
788
+ if (arg == "%x" || (arg.size() > 2 && arg.compare(0, 2, "%x") == 0 && (arg[2] == ':' || arg[2] == '*' || arg[2] == '.' || ('0' <= arg[2] && arg[2] <= '9')))) {
789
+ if (work_stack.size() < 1)
790
+ log_cmd_error("Must have at least one element on the stack for operator %%x.\n");
791
+ select_op_expand(design, work_stack, arg, 'x', false);
792
+ } else
793
+ if (arg == "%ci" || (arg.size() > 3 && arg.compare(0, 3, "%ci") == 0 && (arg[3] == ':' || arg[3] == '*' || arg[3] == '.' || ('0' <= arg[3] && arg[3] <= '9')))) {
794
+ if (work_stack.size() < 1)
795
+ log_cmd_error("Must have at least one element on the stack for operator %%ci.\n");
796
+ select_op_expand(design, work_stack, arg, 'i', false);
797
+ } else
798
+ if (arg == "%co" || (arg.size() > 3 && arg.compare(0, 3, "%co") == 0 && (arg[3] == ':' || arg[3] == '*' || arg[3] == '.' || ('0' <= arg[3] && arg[3] <= '9')))) {
799
+ if (work_stack.size() < 1)
800
+ log_cmd_error("Must have at least one element on the stack for operator %%co.\n");
801
+ select_op_expand(design, work_stack, arg, 'o', false);
802
+ } else
803
+ if (arg == "%xe" || (arg.size() > 3 && arg.compare(0, 3, "%xe") == 0 && (arg[3] == ':' || arg[3] == '*' || arg[3] == '.' || ('0' <= arg[3] && arg[3] <= '9')))) {
804
+ if (work_stack.size() < 1)
805
+ log_cmd_error("Must have at least one element on the stack for operator %%xe.\n");
806
+ select_op_expand(design, work_stack, arg, 'x', true);
807
+ } else
808
+ if (arg == "%cie" || (arg.size() > 4 && arg.compare(0, 4, "%cie") == 0 && (arg[4] == ':' || arg[4] == '*' || arg[4] == '.' || ('0' <= arg[4] && arg[4] <= '9')))) {
809
+ if (work_stack.size() < 1)
810
+ log_cmd_error("Must have at least one element on the stack for operator %%cie.\n");
811
+ select_op_expand(design, work_stack, arg, 'i', true);
812
+ } else
813
+ if (arg == "%coe" || (arg.size() > 4 && arg.compare(0, 4, "%coe") == 0 && (arg[4] == ':' || arg[4] == '*' || arg[4] == '.' || ('0' <= arg[4] && arg[4] <= '9')))) {
814
+ if (work_stack.size() < 1)
815
+ log_cmd_error("Must have at least one element on the stack for operator %%coe.\n");
816
+ select_op_expand(design, work_stack, arg, 'o', true);
817
+ } else
818
+ log_cmd_error("Unknown selection operator '%s'.\n", arg);
819
+ if (work_stack.size() >= 1)
820
+ select_filter_active_mod(design, work_stack.back());
821
+ return;
822
+ }
823
+
824
+ if (arg[0] == '@') {
825
+ std::string set_name = RTLIL::escape_id(arg.substr(1));
826
+ IdString set_twine = design->twines().find(set_name);
827
+ if (set_twine != IdString::Null && design->selection_vars.count(set_twine) > 0)
828
+ work_stack.push_back(design->selection_vars[set_twine]);
829
+ else
830
+ log_cmd_error("Selection @%s is not defined!\n", RTLIL::unescape_id(set_name));
831
+ select_filter_active_mod(design, work_stack.back());
832
+ return;
833
+ }
834
+
835
+ bool select_blackboxes = false;
836
+ if (arg.substr(0, 1) == "=") {
837
+ arg = arg.substr(1);
838
+ select_blackboxes = true;
839
+ }
840
+
841
+ if (!design->selected_active_module.empty()) {
842
+ arg_mod = design->twines().str(design->selected_active_module);
843
+ arg_memb = arg;
844
+ if (!isprefixed(arg_memb))
845
+ arg_memb_found[arg_memb] = false;
846
+ } else
847
+ if (isprefixed(arg) && arg[0] >= 'a' && arg[0] <= 'z') {
848
+ arg_mod = "*", arg_memb = arg;
849
+ } else {
850
+ size_t pos = arg.find('/');
851
+ if (pos == std::string::npos) {
852
+ arg_mod = arg;
853
+ if (!isprefixed(arg_mod))
854
+ arg_mod_found[arg_mod] = false;
855
+ } else {
856
+ arg_mod = arg.substr(0, pos);
857
+ if (!isprefixed(arg_mod))
858
+ arg_mod_found[arg_mod] = false;
859
+ arg_memb = arg.substr(pos+1);
860
+ if (!isprefixed(arg_memb))
861
+ arg_memb_found[arg_memb] = false;
862
+ }
863
+ }
864
+
865
+ bool full_selection = (arg == "*" && arg_mod == "*");
866
+ work_stack.push_back(RTLIL::Selection(full_selection, select_blackboxes, design));
867
+ RTLIL::Selection &sel = work_stack.back();
868
+
869
+ if (sel.full_selection) {
870
+ if (sel.selects_boxes) sel.optimize(design);
871
+ select_filter_active_mod(design, work_stack.back());
872
+ return;
873
+ }
874
+
875
+ for (auto mod : design->modules())
876
+ {
877
+ if (!select_blackboxes && mod->get_blackbox_attribute())
878
+ continue;
879
+
880
+ if (arg_mod.compare(0, 2, "A:") == 0) {
881
+ if (!match_attr(design->twines(), mod->attributes, arg_mod.substr(2)))
882
+ continue;
883
+ } else
884
+ if (arg_mod.compare(0, 2, "N:") == 0) {
885
+ if (!match_ids(mod->name, arg_mod.substr(2)))
886
+ continue;
887
+ } else
888
+ if (!match_ids(mod->name, arg_mod))
889
+ continue;
890
+ else
891
+ arg_mod_found[arg_mod] = true;
892
+
893
+ if (arg_memb == "") {
894
+ sel.selected_modules.insert(mod->name);
895
+ continue;
896
+ }
897
+
898
+ if (arg_memb.compare(0, 2, "w:") == 0) {
899
+ for (auto wire : mod->wires())
900
+ if (match_ids(wire->name, arg_memb.substr(2)))
901
+ sel.selected_members[mod->name].insert(wire->name);
902
+ } else
903
+ if (arg_memb.compare(0, 2, "i:") == 0) {
904
+ for (auto wire : mod->wires())
905
+ if (wire->port_input && match_ids(wire->name, arg_memb.substr(2)))
906
+ sel.selected_members[mod->name].insert(wire->name);
907
+ } else
908
+ if (arg_memb.compare(0, 2, "o:") == 0) {
909
+ for (auto wire : mod->wires())
910
+ if (wire->port_output && match_ids(wire->name, arg_memb.substr(2)))
911
+ sel.selected_members[mod->name].insert(wire->name);
912
+ } else
913
+ if (arg_memb.compare(0, 2, "x:") == 0) {
914
+ for (auto wire : mod->wires())
915
+ if ((wire->port_input || wire->port_output) && match_ids(wire->name, arg_memb.substr(2)))
916
+ sel.selected_members[mod->name].insert(wire->name);
917
+ } else
918
+ if (arg_memb.compare(0, 2, "s:") == 0) {
919
+ size_t delim = arg_memb.substr(2).find(':');
920
+ if (delim == std::string::npos) {
921
+ int width = atoi(arg_memb.substr(2).c_str());
922
+ for (auto wire : mod->wires())
923
+ if (wire->width == width)
924
+ sel.selected_members[mod->name].insert(wire->name);
925
+ } else {
926
+ std::string min_str = arg_memb.substr(2, delim);
927
+ std::string max_str = arg_memb.substr(2+delim+1);
928
+ int min_width = min_str.empty() ? 0 : atoi(min_str.c_str());
929
+ int max_width = max_str.empty() ? -1 : atoi(max_str.c_str());
930
+ for (auto wire : mod->wires())
931
+ if (min_width <= wire->width && (wire->width <= max_width || max_width == -1))
932
+ sel.selected_members[mod->name].insert(wire->name);
933
+ }
934
+ } else
935
+ if (arg_memb.compare(0, 2, "m:") == 0) {
936
+ for (auto &it : mod->memories)
937
+ if (match_ids(design->twines().str(it.first), arg_memb.substr(2)))
938
+ sel.selected_members[mod->name].insert(it.first);
939
+ } else
940
+ if (arg_memb.compare(0, 2, "c:") == 0) {
941
+ for (auto cell : mod->cells())
942
+ if (match_ids(cell->name, arg_memb.substr(2)))
943
+ sel.selected_members[mod->name].insert(cell->name);
944
+ } else
945
+ if (arg_memb.compare(0, 2, "t:") == 0) {
946
+ if (arg_memb.compare(2, 1, "@") == 0) {
947
+ std::string set_name = RTLIL::escape_id(arg_memb.substr(3));
948
+ IdString set_twine = design->twines().find(set_name);
949
+ if (set_twine == IdString::Null || !design->selection_vars.count(set_twine))
950
+ log_cmd_error("Selection @%s is not defined!\n", RTLIL::unescape_id(set_name));
951
+
952
+ auto &muster = design->selection_vars[set_twine];
953
+ for (auto cell : mod->cells())
954
+ if (muster.selected_modules.count(cell->type))
955
+ sel.selected_members[mod->name].insert(cell->name);
956
+ } else {
957
+ for (auto cell : mod->cells())
958
+ if (match_ids(cell->type, arg_memb.substr(2)))
959
+ sel.selected_members[mod->name].insert(cell->name);
960
+ }
961
+ } else
962
+ if (arg_memb.compare(0, 2, "p:") == 0) {
963
+ for (auto &it : mod->processes)
964
+ if (match_ids(design->twines().str(it.first), arg_memb.substr(2)))
965
+ sel.selected_members[mod->name].insert(it.first);
966
+ } else
967
+ if (arg_memb.compare(0, 2, "a:") == 0) {
968
+ for (auto wire : mod->wires())
969
+ if (match_attr(design->twines(), wire->attributes, arg_memb.substr(2)))
970
+ sel.selected_members[mod->name].insert(wire->name);
971
+ for (auto &it : mod->memories)
972
+ if (match_attr(design->twines(), it.second->attributes, arg_memb.substr(2)))
973
+ sel.selected_members[mod->name].insert(it.first);
974
+ for (auto cell : mod->cells())
975
+ if (match_attr(design->twines(), cell->attributes, arg_memb.substr(2)))
976
+ sel.selected_members[mod->name].insert(cell->name);
977
+ for (auto &it : mod->processes)
978
+ if (match_attr(design->twines(), it.second->attributes, arg_memb.substr(2)))
979
+ sel.selected_members[mod->name].insert(it.first);
980
+ } else
981
+ if (arg_memb.compare(0, 2, "r:") == 0) {
982
+ for (auto cell : mod->cells())
983
+ if (match_attr(design->twines(), cell->parameters, arg_memb.substr(2)))
984
+ sel.selected_members[mod->name].insert(cell->name);
985
+ } else {
986
+ std::string orig_arg_memb = arg_memb;
987
+ if (arg_memb.compare(0, 2, "n:") == 0)
988
+ arg_memb = arg_memb.substr(2);
989
+ for (auto wire : mod->wires())
990
+ if (match_ids(wire->name, arg_memb)) {
991
+ sel.selected_members[mod->name].insert(wire->name);
992
+ arg_memb_found[orig_arg_memb] = true;
993
+ }
994
+ for (auto &it : mod->memories)
995
+ if (match_ids(design->twines().str(it.first), arg_memb)) {
996
+ sel.selected_members[mod->name].insert(it.first);
997
+ arg_memb_found[orig_arg_memb] = true;
998
+ }
999
+ for (auto cell : mod->cells())
1000
+ if (match_ids(cell->name, arg_memb)) {
1001
+ sel.selected_members[mod->name].insert(cell->name);
1002
+ arg_memb_found[orig_arg_memb] = true;
1003
+ }
1004
+ for (auto &it : mod->processes)
1005
+ if (match_ids(design->twines().str(it.first), arg_memb)) {
1006
+ sel.selected_members[mod->name].insert(it.first);
1007
+ arg_memb_found[orig_arg_memb] = true;
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ select_filter_active_mod(design, work_stack.back());
1013
+
1014
+ for (auto &it : arg_mod_found) {
1015
+ if (it.second == false && !disable_empty_warning) {
1016
+ std::string selection_str = select_blackboxes ? "=" : "";
1017
+ selection_str += it.first;
1018
+ log_warning("Selection \"%s\" did not match any module.\n", selection_str);
1019
+ }
1020
+ }
1021
+ for (auto &it : arg_memb_found) {
1022
+ if (it.second == false && !disable_empty_warning) {
1023
+ std::string selection_str = select_blackboxes ? "=" : "";
1024
+ selection_str += it.first;
1025
+ log_warning("Selection \"%s\" did not match any object.\n", selection_str);
1026
+ }
1027
+ }
1028
+ }
1029
+
1030
+ static std::string describe_selection_for_assert(RTLIL::Design *design, RTLIL::Selection *sel, bool whole_modules = false)
1031
+ {
1032
+ bool push_selection = &design->selection() != sel;
1033
+ if (push_selection) design->push_selection(*sel);
1034
+ std::string desc = "Selection contains:\n";
1035
+ for (auto mod : design->all_selected_modules())
1036
+ {
1037
+ if (whole_modules && sel->selected_whole_module(mod->name))
1038
+ desc += stringf("%s\n", mod);
1039
+ for (auto it : mod->selected_members())
1040
+ desc += stringf("%s/%s\n", mod, it.name.str());
1041
+ }
1042
+ if (push_selection) design->pop_selection();
1043
+ return desc;
1044
+ }
1045
+
1046
+ PRIVATE_NAMESPACE_END
1047
+ YOSYS_NAMESPACE_BEGIN
1048
+
1049
+ // used in kernel/register.cc and maybe other locations, extern decl. in register.h
1050
+ void handle_extra_select_args(Pass *pass, const vector<string> &args, size_t argidx, size_t args_size, RTLIL::Design *design)
1051
+ {
1052
+ std::vector<RTLIL::Selection> work_stack;
1053
+ for (; argidx < args_size; argidx++) {
1054
+ if (args[argidx].compare(0, 1, "-") == 0) {
1055
+ if (pass != nullptr)
1056
+ pass->cmd_error(args, argidx, "Unexpected option in selection arguments.");
1057
+ else
1058
+ log_cmd_error("Unexpected option in selection arguments.\n");
1059
+ }
1060
+ select_stmt(design, work_stack, args[argidx]);
1061
+ }
1062
+ select_op_union_all(design, work_stack);
1063
+ if (work_stack.empty())
1064
+ design->push_empty_selection();
1065
+ else
1066
+ design->push_selection(work_stack.back());
1067
+ }
1068
+
1069
+ // extern decl. in register.h
1070
+ RTLIL::Selection eval_select_args(const vector<string> &args, RTLIL::Design *design)
1071
+ {
1072
+ std::vector<RTLIL::Selection> work_stack;
1073
+ for (auto &arg : args)
1074
+ select_stmt(design, work_stack, arg);
1075
+ select_op_union_all(design, work_stack);
1076
+ if (work_stack.empty())
1077
+ return RTLIL::Selection::EmptySelection(design);
1078
+ return work_stack.back();
1079
+ }
1080
+
1081
+ // extern decl. in register.h
1082
+ void eval_select_op(vector<RTLIL::Selection> &work, const string &op, RTLIL::Design *design)
1083
+ {
1084
+ select_stmt(design, work, op);
1085
+ }
1086
+
1087
+ YOSYS_NAMESPACE_END
1088
+ PRIVATE_NAMESPACE_BEGIN
1089
+
1090
+ struct SelectPass : public Pass {
1091
+ SelectPass() : Pass("select", "modify and view the list of selected objects") { }
1092
+ bool formatted_help() override {
1093
+ auto *help = PrettyHelp::get_current();
1094
+ help->set_group("passes/status");
1095
+ return false;
1096
+ }
1097
+ void help() override
1098
+ {
1099
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1100
+ log("\n");
1101
+ log(" select [ -add | -del | -set <name> ] {-read <filename> | <selection>}\n");
1102
+ log(" select [ -unset <name> ]\n");
1103
+ log(" select [ <assert_option> ] {-read <filename> | <selection>}\n");
1104
+ log(" select [ -list | -list-mod | -write <filename> | -count | -clear ]\n");
1105
+ log(" select -module <modname>\n");
1106
+ log("\n");
1107
+ log("Most commands use the list of currently selected objects to determine which part\n");
1108
+ log("of the design to operate on. This command can be used to modify and view this\n");
1109
+ log("list of selected objects.\n");
1110
+ log("\n");
1111
+ log("Note that many commands support an optional [selection] argument that can be\n");
1112
+ log("used to override the global selection for the command. The syntax of this\n");
1113
+ log("optional argument is identical to the syntax of the <selection> argument\n");
1114
+ log("described here.\n");
1115
+ log("\n");
1116
+ log(" -add, -del\n");
1117
+ log(" add or remove the given objects to the current selection.\n");
1118
+ log(" without this options the current selection is replaced.\n");
1119
+ log("\n");
1120
+ log(" -set <name>\n");
1121
+ log(" do not modify the current selection. instead save the new selection\n");
1122
+ log(" under the given name (see @<name> below). to save the current selection,\n");
1123
+ log(" use \"select -set <name> %%\"\n");
1124
+ log("\n");
1125
+ log(" -unset <name>\n");
1126
+ log(" do not modify the current selection. instead remove a previously saved\n");
1127
+ log(" selection under the given name (see @<name> below).\n");
1128
+ log("\n");
1129
+ log(" -assert-none\n");
1130
+ log(" do not modify the current selection. instead assert that the given\n");
1131
+ log(" selection is empty. i.e. produce an error if any object or module\n");
1132
+ log(" matching the selection is found.\n");
1133
+ log("\n");
1134
+ log(" -assert-any\n");
1135
+ log(" do not modify the current selection. instead assert that the given\n");
1136
+ log(" selection is non-empty. i.e. produce an error if no object or module\n");
1137
+ log(" matching the selection is found.\n");
1138
+ log("\n");
1139
+ log(" -assert-mod-count N\n");
1140
+ log(" do not modify the current selection. instead assert that the given\n");
1141
+ log(" selection contains exactly N modules (partially or fully selected).\n");
1142
+ log("\n");
1143
+ log(" -assert-count N\n");
1144
+ log(" do not modify the current selection. instead assert that the given\n");
1145
+ log(" selection contains exactly N objects.\n");
1146
+ log("\n");
1147
+ log(" -assert-max N\n");
1148
+ log(" do not modify the current selection. instead assert that the given\n");
1149
+ log(" selection contains less than or exactly N objects.\n");
1150
+ log("\n");
1151
+ log(" -assert-min N\n");
1152
+ log(" do not modify the current selection. instead assert that the given\n");
1153
+ log(" selection contains at least N objects.\n");
1154
+ log("\n");
1155
+ log(" -list\n");
1156
+ log(" list all objects in the current selection\n");
1157
+ log("\n");
1158
+ log(" -write <filename>\n");
1159
+ log(" like -list but write the output to the specified file\n");
1160
+ log("\n");
1161
+ log(" -read <filename>\n");
1162
+ log(" read the specified file (written by -write)\n");
1163
+ log("\n");
1164
+ log(" -count\n");
1165
+ log(" count all objects in the current selection\n");
1166
+ log("\n");
1167
+ log(" -clear\n");
1168
+ log(" clear the current selection. this effectively selects the whole\n");
1169
+ log(" design. it also resets the selected module (see -module). use the\n");
1170
+ log(" command 'select *' to select everything but stay in the current module.\n");
1171
+ log("\n");
1172
+ log(" -none\n");
1173
+ log(" create an empty selection. the current module is unchanged.\n");
1174
+ log("\n");
1175
+ log(" -module <modname>\n");
1176
+ log(" limit the current scope to the specified module.\n");
1177
+ log(" the difference between this and simply selecting the module\n");
1178
+ log(" is that all object names are interpreted relative to this\n");
1179
+ log(" module after this command until the selection is cleared again.\n");
1180
+ log("\n");
1181
+ log("When this command is called without an argument, the current selection\n");
1182
+ log("is displayed in a compact form (i.e. only the module name when a whole module\n");
1183
+ log("is selected).\n");
1184
+ log("\n");
1185
+ log("The <selection> argument itself is a series of commands for a simple stack\n");
1186
+ log("machine. Each element on the stack represents a set of selected objects.\n");
1187
+ log("After this commands have been executed, the union of all remaining sets\n");
1188
+ log("on the stack is computed and used as selection for the command.\n");
1189
+ log("\n");
1190
+ log("Pushing (selecting) object when not in -module mode:\n");
1191
+ log("\n");
1192
+ log(" <mod_pattern>\n");
1193
+ log(" select the specified module(s)\n");
1194
+ log("\n");
1195
+ log(" <mod_pattern>/<obj_pattern>\n");
1196
+ log(" select the specified object(s) from the module(s)\n");
1197
+ log("\n");
1198
+ log("Pushing (selecting) object when in -module mode:\n");
1199
+ log("\n");
1200
+ log(" <obj_pattern>\n");
1201
+ log(" select the specified object(s) from the current module\n");
1202
+ log("\n");
1203
+ log("By default, patterns will not match black/white-box modules or their\n");
1204
+ log("contents. To include such objects, prefix the pattern with '='.\n");
1205
+ log("\n");
1206
+ log("A <mod_pattern> can be a module name, wildcard expression (*, ?, [..])\n");
1207
+ log("matching module names, or one of the following:\n");
1208
+ log("\n");
1209
+ log(" A:<pattern>, A:<pattern>=<pattern>\n");
1210
+ log(" all modules with an attribute matching the given pattern\n");
1211
+ log(" in addition to = also <, <=, >=, and > are supported\n");
1212
+ log("\n");
1213
+ log(" N:<pattern>\n");
1214
+ log(" all modules with a name matching the given pattern\n");
1215
+ log(" (i.e. 'N:' is optional as it is the default matching rule)\n");
1216
+ log("\n");
1217
+ log("An <obj_pattern> can be an object name, wildcard expression, or one of\n");
1218
+ log("the following:\n");
1219
+ log("\n");
1220
+ log(" w:<pattern>\n");
1221
+ log(" all wires with a name matching the given wildcard pattern\n");
1222
+ log("\n");
1223
+ log(" i:<pattern>, o:<pattern>, x:<pattern>\n");
1224
+ log(" all inputs (i:), outputs (o:) or any ports (x:) with matching names\n");
1225
+ log("\n");
1226
+ log(" s:<size>, s:<min>:<max>\n");
1227
+ log(" all wires with a matching width\n");
1228
+ log("\n");
1229
+ log(" m:<pattern>\n");
1230
+ log(" all memories with a name matching the given pattern\n");
1231
+ log("\n");
1232
+ log(" c:<pattern>\n");
1233
+ log(" all cells with a name matching the given pattern\n");
1234
+ log("\n");
1235
+ log(" t:<pattern>\n");
1236
+ log(" all cells with a type matching the given pattern\n");
1237
+ log("\n");
1238
+ log(" t:@<name>\n");
1239
+ log(" all cells with a type matching a module in the saved selection <name>\n");
1240
+ log("\n");
1241
+ log(" p:<pattern>\n");
1242
+ log(" all processes with a name matching the given pattern\n");
1243
+ log("\n");
1244
+ log(" a:<pattern>\n");
1245
+ log(" all objects with an attribute name matching the given pattern\n");
1246
+ log("\n");
1247
+ log(" a:<pattern>=<pattern>\n");
1248
+ log(" all objects with a matching attribute name-value-pair.\n");
1249
+ log(" in addition to = also <, <=, >=, and > are supported\n");
1250
+ log("\n");
1251
+ log(" r:<pattern>, r:<pattern>=<pattern>\n");
1252
+ log(" cells with matching parameters. also with <, <=, >= and >.\n");
1253
+ log("\n");
1254
+ log(" n:<pattern>\n");
1255
+ log(" all objects with a name matching the given pattern\n");
1256
+ log(" (i.e. 'n:' is optional as it is the default matching rule)\n");
1257
+ log("\n");
1258
+ log(" @<name>\n");
1259
+ log(" push the selection saved prior with 'select -set <name> ...'\n");
1260
+ log("\n");
1261
+ log("The following actions can be performed on the top sets on the stack:\n");
1262
+ log("\n");
1263
+ log(" %%\n");
1264
+ log(" push a copy of the current selection to the stack\n");
1265
+ log("\n");
1266
+ log(" %%%%\n");
1267
+ log(" replace the stack with a union of all elements on it\n");
1268
+ log("\n");
1269
+ log(" %%n\n");
1270
+ log(" replace top set with its invert\n");
1271
+ log("\n");
1272
+ log(" %%u\n");
1273
+ log(" replace the two top sets on the stack with their union\n");
1274
+ log("\n");
1275
+ log(" %%i\n");
1276
+ log(" replace the two top sets on the stack with their intersection\n");
1277
+ log("\n");
1278
+ log(" %%d\n");
1279
+ log(" pop the top set from the stack and subtract it from the new top\n");
1280
+ log("\n");
1281
+ log(" %%D\n");
1282
+ log(" like %%d but swap the roles of two top sets on the stack\n");
1283
+ log("\n");
1284
+ log(" %%c\n");
1285
+ log(" create a copy of the top set from the stack and push it\n");
1286
+ log("\n");
1287
+ log(" %%x[<num1>|*][.<num2>][:<rule>[:<rule>..]]\n");
1288
+ log(" expand top set <num1> num times according to the specified rules.\n");
1289
+ log(" (i.e. select all cells connected to selected wires and select all\n");
1290
+ log(" wires connected to selected cells) The rules specify which cell\n");
1291
+ log(" ports to use for this. the syntax for a rule is a '-' for exclusion\n");
1292
+ log(" and a '+' for inclusion, followed by an optional comma separated\n");
1293
+ log(" list of cell types followed by an optional comma separated list of\n");
1294
+ log(" cell ports in square brackets. a rule can also be just a cell or wire\n");
1295
+ log(" name that limits the expansion (is included but does not go beyond).\n");
1296
+ log(" select at most <num2> objects. a warning message is printed when this\n");
1297
+ log(" limit is reached. When '*' is used instead of <num1> then the process\n");
1298
+ log(" is repeated until no further object are selected.\n");
1299
+ log("\n");
1300
+ log(" %%ci[<num1>|*][.<num2>][:<rule>[:<rule>..]]\n");
1301
+ log(" %%co[<num1>|*][.<num2>][:<rule>[:<rule>..]]\n");
1302
+ log(" similar to %%x, but only select input (%%ci) or output cones (%%co)\n");
1303
+ log("\n");
1304
+ log(" %%xe[...] %%cie[...] %%coe\n");
1305
+ log(" like %%x, %%ci, and %%co but only consider combinatorial cells\n");
1306
+ log("\n");
1307
+ log(" %%a\n");
1308
+ log(" expand top set by selecting all wires that are (at least in part)\n");
1309
+ log(" aliases for selected wires.\n");
1310
+ log("\n");
1311
+ log(" %%s\n");
1312
+ log(" expand top set by adding all modules that implement cells in selected\n");
1313
+ log(" modules\n");
1314
+ log("\n");
1315
+ log(" %%m\n");
1316
+ log(" expand top set by selecting all modules that contain selected objects\n");
1317
+ log("\n");
1318
+ log(" %%M\n");
1319
+ log(" select modules that implement selected cells\n");
1320
+ log("\n");
1321
+ log(" %%C\n");
1322
+ log(" select cells that implement selected modules\n");
1323
+ log("\n");
1324
+ log(" %%R[<num>]\n");
1325
+ log(" select <num> random objects from top selection (default 1)\n");
1326
+ log("\n");
1327
+ log("Example: the following command selects all wires that are connected to a\n");
1328
+ log("'GATE' input of a 'SWITCH' cell:\n");
1329
+ log("\n");
1330
+ log(" select */t:SWITCH %%x:+[GATE] */t:SWITCH %%d\n");
1331
+ log("\n");
1332
+ }
1333
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
1334
+ {
1335
+ bool add_mode = false;
1336
+ bool del_mode = false;
1337
+ bool clear_mode = false;
1338
+ bool none_mode = false;
1339
+ bool list_mode = false;
1340
+ bool list_mod_mode = false;
1341
+ bool count_mode = false;
1342
+ bool got_module = false;
1343
+ bool assert_none = false;
1344
+ bool assert_any = false;
1345
+ int assert_modcount = -1;
1346
+ int assert_count = -1;
1347
+ int assert_max = -1;
1348
+ int assert_min = -1;
1349
+ std::string write_file, read_file;
1350
+ std::string set_name, unset_name, sel_str;
1351
+
1352
+ std::vector<RTLIL::Selection> work_stack;
1353
+
1354
+ size_t argidx;
1355
+ for (argidx = 1; argidx < args.size(); argidx++)
1356
+ {
1357
+ std::string arg = args[argidx];
1358
+ if (arg == "-add") {
1359
+ add_mode = true;
1360
+ continue;
1361
+ }
1362
+ if (arg == "-del") {
1363
+ del_mode = true;
1364
+ continue;
1365
+ }
1366
+ if (arg == "-assert-none") {
1367
+ assert_none = true;
1368
+ continue;
1369
+ }
1370
+ if (arg == "-assert-any") {
1371
+ assert_any = true;
1372
+ continue;
1373
+ }
1374
+ if (arg == "-assert-mod-count" && argidx+1 < args.size()) {
1375
+ assert_modcount = atoi(args[++argidx].c_str());
1376
+ continue;
1377
+ }
1378
+ if (arg == "-assert-count" && argidx+1 < args.size()) {
1379
+ assert_count = atoi(args[++argidx].c_str());
1380
+ continue;
1381
+ }
1382
+ if (arg == "-assert-max" && argidx+1 < args.size()) {
1383
+ assert_max = atoi(args[++argidx].c_str());
1384
+ continue;
1385
+ }
1386
+ if (arg == "-assert-min" && argidx+1 < args.size()) {
1387
+ assert_min = atoi(args[++argidx].c_str());
1388
+ continue;
1389
+ }
1390
+ if (arg == "-clear") {
1391
+ clear_mode = true;
1392
+ continue;
1393
+ }
1394
+ if (arg == "-none") {
1395
+ none_mode = true;
1396
+ continue;
1397
+ }
1398
+ if (arg == "-list") {
1399
+ list_mode = true;
1400
+ continue;
1401
+ }
1402
+ if (arg == "-list-mod") {
1403
+ list_mode = true;
1404
+ list_mod_mode = true;
1405
+ continue;
1406
+ }
1407
+ if (arg == "-write" && argidx+1 < args.size()) {
1408
+ write_file = args[++argidx];
1409
+ continue;
1410
+ }
1411
+ if (arg == "-read" && argidx+1 < args.size()) {
1412
+ read_file = args[++argidx];
1413
+ continue;
1414
+ }
1415
+ if (arg == "-count") {
1416
+ count_mode = true;
1417
+ continue;
1418
+ }
1419
+ if (arg == "-module" && argidx+1 < args.size()) {
1420
+ std::string mod_name = RTLIL::escape_id(args[++argidx]);
1421
+ IdString t = design->twines().find(mod_name);
1422
+ if (t == IdString::Null || design->module(t) == nullptr)
1423
+ log_cmd_error("No such module: %s\n", RTLIL::unescape_id(mod_name));
1424
+ design->selected_active_module = t;
1425
+ got_module = true;
1426
+ continue;
1427
+ }
1428
+ if (arg == "-set" && argidx+1 < args.size()) {
1429
+ set_name = RTLIL::escape_id(args[++argidx]);
1430
+ continue;
1431
+ }
1432
+ if (arg == "-unset" && argidx+1 < args.size()) {
1433
+ unset_name = RTLIL::escape_id(args[++argidx]);
1434
+ continue;
1435
+ }
1436
+ if (arg.size() > 0 && arg[0] == '-')
1437
+ log_cmd_error("Unknown option %s.\n", arg);
1438
+ bool disable_empty_warning = count_mode || assert_none || assert_any || (assert_modcount != -1) ||
1439
+ (assert_count != -1) || (assert_max != -1) || (assert_min != -1);
1440
+ select_stmt(design, work_stack, arg, disable_empty_warning);
1441
+ sel_str += " " + arg;
1442
+ }
1443
+
1444
+ if (!read_file.empty())
1445
+ {
1446
+ if (!sel_str.empty())
1447
+ log_cmd_error("Option -read can not be combined with a selection expression.\n");
1448
+
1449
+ std::ifstream f(read_file);
1450
+ yosys_input_files.insert(read_file);
1451
+ if (f.fail())
1452
+ log_error("Can't open '%s' for reading: %s\n", read_file, strerror(errno));
1453
+
1454
+ auto sel = RTLIL::Selection::EmptySelection(design);
1455
+ string line;
1456
+
1457
+ while (std::getline(f, line)) {
1458
+ size_t slash_pos = line.find('/');
1459
+ if (slash_pos == string::npos) {
1460
+ log_warning("Ignoring line without slash in 'select -read': %s\n", line);
1461
+ continue;
1462
+ }
1463
+ std::string mod_name = RTLIL::escape_id(line.substr(0, slash_pos));
1464
+ std::string obj_name = RTLIL::escape_id(line.substr(slash_pos+1));
1465
+ IdString mod_ref = design->twines().find(mod_name);
1466
+ IdString obj_ref = design->twines().find(obj_name);
1467
+ if (mod_ref == IdString::Null || obj_ref == IdString::Null)
1468
+ continue;
1469
+ sel.selected_members[mod_ref].insert(obj_ref);
1470
+ }
1471
+
1472
+ select_filter_active_mod(design, sel);
1473
+ sel.optimize(design);
1474
+ work_stack.push_back(sel);
1475
+ }
1476
+
1477
+ if (clear_mode && args.size() != 2)
1478
+ log_cmd_error("Option -clear can not be combined with any other options.\n");
1479
+
1480
+ if (none_mode && args.size() != 2)
1481
+ log_cmd_error("Option -none can not be combined with any other options.\n");
1482
+
1483
+ int common_flagset_tally = add_mode + del_mode + assert_none + assert_any + (assert_modcount >= 0) + (assert_count >= 0) + (assert_max >= 0) + (assert_min >= 0);
1484
+ const char *common_flagset = "-add, -del, -assert-none, -assert-any, -assert-mod-count, -assert-count, -assert-max, or -assert-min";
1485
+
1486
+ if (common_flagset_tally > 1)
1487
+ log_cmd_error("Options %s can not be combined.\n", common_flagset);
1488
+
1489
+ if ((list_mode || !write_file.empty() || count_mode) && common_flagset_tally)
1490
+ log_cmd_error("Options -list, -list-mod, -write and -count can not be combined with %s.\n", common_flagset);
1491
+
1492
+ if (!set_name.empty() && (list_mode || !write_file.empty() || count_mode || !unset_name.empty() || common_flagset_tally))
1493
+ log_cmd_error("Option -set can not be combined with -list, -write, -count, -unset, %s.\n", common_flagset);
1494
+
1495
+ if (!unset_name.empty() && (list_mode || !write_file.empty() || count_mode || !set_name.empty() || common_flagset_tally))
1496
+ log_cmd_error("Option -unset can not be combined with -list, -write, -count, -set, %s.\n", common_flagset);
1497
+
1498
+ if (work_stack.size() == 0 && got_module) {
1499
+ auto sel = RTLIL::Selection::FullSelection(design);
1500
+ select_filter_active_mod(design, sel);
1501
+ work_stack.push_back(sel);
1502
+ }
1503
+
1504
+ select_op_union_all(design, work_stack);
1505
+
1506
+ log_assert(!design->selection_stack.empty());
1507
+
1508
+ if (clear_mode) {
1509
+ design->selection() = RTLIL::Selection::FullSelection(design);
1510
+ design->selected_active_module.clear();
1511
+ return;
1512
+ }
1513
+
1514
+ if (none_mode) {
1515
+ design->selection() = RTLIL::Selection::EmptySelection(design);
1516
+ return;
1517
+ }
1518
+
1519
+ if (list_mode || count_mode || !write_file.empty())
1520
+ {
1521
+ #define LOG_OBJECT(...) { if (list_mode) log(__VA_ARGS__); if (f != nullptr) fprintf(f, __VA_ARGS__); total_count++; }
1522
+ int total_count = 0;
1523
+ FILE *f = nullptr;
1524
+ if (!write_file.empty()) {
1525
+ f = fopen(write_file.c_str(), "w");
1526
+ yosys_output_files.insert(write_file);
1527
+ if (f == nullptr)
1528
+ log_error("Can't open '%s' for writing: %s\n", write_file, strerror(errno));
1529
+ }
1530
+ if (work_stack.size() > 0)
1531
+ design->push_selection(work_stack.back());
1532
+ RTLIL::Selection *sel = &design->selection();
1533
+ sel->optimize(design);
1534
+ for (auto mod : design->all_selected_modules())
1535
+ {
1536
+ if (sel->selected_whole_module(mod->name) && list_mode)
1537
+ log("%s\n", mod);
1538
+ if (!list_mod_mode)
1539
+ for (auto it : mod->selected_members())
1540
+ LOG_OBJECT("%s/%s\n", mod->name.unescape().c_str(), it.name.unescape().c_str())
1541
+ }
1542
+ if (count_mode)
1543
+ {
1544
+ design->scratchpad_set_int("select.count", total_count);
1545
+ log("%d objects.\n", total_count);
1546
+ }
1547
+ if (f != nullptr)
1548
+ fclose(f);
1549
+ if (work_stack.size() > 0)
1550
+ design->pop_selection();
1551
+ #undef LOG_OBJECT
1552
+ return;
1553
+ }
1554
+
1555
+ if (add_mode)
1556
+ {
1557
+ if (work_stack.size() == 0)
1558
+ log_cmd_error("Nothing to add to selection.\n");
1559
+ select_op_union(design, design->selection(), work_stack.back());
1560
+ design->selection().optimize(design);
1561
+ return;
1562
+ }
1563
+
1564
+ if (del_mode)
1565
+ {
1566
+ if (work_stack.size() == 0)
1567
+ log_cmd_error("Nothing to delete from selection.\n");
1568
+ select_op_diff(design, design->selection(), work_stack.back());
1569
+ design->selection().optimize(design);
1570
+ return;
1571
+ }
1572
+
1573
+ if (assert_none)
1574
+ {
1575
+ if (work_stack.size() == 0)
1576
+ log_cmd_error("No selection to check.\n");
1577
+ work_stack.back().optimize(design);
1578
+ if (!work_stack.back().empty())
1579
+ {
1580
+ RTLIL::Selection *sel = &work_stack.back();
1581
+ sel->optimize(design);
1582
+ std::string desc = describe_selection_for_assert(design, sel, true);
1583
+ log_error("Assertion failed: selection is not empty:%s\n%s", sel_str, desc);
1584
+ }
1585
+ return;
1586
+ }
1587
+
1588
+ if (assert_any)
1589
+ {
1590
+ if (work_stack.size() == 0)
1591
+ log_cmd_error("No selection to check.\n");
1592
+ work_stack.back().optimize(design);
1593
+ if (work_stack.back().empty())
1594
+ {
1595
+ RTLIL::Selection *sel = &work_stack.back();
1596
+ sel->optimize(design);
1597
+ std::string desc = describe_selection_for_assert(design, sel, true);
1598
+ log_error("Assertion failed: selection is empty:%s\n%s", sel_str, desc);
1599
+ }
1600
+ return;
1601
+ }
1602
+
1603
+ if (assert_modcount >= 0 || assert_count >= 0 || assert_max >= 0 || assert_min >= 0)
1604
+ {
1605
+ int module_count = 0, total_count = 0;
1606
+ if (work_stack.size() == 0)
1607
+ log_cmd_error("No selection to check.\n");
1608
+ RTLIL::Selection *sel = &work_stack.back();
1609
+ design->push_selection(*sel);
1610
+ sel->optimize(design);
1611
+ for (auto mod : design->all_selected_modules()) {
1612
+ module_count++;
1613
+ for ([[maybe_unused]] auto member_name : mod->selected_members())
1614
+ total_count++;
1615
+ }
1616
+ if (assert_modcount >= 0 && assert_modcount != module_count)
1617
+ {
1618
+ log_error("Assertion failed: selection contains %d modules instead of the asserted %d:%s\n",
1619
+ module_count, assert_modcount, sel_str);
1620
+ }
1621
+ if (assert_count >= 0 && assert_count != total_count)
1622
+ {
1623
+ std::string desc = describe_selection_for_assert(design, sel);
1624
+ log_error("Assertion failed: selection contains %d elements instead of the asserted %d:%s\n%s",
1625
+ total_count, assert_count, sel_str, desc);
1626
+ }
1627
+ if (assert_max >= 0 && assert_max < total_count)
1628
+ {
1629
+ std::string desc = describe_selection_for_assert(design, sel);
1630
+ log_error("Assertion failed: selection contains %d elements, more than the maximum number %d:%s\n%s",
1631
+ total_count, assert_max, sel_str, desc);
1632
+ }
1633
+ if (assert_min >= 0 && assert_min > total_count)
1634
+ {
1635
+ std::string desc = describe_selection_for_assert(design, sel);
1636
+ log_error("Assertion failed: selection contains %d elements, less than the minimum number %d:%s\n%s",
1637
+ total_count, assert_min, sel_str, desc);
1638
+ }
1639
+ design->pop_selection();
1640
+ return;
1641
+ }
1642
+
1643
+ if (!set_name.empty())
1644
+ {
1645
+ IdString set_twine = design->twines().add(set_name);
1646
+ if (work_stack.size() == 0)
1647
+ design->selection_vars[set_twine] = RTLIL::Selection::EmptySelection(design);
1648
+ else
1649
+ design->selection_vars[set_twine] = work_stack.back();
1650
+ return;
1651
+ }
1652
+
1653
+ if (!unset_name.empty())
1654
+ {
1655
+ IdString unset_twine = design->twines().find(unset_name);
1656
+ if (unset_twine == IdString::Null || !design->selection_vars.erase(unset_twine))
1657
+ log_error("Selection '%s' does not exist!\n", unset_name);
1658
+ return;
1659
+ }
1660
+
1661
+ if (work_stack.size() == 0) {
1662
+ RTLIL::Selection &sel = design->selection();
1663
+ if (sel.full_selection)
1664
+ log("*\n");
1665
+ for (auto &it : sel.selected_modules)
1666
+ log("%s\n", PooledName(design, it).unescape());
1667
+ for (auto &it : sel.selected_members)
1668
+ for (auto &it2 : it.second)
1669
+ log("%s/%s\n", PooledName(design, it.first).unescape(), PooledName(design, it2).unescape());
1670
+ return;
1671
+ }
1672
+
1673
+ design->selection() = work_stack.back();
1674
+ design->selection().optimize(design);
1675
+ }
1676
+ } SelectPass;
1677
+
1678
+ struct CdPass : public Pass {
1679
+ CdPass() : Pass("cd", "a shortcut for 'select -module <name>'") { }
1680
+ bool formatted_help() override {
1681
+ auto *help = PrettyHelp::get_current();
1682
+ help->set_group("passes/status");
1683
+ return false;
1684
+ }
1685
+ void help() override
1686
+ {
1687
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1688
+ log("\n");
1689
+ log(" cd <modname>\n");
1690
+ log("\n");
1691
+ log("This is just a shortcut for 'select -module <modname>'.\n");
1692
+ log("\n");
1693
+ log("\n");
1694
+ log(" cd <cellname>\n");
1695
+ log("\n");
1696
+ log("When no module with the specified name is found, but there is a cell\n");
1697
+ log("with the specified name in the current module, then this is equivalent\n");
1698
+ log("to 'cd <celltype>'.\n");
1699
+ log("\n");
1700
+ log("\n");
1701
+ log(" cd ..\n");
1702
+ log("\n");
1703
+ log("Remove trailing substrings that start with '.' in current module name until\n");
1704
+ log("the name of a module in the current design is generated, then switch to that\n");
1705
+ log("module. Otherwise clear the current selection.\n");
1706
+ log("\n");
1707
+ log("\n");
1708
+ log(" cd\n");
1709
+ log("\n");
1710
+ log("This is just a shortcut for 'select -clear'.\n");
1711
+ log("\n");
1712
+ }
1713
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
1714
+ {
1715
+ if (args.size() != 1 && args.size() != 2)
1716
+ log_cmd_error("Invalid number of arguments.\n");
1717
+
1718
+ if (args.size() == 1 || args[1] == "/") {
1719
+ design->pop_selection();
1720
+ design->push_full_selection();
1721
+ design->selected_active_module.clear();
1722
+ return;
1723
+ }
1724
+
1725
+ if (args[1] == "..")
1726
+ {
1727
+ string modname = design->twines().str(design->selected_active_module);
1728
+
1729
+ design->pop_selection();
1730
+ design->push_full_selection();
1731
+ design->selected_active_module.clear();
1732
+
1733
+ while (1)
1734
+ {
1735
+ size_t pos = modname.rfind('.');
1736
+
1737
+ if (pos == string::npos)
1738
+ break;
1739
+
1740
+ modname = modname.substr(0, pos);
1741
+ IdString mod_ref = design->twines().find(modname);
1742
+ Module *mod = design->module(mod_ref);
1743
+
1744
+ if (mod == nullptr)
1745
+ continue;
1746
+
1747
+ design->selected_active_module = mod_ref;
1748
+ design->pop_selection();
1749
+ design->push_full_selection();
1750
+ select_filter_active_mod(design, design->selection());
1751
+ design->selection().optimize(design);
1752
+ return;
1753
+ }
1754
+
1755
+ return;
1756
+ }
1757
+
1758
+ IdString modname = design->twines().find(RTLIL::escape_id(args[1]));
1759
+
1760
+ if (design->module(modname) == nullptr && !design->selected_active_module.empty()) {
1761
+ RTLIL::Module *module = design->module(design->selected_active_module);
1762
+ IdString cell_ref = modname;
1763
+ if (module != nullptr && cell_ref != IdString::Null && module->cell(cell_ref) != nullptr)
1764
+ modname = module->cell(cell_ref)->type;
1765
+ }
1766
+
1767
+ if (design->module(modname) != nullptr) {
1768
+ design->selected_active_module = modname;
1769
+ design->pop_selection();
1770
+ design->push_full_selection();
1771
+ select_filter_active_mod(design, design->selection());
1772
+ design->selection().optimize(design);
1773
+ return;
1774
+ }
1775
+
1776
+ log_cmd_error("No such module `%s' found!\n", PooledName(design, modname).unescape());
1777
+ }
1778
+ } CdPass;
1779
+
1780
+ template<typename T>
1781
+ static void log_matches(const char *title, Module *module, const T &list)
1782
+ {
1783
+ std::vector<IdString> matches;
1784
+
1785
+ for (auto &it : list)
1786
+ if (module->selected(it.second))
1787
+ matches.push_back(it.first);
1788
+
1789
+ if (!matches.empty()) {
1790
+ log("\n");
1791
+ log("%d %s:\n", int(matches.size()), title);
1792
+ auto &twines = module->twines();
1793
+ std::sort(matches.begin(), matches.end(), [&](IdString a, IdString b) {
1794
+ return twines.str(a) < twines.str(b);
1795
+ });
1796
+ for (auto ref : matches)
1797
+ log(" %s\n", twines.unescaped_str(ref));
1798
+ }
1799
+ }
1800
+
1801
+ struct LsPass : public Pass {
1802
+ LsPass() : Pass("ls", "list modules or objects in modules") { }
1803
+ bool formatted_help() override {
1804
+ auto *help = PrettyHelp::get_current();
1805
+ help->set_group("passes/status");
1806
+ return false;
1807
+ }
1808
+ void help() override
1809
+ {
1810
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1811
+ log("\n");
1812
+ log(" ls [selection]\n");
1813
+ log("\n");
1814
+ log("When no active module is selected, this prints a list of modules.\n");
1815
+ log("\n");
1816
+ log("When an active module is selected, this prints a list of objects in the module.\n");
1817
+ log("\n");
1818
+ }
1819
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
1820
+ {
1821
+ size_t argidx = 1;
1822
+ extra_args(args, argidx, design);
1823
+
1824
+ if (design->selected_active_module.empty())
1825
+ {
1826
+ std::vector<IdString> matches;
1827
+
1828
+ for (auto mod : design->all_selected_modules())
1829
+ matches.push_back(mod->name);
1830
+
1831
+ if (!matches.empty()) {
1832
+ log("\n");
1833
+ log("%d %s:\n", int(matches.size()), "modules");
1834
+ std::sort(matches.begin(), matches.end(), RTLIL::sort_by_id_str(design->twines()));
1835
+ for (auto id : matches)
1836
+ log(" %s%s\n", PooledName(design, id).unescape(), design->selected_whole_module(design->module(id)) ? "" : "*");
1837
+ }
1838
+ }
1839
+ else
1840
+ if (design->module(design->selected_active_module) != nullptr)
1841
+ {
1842
+ RTLIL::Module *module = design->module(design->selected_active_module);
1843
+ log_matches("wires", module, module->wires_);
1844
+ log_matches("memories", module, module->memories);
1845
+ log_matches("cells", module, module->cells_);
1846
+ log_matches("processes", module, module->processes);
1847
+ }
1848
+ }
1849
+ } LsPass;
1850
+
1851
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/setattr.cc ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/rtlil.h"
22
+ #include "kernel/log.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct setunset_t
28
+ {
29
+ std::string name;
30
+ RTLIL::Const value;
31
+ bool unset;
32
+
33
+ setunset_t(std::string unset_name) : name(RTLIL::escape_id(unset_name)), value(), unset(true) { }
34
+
35
+ setunset_t(std::string set_name, std::string set_value) : name(RTLIL::escape_id(set_name)), value(), unset(false)
36
+ {
37
+ if (set_value.compare(0, 1, "\"") == 0 && set_value.compare(GetSize(set_value)-1, std::string::npos, "\"") == 0) {
38
+ value = RTLIL::Const(set_value.substr(1, GetSize(set_value)-2));
39
+ } else {
40
+ RTLIL::SigSpec sig_value;
41
+ if (!RTLIL::SigSpec::parse(sig_value, nullptr, set_value))
42
+ log_cmd_error("Can't decode value '%s'!\n", set_value);
43
+ value = sig_value.as_const();
44
+ value.tag_bare_integer_const(set_value);
45
+ }
46
+ }
47
+ };
48
+
49
+ static void do_setunset(RTLIL::Design *design, dict<IdString, RTLIL::Const> &attrs, const std::vector<setunset_t> &list)
50
+ {
51
+ for (auto &item : list)
52
+ if (item.unset) {
53
+ IdString name = design->twines().find(item.name);
54
+ if (name != IdString::Null)
55
+ attrs.erase(name);
56
+ } else
57
+ attrs[design->twines().add(item.name)] = item.value;
58
+ }
59
+
60
+ struct SetattrPass : public Pass {
61
+ SetattrPass() : Pass("setattr", "set/unset attributes on objects") { }
62
+ void help() override
63
+ {
64
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
65
+ log("\n");
66
+ log(" setattr [ -mod ] [ -set name value | -unset name ]... [selection]\n");
67
+ log("\n");
68
+ log("Set/unset the given attributes on the selected objects. String values must be\n");
69
+ log("passed in double quotes (\").\n");
70
+ log("\n");
71
+ log("When called with -mod, this command will set and unset attributes on modules\n");
72
+ log("instead of objects within modules.\n");
73
+ log("\n");
74
+ }
75
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
76
+ {
77
+ std::vector<setunset_t> setunset_list;
78
+ bool flag_mod = false;
79
+
80
+ size_t argidx;
81
+ for (argidx = 1; argidx < args.size(); argidx++)
82
+ {
83
+ std::string arg = args[argidx];
84
+ if (arg == "-set" && argidx+2 < args.size()) {
85
+ string set_key = args[++argidx];
86
+ string set_val = args[++argidx];
87
+ setunset_list.push_back(setunset_t(set_key, set_val));
88
+ continue;
89
+ }
90
+ if (arg == "-unset" && argidx+1 < args.size()) {
91
+ setunset_list.push_back(setunset_t(args[++argidx]));
92
+ continue;
93
+ }
94
+ if (arg == "-mod") {
95
+ flag_mod = true;
96
+ continue;
97
+ }
98
+ break;
99
+ }
100
+ extra_args(args, argidx, design);
101
+
102
+ for (auto module : design->all_selected_modules())
103
+ {
104
+ if (flag_mod) {
105
+ if (module->is_selected_whole())
106
+ do_setunset(design, module->attributes, setunset_list);
107
+ continue;
108
+ }
109
+
110
+ for (auto memb : module->selected_members())
111
+ do_setunset(design, memb.obj->attributes, setunset_list);
112
+ }
113
+ }
114
+ } SetattrPass;
115
+
116
+ struct WbflipPass : public Pass {
117
+ WbflipPass() : Pass("wbflip", "flip the whitebox attribute") { }
118
+ void help() override
119
+ {
120
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
121
+ log("\n");
122
+ log(" wbflip [selection]\n");
123
+ log("\n");
124
+ log("Flip the whitebox attribute on selected cells. I.e. if it's set, unset it, and\n");
125
+ log("vice-versa. Blackbox cells are not effected by this command.\n");
126
+ log("\n");
127
+ }
128
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
129
+ {
130
+ size_t argidx;
131
+ for (argidx = 1; argidx < args.size(); argidx++)
132
+ {
133
+ std::string arg = args[argidx];
134
+ // if (arg == "-mod") {
135
+ // flag_mod = true;
136
+ // continue;
137
+ // }
138
+ break;
139
+ }
140
+ extra_args(args, argidx, design);
141
+
142
+ for (auto *module : design->selected_modules(RTLIL::SELECT_ALL, RTLIL::SB_EXCL_BB_ONLY))
143
+ module->set_bool_attribute(ID::whitebox, !module->get_bool_attribute(ID::whitebox));
144
+ }
145
+ } WbflipPass;
146
+
147
+ struct SetparamPass : public Pass {
148
+ SetparamPass() : Pass("setparam", "set/unset parameters on objects") { }
149
+ void help() override
150
+ {
151
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
152
+ log("\n");
153
+ log(" setparam [ -type cell_type ] [ -set name value | -unset name ]... [selection]\n");
154
+ log("\n");
155
+ log("Set/unset the given parameters on the selected cells. String values must be\n");
156
+ log("passed in double quotes (\").\n");
157
+ log("\n");
158
+ log("The -type option can be used to change the cell type of the selected cells.\n");
159
+ log("\n");
160
+ }
161
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
162
+ {
163
+ vector<setunset_t> setunset_list;
164
+ string new_cell_type;
165
+
166
+ size_t argidx;
167
+ for (argidx = 1; argidx < args.size(); argidx++)
168
+ {
169
+ std::string arg = args[argidx];
170
+ if (arg == "-set" && argidx+2 < args.size()) {
171
+ string set_key = args[++argidx];
172
+ string set_val = args[++argidx];
173
+ setunset_list.push_back(setunset_t(set_key, set_val));
174
+ continue;
175
+ }
176
+ if (arg == "-unset" && argidx+1 < args.size()) {
177
+ setunset_list.push_back(setunset_t(args[++argidx]));
178
+ continue;
179
+ }
180
+ if (arg == "-type" && argidx+1 < args.size()) {
181
+ new_cell_type = RTLIL::escape_id(args[++argidx]);
182
+ continue;
183
+ }
184
+ break;
185
+ }
186
+ extra_args(args, argidx, design);
187
+
188
+ for (auto module : design->selected_modules())
189
+ {
190
+ for (auto cell : module->selected_cells()) {
191
+ if (!new_cell_type.empty())
192
+ cell->type = cell->twines().add(new_cell_type);
193
+ do_setunset(design, cell->parameters, setunset_list);
194
+ }
195
+ }
196
+ }
197
+ } SetparamPass;
198
+
199
+ struct ChparamPass : public Pass {
200
+ ChparamPass() : Pass("chparam", "re-evaluate modules with new parameters") { }
201
+ void help() override
202
+ {
203
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
204
+ log("\n");
205
+ log(" chparam [ -set name value ]... [selection]\n");
206
+ log("\n");
207
+ log("Re-evaluate the selected modules with new parameters. String values must be\n");
208
+ log("passed in double quotes (\").\n");
209
+ log("\n");
210
+ log("\n");
211
+ log(" chparam -list [selection]\n");
212
+ log("\n");
213
+ log("List the available parameters of the selected modules.\n");
214
+ log("\n");
215
+ }
216
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
217
+ {
218
+ std::vector<setunset_t> setunset_list;
219
+ dict<RTLIL::IdString, RTLIL::Const> new_parameters;
220
+ bool list_mode = false;
221
+
222
+ size_t argidx;
223
+ for (argidx = 1; argidx < args.size(); argidx++)
224
+ {
225
+ std::string arg = args[argidx];
226
+ if (arg == "-set" && argidx+2 < args.size()) {
227
+ string set_key = args[++argidx];
228
+ string set_val = args[++argidx];
229
+ setunset_list.push_back(setunset_t(set_key, set_val));
230
+ continue;
231
+ }
232
+ if (arg == "-list") {
233
+ list_mode = true;
234
+ continue;
235
+ }
236
+ break;
237
+ }
238
+
239
+ for (int i = argidx; i < GetSize(args); i++)
240
+ if (design->module("$abstract\\" + args[i]) != nullptr &&
241
+ design->module(RTLIL::escape_id(args[i])) == nullptr)
242
+ args[i] = "$abstract\\" + args[i];
243
+
244
+ extra_args(args, argidx, design);
245
+
246
+ do_setunset(design, new_parameters, setunset_list);
247
+
248
+ if (list_mode) {
249
+ if (!new_parameters.empty())
250
+ log_cmd_error("The options -set and -list cannot be used together.\n");
251
+ for (auto module : design->selected_modules()) {
252
+ log("%s:\n", module);
253
+ for (auto param : module->avail_parameters)
254
+ log(" %s\n", PooledName(design, param).unescape());
255
+ }
256
+ return;
257
+ }
258
+
259
+ pool<IdString> modnames, old_modnames;
260
+ for (auto module : design->selected_whole_modules_warn()) {
261
+ modnames.insert(module->name);
262
+ old_modnames.insert(module->name);
263
+ }
264
+ modnames.sort();
265
+
266
+ for (auto modname : modnames) {
267
+ Module *module = design->module(modname);
268
+ Module *new_module = design->module(module->derive(design, new_parameters));
269
+ if (module != new_module) {
270
+ Module *m = new_module->clone();
271
+ m->name = module->name;
272
+ design->remove(module);
273
+ design->add(m);
274
+ }
275
+ if (old_modnames.count(new_module->name) == 0)
276
+ design->remove(new_module);
277
+ }
278
+ }
279
+ } ChparamPass;
280
+
281
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/setenv.cc ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2024 N. Engelhardt <nak@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/yosys.h"
21
+ #include "kernel/log_help.h"
22
+
23
+ USING_YOSYS_NAMESPACE
24
+ PRIVATE_NAMESPACE_BEGIN
25
+ struct SetenvPass : public Pass {
26
+ SetenvPass() : Pass("setenv", "set an environment variable") { }
27
+ bool formatted_help() override {
28
+ auto *help = PrettyHelp::get_current();
29
+ help->set_group("passes/status");
30
+ return false;
31
+ }
32
+ void help() override
33
+ {
34
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
35
+ log("\n");
36
+ log(" setenv name value\n");
37
+ log("\n");
38
+ log("Set the given environment variable on the current process. Values containing\n");
39
+ log("whitespace must be passed in double quotes (\").\n");
40
+ log("\n");
41
+ }
42
+ void execute(std::vector<std::string> args, [[maybe_unused]] RTLIL::Design *design) override
43
+ {
44
+ if(args.size() != 3)
45
+ log_cmd_error("Wrong number of arguments given.\n");
46
+
47
+ std::string name = args[1];
48
+ std::string value = args[2];
49
+ if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2);
50
+
51
+ #if defined(_WIN32)
52
+ _putenv_s(name.c_str(), value.c_str());
53
+ #else
54
+ if (setenv(name.c_str(), value.c_str(), 1))
55
+ log_cmd_error("Invalid name \"%s\".\n", name);
56
+ #endif
57
+
58
+ }
59
+ } SetenvPass;
60
+
61
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/setundef.cc ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/register.h"
21
+ #include "kernel/celltypes.h"
22
+ #include "kernel/sigtools.h"
23
+ #include "kernel/mem.h"
24
+ #include "kernel/rtlil.h"
25
+ #include "kernel/log.h"
26
+
27
+ #define MODE_ZERO 0
28
+ #define MODE_ONE 1
29
+ #define MODE_UNDEF 2
30
+ #define MODE_RANDOM 3
31
+ #define MODE_ANYSEQ 4
32
+ #define MODE_ANYCONST 5
33
+
34
+ USING_YOSYS_NAMESPACE
35
+ PRIVATE_NAMESPACE_BEGIN
36
+
37
+ static RTLIL::Wire * add_wire(RTLIL::Module *module, std::string name, int width, bool flag_input, bool flag_output)
38
+ {
39
+ RTLIL::Wire *wire = NULL;
40
+ name = RTLIL::escape_id(name);
41
+
42
+ IdString t = module->twines().add(name);
43
+
44
+ if (module->count_id(t) != 0)
45
+ {
46
+ log("Module %s already has such an object %s.\n", module->name, name);
47
+ name += "$";
48
+ return add_wire(module, name, width, flag_input, flag_output);
49
+ }
50
+ else
51
+ {
52
+ wire = module->addWire(name, width);
53
+ wire->port_input = flag_input;
54
+ wire->port_output = flag_output;
55
+
56
+ if (flag_input || flag_output) {
57
+ wire->port_id = module->wires_.size();
58
+ module->fixup_ports();
59
+ }
60
+
61
+ log("Added wire %s to module %s.\n", name, module->name);
62
+ }
63
+
64
+ return wire;
65
+ }
66
+
67
+ struct SetundefWorker
68
+ {
69
+ int next_bit_mode;
70
+ uint32_t next_bit_state;
71
+ vector<SigSpec*> siglist;
72
+
73
+ RTLIL::State next_bit()
74
+ {
75
+ if (next_bit_mode == MODE_ZERO)
76
+ return RTLIL::State::S0;
77
+
78
+ if (next_bit_mode == MODE_ONE)
79
+ return RTLIL::State::S1;
80
+
81
+ if (next_bit_mode == MODE_UNDEF)
82
+ return RTLIL::State::Sx;
83
+
84
+ if (next_bit_mode == MODE_RANDOM)
85
+ {
86
+ // xorshift32
87
+ next_bit_state ^= next_bit_state << 13;
88
+ next_bit_state ^= next_bit_state >> 17;
89
+ next_bit_state ^= next_bit_state << 5;
90
+ log_assert(next_bit_state != 0);
91
+
92
+ return ((next_bit_state >> (next_bit_state & 15)) & 16) ? RTLIL::State::S0 : RTLIL::State::S1;
93
+ }
94
+
95
+ log_abort();
96
+ }
97
+
98
+ void operator()(RTLIL::SigSpec &sig)
99
+ {
100
+ if (next_bit_mode == MODE_ANYSEQ || next_bit_mode == MODE_ANYCONST) {
101
+ siglist.push_back(&sig);
102
+ return;
103
+ }
104
+
105
+ for (auto &bit : sig)
106
+ if (bit.wire == NULL && bit.data > RTLIL::State::S1)
107
+ bit = next_bit();
108
+ }
109
+ };
110
+
111
+ struct SetundefPass : public Pass {
112
+ SetundefPass() : Pass("setundef", "replace undef values with defined constants") { }
113
+ void help() override
114
+ {
115
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
116
+ log("\n");
117
+ log(" setundef [options] [selection]\n");
118
+ log("\n");
119
+ log("This command replaces undef (x) constants with defined (0/1) constants.\n");
120
+ log("\n");
121
+ log(" -undriven\n");
122
+ log(" also set undriven nets to constant values\n");
123
+ log("\n");
124
+ log(" -expose\n");
125
+ log(" also expose undriven nets as inputs (use with -undriven)\n");
126
+ log("\n");
127
+ log(" -zero\n");
128
+ log(" replace with bits cleared (0)\n");
129
+ log("\n");
130
+ log(" -one\n");
131
+ log(" replace with bits set (1)\n");
132
+ log("\n");
133
+ log(" -undef\n");
134
+ log(" replace with undef (x) bits, may be used with -undriven\n");
135
+ log("\n");
136
+ log(" -anyseq\n");
137
+ log(" replace with $anyseq drivers (for formal)\n");
138
+ log("\n");
139
+ log(" -anyconst\n");
140
+ log(" replace with $anyconst drivers (for formal)\n");
141
+ log("\n");
142
+ log(" -random <seed>\n");
143
+ log(" replace with random bits using the specified integer as seed\n");
144
+ log(" value for the random number generator.\n");
145
+ log("\n");
146
+ log(" -init\n");
147
+ log(" also create/update init values for flip-flops\n");
148
+ log("\n");
149
+ log(" -params\n");
150
+ log(" replace undef in cell parameters\n");
151
+ log("\n");
152
+ }
153
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
154
+ {
155
+ int got_value = 0;
156
+ bool undriven_mode = false;
157
+ bool expose_mode = false;
158
+ bool init_mode = false;
159
+ bool params_mode = false;
160
+ SetundefWorker worker;
161
+
162
+ log_header(design, "Executing SETUNDEF pass (replace undef values with defined constants).\n");
163
+
164
+ size_t argidx;
165
+ for (argidx = 1; argidx < args.size(); argidx++)
166
+ {
167
+ if (args[argidx] == "-undriven") {
168
+ undriven_mode = true;
169
+ continue;
170
+ }
171
+ if (args[argidx] == "-expose") {
172
+ expose_mode = true;
173
+ continue;
174
+ }
175
+ if (args[argidx] == "-zero") {
176
+ got_value++;
177
+ worker.next_bit_mode = MODE_ZERO;
178
+ worker.next_bit_state = 0;
179
+ continue;
180
+ }
181
+ if (args[argidx] == "-one") {
182
+ got_value++;
183
+ worker.next_bit_mode = MODE_ONE;
184
+ worker.next_bit_state = 0;
185
+ continue;
186
+ }
187
+ if (args[argidx] == "-anyseq") {
188
+ got_value++;
189
+ worker.next_bit_mode = MODE_ANYSEQ;
190
+ worker.next_bit_state = 0;
191
+ continue;
192
+ }
193
+ if (args[argidx] == "-anyconst") {
194
+ got_value++;
195
+ worker.next_bit_mode = MODE_ANYCONST;
196
+ worker.next_bit_state = 0;
197
+ continue;
198
+ }
199
+ if (args[argidx] == "-undef") {
200
+ got_value++;
201
+ worker.next_bit_mode = MODE_UNDEF;
202
+ worker.next_bit_state = 0;
203
+ continue;
204
+ }
205
+ if (args[argidx] == "-init") {
206
+ init_mode = true;
207
+ continue;
208
+ }
209
+ if (args[argidx] == "-params") {
210
+ params_mode = true;
211
+ continue;
212
+ }
213
+ if (args[argidx] == "-random" && argidx+1 < args.size()) {
214
+ got_value++;
215
+ worker.next_bit_mode = MODE_RANDOM;
216
+ worker.next_bit_state = atoi(args[++argidx].c_str()) + 1;
217
+ for (int i = 0; i < 10; i++)
218
+ worker.next_bit();
219
+ continue;
220
+ }
221
+ break;
222
+ }
223
+ extra_args(args, argidx, design);
224
+
225
+ if (!got_value && expose_mode) {
226
+ log("Using default as -undef with -expose.\n");
227
+ got_value++;
228
+ worker.next_bit_mode = MODE_UNDEF;
229
+ worker.next_bit_state = 0;
230
+ }
231
+
232
+ if (expose_mode && !undriven_mode)
233
+ log_cmd_error("Option -expose must be used with option -undriven.\n");
234
+ if (!got_value)
235
+ log_cmd_error("One of the options -zero, -one, -anyseq, -anyconst, -random <seed>, or -expose must be specified.\n");
236
+ else if (got_value > 1)
237
+ log_cmd_error("Only one of the options -zero, -one, -anyseq, -anyconst, or -random <seed> can be specified.\n");
238
+
239
+ if (init_mode && (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST))
240
+ log_cmd_error("The options -init and -anyseq / -anyconst are exclusive.\n");
241
+
242
+ for (auto module : design->selected_modules())
243
+ {
244
+ if (params_mode)
245
+ {
246
+ for (auto *cell : module->selected_cells()) {
247
+ for (auto &parameter : cell->parameters) {
248
+ for (auto bit : parameter.second) {
249
+ if (bit > RTLIL::State::S1)
250
+ bit = worker.next_bit();
251
+ }
252
+ }
253
+ }
254
+ }
255
+
256
+ if (undriven_mode)
257
+ {
258
+ if (!module->processes.empty())
259
+ log_error("The 'setundef' command can't operate in -undriven mode on modules with processes. Run 'proc' first.\n");
260
+
261
+ if (expose_mode)
262
+ {
263
+ SigMap sigmap(module);
264
+ dict<SigBit, bool> wire_drivers;
265
+ pool<SigBit> used_wires;
266
+ SigPool undriven_signals;
267
+
268
+ for (auto cell : module->cells())
269
+ for (auto &conn : cell->connections()) {
270
+ SigSpec sig = sigmap(conn.second);
271
+ if (cell->input(conn.first))
272
+ for (auto bit : sig)
273
+ if (bit.wire)
274
+ used_wires.insert(bit);
275
+ if (cell->output(conn.first))
276
+ for (int i = 0; i < GetSize(sig); i++)
277
+ if (sig[i].wire)
278
+ wire_drivers[sig[i]] = true;
279
+ }
280
+
281
+ for (auto wire : module->wires()) {
282
+ if (wire->port_input) {
283
+ SigSpec sig = sigmap(wire);
284
+ for (int i = 0; i < GetSize(sig); i++)
285
+ wire_drivers[sig[i]] = true;
286
+ }
287
+ if (wire->port_output) {
288
+ SigSpec sig = sigmap(wire);
289
+ for (auto bit : sig)
290
+ if (bit.wire)
291
+ used_wires.insert(bit);
292
+ }
293
+ }
294
+
295
+ pool<RTLIL::Wire*> undriven_wires;
296
+ for (auto bit : used_wires)
297
+ if (!wire_drivers.count(bit))
298
+ undriven_wires.insert(bit.wire);
299
+
300
+ for (auto &it : undriven_wires)
301
+ undriven_signals.add(sigmap(it));
302
+
303
+ for (auto &it : undriven_wires)
304
+ if (it->port_input)
305
+ undriven_signals.del(sigmap(it));
306
+
307
+ CellTypes ct(design);
308
+ for (auto &it : module->cells_)
309
+ for (auto &conn : it.second->connections())
310
+ if (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first))
311
+ undriven_signals.del(sigmap(conn.second));
312
+
313
+ RTLIL::SigSpec sig = undriven_signals.export_all();
314
+ for (auto &c : sig.chunks()) {
315
+ if (!design->selected(module, c.wire))
316
+ continue;
317
+ RTLIL::Wire * wire;
318
+ if (c.wire->width == c.width) {
319
+ wire = c.wire;
320
+ wire->port_input = true;
321
+ } else {
322
+ string name = c.wire->name.str() + "$[" + std::to_string(c.width + c.offset) + ":" + std::to_string(c.offset) + "]";
323
+ wire = add_wire(module, name, c.width, true, false);
324
+ module->connect(RTLIL::SigSig(c, wire));
325
+ }
326
+ log("Exposing undriven wire %s as input.\n", wire->name);
327
+ }
328
+ module->fixup_ports();
329
+ }
330
+ else
331
+ {
332
+ SigMap sigmap(module);
333
+ SigPool undriven_signals;
334
+
335
+ for (auto wire : module->selected_wires())
336
+ undriven_signals.add(sigmap(wire));
337
+
338
+ for (auto wire : module->selected_wires())
339
+ if (wire->port_input)
340
+ undriven_signals.del(sigmap(wire));
341
+
342
+ CellTypes ct(design);
343
+ for (auto &it : module->cells_)
344
+ for (auto &conn : it.second->connections())
345
+ if (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first))
346
+ undriven_signals.del(sigmap(conn.second));
347
+
348
+ RTLIL::SigSpec sig = undriven_signals.export_all();
349
+ for (auto &c : sig.chunks()) {
350
+ RTLIL::SigSpec bits;
351
+ if (worker.next_bit_mode == MODE_ANYSEQ)
352
+ bits = module->Anyseq(NEW_ID, c.width);
353
+ else if (worker.next_bit_mode == MODE_ANYCONST)
354
+ bits = module->Anyconst(NEW_ID, c.width);
355
+ else
356
+ for (int i = 0; i < c.width; i++)
357
+ bits.append(worker.next_bit());
358
+ module->connect(RTLIL::SigSig(c, bits));
359
+ }
360
+ }
361
+ }
362
+
363
+ if (init_mode)
364
+ {
365
+ SigMap sigmap(module);
366
+ pool<SigBit> ffbits;
367
+ pool<Wire*> initwires;
368
+
369
+ for (auto cell : module->cells())
370
+ {
371
+ if (!cell->is_builtin_ff())
372
+ continue;
373
+
374
+ bool cell_selected = design->selected(module, cell);
375
+ bool wire_selected = false;
376
+ for (auto bit : sigmap(cell->getPort(ID::Q)))
377
+ if (bit.wire && design->selected(module, bit.wire))
378
+ wire_selected = true;
379
+ if (!cell_selected && !wire_selected)
380
+ continue;
381
+
382
+ for (auto bit : sigmap(cell->getPort(ID::Q)))
383
+ ffbits.insert(bit);
384
+ }
385
+
386
+ auto process_initwires = [&]()
387
+ {
388
+ dict<Wire*, int> wire_weights;
389
+
390
+ for (auto wire : initwires)
391
+ {
392
+ int weight = 0;
393
+
394
+ for (auto bit : sigmap(wire))
395
+ weight += ffbits.count(bit) ? +1 : -1;
396
+
397
+ wire_weights[wire] = weight;
398
+ }
399
+
400
+ initwires.sort([&](Wire *a, Wire *b) { return wire_weights.at(a) > wire_weights.at(b); });
401
+
402
+ for (auto wire : initwires)
403
+ {
404
+ Const &initval = wire->attributes[ID::init];
405
+ initval.resize(GetSize(wire), State::Sx);
406
+
407
+ for (int i = 0; i < GetSize(wire); i++) {
408
+ SigBit bit = sigmap(SigBit(wire, i));
409
+ if (initval[i] == State::Sx && ffbits.count(bit)) {
410
+ initval.set(i, worker.next_bit());
411
+ ffbits.erase(bit);
412
+ }
413
+ }
414
+
415
+ if (initval.is_fully_undef())
416
+ wire->attributes.erase(ID::init);
417
+ }
418
+
419
+ initwires.clear();
420
+ };
421
+
422
+ for (int wire_types = 0; wire_types < 2; wire_types++)
423
+ {
424
+ // prioritize wires that already have an init attribute
425
+ if (!ffbits.empty())
426
+ {
427
+ for (auto wire : module->wires())
428
+ {
429
+ if (wire->name.isPublic() == wire_types)
430
+ continue;
431
+
432
+ if (!wire->attributes.count(ID::init))
433
+ continue;
434
+
435
+ Const &initval = wire->attributes[ID::init];
436
+ initval.resize(GetSize(wire), State::Sx);
437
+
438
+ if (initval.is_fully_undef()) {
439
+ wire->attributes.erase(ID::init);
440
+ continue;
441
+ }
442
+
443
+ for (int i = 0; i < GetSize(wire); i++)
444
+ if (initval[i] != State::Sx)
445
+ ffbits.erase(sigmap(SigBit(wire, i)));
446
+
447
+ initwires.insert(wire);
448
+ }
449
+
450
+ process_initwires();
451
+ }
452
+
453
+ // next consider wires that completely contain bits to be initialized
454
+ if (!ffbits.empty())
455
+ {
456
+ for (auto wire : module->wires())
457
+ {
458
+ if (wire->name.isPublic() == wire_types)
459
+ continue;
460
+
461
+ for (auto bit : sigmap(wire))
462
+ if (!ffbits.count(bit))
463
+ goto next_wire;
464
+
465
+ initwires.insert(wire);
466
+
467
+ next_wire:
468
+ continue;
469
+ }
470
+
471
+ process_initwires();
472
+ }
473
+
474
+ // finally use whatever wire we can find.
475
+ if (!ffbits.empty())
476
+ {
477
+ for (auto wire : module->wires())
478
+ {
479
+ if (wire->name.isPublic() == wire_types)
480
+ continue;
481
+
482
+ for (auto bit : sigmap(wire))
483
+ if (ffbits.count(bit))
484
+ initwires.insert(wire);
485
+ }
486
+
487
+ process_initwires();
488
+ }
489
+ }
490
+
491
+ log_assert(ffbits.empty());
492
+ }
493
+
494
+ if (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST)
495
+ {
496
+ // Do not add anyseq / anyconst to unused memory port clocks
497
+ std::vector<Mem> memories = Mem::get_selected_memories(module);
498
+ for (auto &mem : memories) {
499
+ bool changed = false;
500
+ for (auto &rd_port : mem.rd_ports) {
501
+ if (!rd_port.clk_enable && rd_port.clk.is_fully_undef()) {
502
+ changed = true;
503
+ rd_port.clk = State::S0;
504
+ }
505
+ }
506
+ for (auto &wr_port : mem.rd_ports) {
507
+ if (!wr_port.clk_enable && wr_port.clk.is_fully_undef()) {
508
+ changed = true;
509
+ wr_port.clk = State::S0;
510
+ }
511
+ }
512
+ if (changed)
513
+ mem.emit();
514
+ }
515
+ }
516
+
517
+ for (auto cell : module->selected_cells())
518
+ if (!cell->get_bool_attribute(ID::xprop_decoder))
519
+ cell->rewrite_sigspecs(worker);
520
+ for (auto proc : module->selected_processes())
521
+ proc->rewrite_sigspecs(worker);
522
+ for (auto &it : module->connections_) {
523
+ SigSpec lhs = it.first;
524
+ bool selected = false;
525
+ for (auto &chunk : lhs.chunks())
526
+ if (chunk.wire && module->design->selected(module, chunk.wire))
527
+ selected = true;
528
+ if (selected) {
529
+ worker(it.first);
530
+ worker(it.second);
531
+ }
532
+ }
533
+
534
+ if (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST)
535
+ {
536
+ vector<SigSpec*> siglist;
537
+ siglist.swap(worker.siglist);
538
+
539
+ for (auto sigptr : siglist)
540
+ {
541
+ SigSpec &sig = *sigptr;
542
+ int cursor = 0;
543
+
544
+ while (cursor < GetSize(sig))
545
+ {
546
+ int width = 0;
547
+ while (cursor+width < GetSize(sig) && sig[cursor+width] == State::Sx)
548
+ width++;
549
+
550
+ if (width > 0) {
551
+ if (worker.next_bit_mode == MODE_ANYSEQ)
552
+ sig.replace(cursor, module->Anyseq(NEW_ID, width));
553
+ else
554
+ sig.replace(cursor, module->Anyconst(NEW_ID, width));
555
+ cursor += width;
556
+ } else {
557
+ cursor++;
558
+ }
559
+ }
560
+ }
561
+ }
562
+ }
563
+ }
564
+ } SetundefPass;
565
+
566
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/show.cc ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ #include "kernel/rtlil.h"
21
+ #include "kernel/yosys.h"
22
+ #include "kernel/celltypes.h"
23
+ #include "kernel/log_help.h"
24
+
25
+ #ifndef _WIN32
26
+ # include <dirent.h>
27
+ #endif
28
+
29
+ #ifdef __APPLE__
30
+ # include <unistd.h>
31
+ #endif
32
+
33
+ #ifdef YOSYS_ENABLE_READLINE
34
+ # include <readline/readline.h>
35
+ #endif
36
+
37
+ #ifdef YOSYS_ENABLE_EDITLINE
38
+ # include <editline/readline.h>
39
+ #endif
40
+
41
+ USING_YOSYS_NAMESPACE
42
+ PRIVATE_NAMESPACE_BEGIN
43
+
44
+ #undef CLUSTER_CELLS_AND_PORTBOXES
45
+
46
+ struct ShowWorker
47
+ {
48
+ CellTypes ct;
49
+
50
+ vector<shared_str> dot_escape_store;
51
+ std::map<RTLIL::IdString, int> dot_id2num_store;
52
+ std::map<std::string, int> autonames;
53
+ int single_idx_count;
54
+
55
+ struct net_conn { std::set<std::pair<std::string, int>> in, out; std::string color; };
56
+ std::map<std::string, net_conn> net_conn_map;
57
+
58
+ FILE *f;
59
+ RTLIL::Design *design;
60
+ RTLIL::Module *module;
61
+ uint32_t currentColor;
62
+ bool genWidthLabels;
63
+ std::string wireshape;
64
+ bool genSignedLabels;
65
+ bool stretchIO;
66
+ bool enumerateIds;
67
+ bool abbreviateIds;
68
+ bool notitle;
69
+ bool href;
70
+ int page_counter;
71
+
72
+ const std::vector<std::pair<std::string, RTLIL::Selection>> &color_selections;
73
+ const std::vector<std::pair<std::string, RTLIL::Selection>> &label_selections;
74
+
75
+ std::map<RTLIL::Const, int> colorattr_cache;
76
+ RTLIL::IdString colorattr;
77
+
78
+
79
+ static uint32_t xorshift32(uint32_t x) {
80
+ x ^= x << 13;
81
+ x ^= x >> 17;
82
+ x ^= x << 5;
83
+ return x;
84
+ }
85
+
86
+ std::string nextColor()
87
+ {
88
+ if (currentColor == 0)
89
+ return "color=\"black\", fontcolor=\"black\"";
90
+ return stringf("colorscheme=\"dark28\", color=\"%d\", fontcolor=\"%d\"", currentColor%8+1, currentColor%8+1);
91
+ }
92
+
93
+ std::string nextColor(std::string presetColor)
94
+ {
95
+ if (presetColor.empty())
96
+ return nextColor();
97
+ return presetColor;
98
+ }
99
+
100
+ std::string nextColor(RTLIL::SigSpec sig, std::string defaultColor)
101
+ {
102
+ std::string color = findColor(sig);
103
+ if (!color.empty()) return color;
104
+ return defaultColor;
105
+ }
106
+
107
+ std::string nextColor(const RTLIL::SigSig &conn, std::string defaultColor)
108
+ {
109
+ std::string color = findColor(conn);
110
+ if (!color.empty()) return color;
111
+ return defaultColor;
112
+ }
113
+
114
+ std::string nextColor(const RTLIL::SigSpec &sig)
115
+ {
116
+ return nextColor(sig, nextColor());
117
+ }
118
+
119
+ std::string nextColor(const RTLIL::SigSig &conn)
120
+ {
121
+ return nextColor(conn, nextColor());
122
+ }
123
+
124
+ std::string widthLabel(int bits)
125
+ {
126
+ if (bits <= 1)
127
+ return "label=\"\"";
128
+ if (!genWidthLabels)
129
+ return "style=\"setlinewidth(3)\", label=\"\"";
130
+ return stringf("style=\"setlinewidth(3)\", label=\"<%d>\"", bits);
131
+ }
132
+
133
+ std::string findColor(RTLIL::SigSpec sig)
134
+ {
135
+ sig.sort_and_unify();
136
+ for (auto &c : sig.chunks()) {
137
+ if (c.wire != nullptr)
138
+ return findColor(c.wire->name);
139
+ }
140
+ return "";
141
+ }
142
+
143
+ std::string findColor(const RTLIL::SigSig &conn)
144
+ {
145
+ std::string firstColor = findColor(conn.first);
146
+ if (findColor(conn.second) == firstColor) return firstColor;
147
+ return "";
148
+ }
149
+
150
+ std::string findColor(IdString member_ref)
151
+ {
152
+ for (auto &s : color_selections)
153
+ if (member_ref != IdString::Null && s.second.selected_member(module->name, member_ref)) {
154
+ return stringf("color=\"%s\", fontcolor=\"%s\"", s.first, s.first);
155
+ }
156
+
157
+ RTLIL::Const colorattr_value;
158
+ RTLIL::Cell *cell = member_ref != IdString::Null ? module->cell(member_ref) : nullptr;
159
+ RTLIL::Wire *wire = member_ref != IdString::Null ? module->wire(member_ref) : nullptr;
160
+
161
+ if (cell && cell->attributes.count(colorattr))
162
+ colorattr_value = cell->attributes.at(colorattr);
163
+ else if (wire && wire->attributes.count(colorattr))
164
+ colorattr_value = wire->attributes.at(colorattr);
165
+ else
166
+ return "";
167
+
168
+ if (colorattr_cache.count(colorattr_value) == 0) {
169
+ int next_id = GetSize(colorattr_cache);
170
+ colorattr_cache[colorattr_value] = (next_id % 8) + 1;
171
+ }
172
+
173
+ return stringf("colorscheme=\"dark28\", color=\"%d\", fontcolor=\"%d\"", colorattr_cache.at(colorattr_value), colorattr_cache.at(colorattr_value));
174
+ }
175
+
176
+ const char *findLabel(std::string member_name)
177
+ {
178
+ bool is_id = (member_name.starts_with('$') || member_name.starts_with('\\')) &&
179
+ std::none_of(member_name.begin(), member_name.end(), [](char ch) { return (unsigned char)ch <= ' '; });
180
+ IdString member_ref = is_id ? design->twines().find(member_name) : IdString::Null;
181
+ for (auto &s : label_selections)
182
+ if (member_ref != IdString::Null && s.second.selected_member(module->name, member_ref))
183
+ return escape(s.first);
184
+ return escape(member_name, true);
185
+ }
186
+
187
+ const char *escape(std::string id, bool is_name = false)
188
+ {
189
+ if (id.size() == 0)
190
+ return "";
191
+
192
+ if (id[0] == '$' && is_name) {
193
+ if (enumerateIds) {
194
+ if (autonames.count(id) == 0) {
195
+ autonames[id] = autonames.size() + 1;
196
+ log("Generated short name for internal identifier: _%d_ -> %s\n", autonames[id], id);
197
+ }
198
+ id = stringf("_%d_", autonames[id]);
199
+ } else if (abbreviateIds) {
200
+ const char *p = id.c_str();
201
+ const char *q = strrchr(p, '$');
202
+ id = std::string(q);
203
+ }
204
+ }
205
+
206
+ if (id[0] == '\\')
207
+ id = id.substr(1);
208
+
209
+ // TODO: optionally include autoname + print correspondence in case of ambiguity
210
+ size_t max_label_len = abbreviateIds ? 256 : 16384;
211
+ if (id.size() > max_label_len) {
212
+ id = id.substr(0,max_label_len-3) + "...";
213
+ }
214
+
215
+ std::string str;
216
+ for (char ch : id) {
217
+ if (ch == '\\') {
218
+ // new graphviz have bug with escaping '\'
219
+ str += "&#9586;";
220
+ continue;
221
+ }
222
+ if (ch == '"' || ch == '<' || ch == '>')
223
+ str += "\\";
224
+ str += ch;
225
+ }
226
+
227
+ dot_escape_store.push_back(str);
228
+ return dot_escape_store.back().c_str();
229
+ }
230
+
231
+ int id2num(RTLIL::IdString id)
232
+ {
233
+ if (dot_id2num_store.count(id) > 0)
234
+ return dot_id2num_store[id];
235
+ return dot_id2num_store[id] = dot_id2num_store.size() + 1;
236
+ }
237
+
238
+ std::string gen_signode_simple(RTLIL::SigSpec sig, bool range_check = true)
239
+ {
240
+ if (GetSize(sig) == 0) {
241
+ fprintf(f, "v%d [ label=\"\" ];\n", single_idx_count);
242
+ return stringf("v%d", single_idx_count++);
243
+ }
244
+
245
+ if (sig.is_chunk()) {
246
+ const RTLIL::SigChunk &c = sig.as_chunk();
247
+ if (c.wire != nullptr && design->selected_member(module->name, c.wire->name)) {
248
+ if (!range_check || c.wire->width == c.width)
249
+ return stringf("n%d", id2num(c.wire->name));
250
+ } else {
251
+ fprintf(f, "v%d [ label=\"%s\" ];\n", single_idx_count, findLabel(log_signal(c)));
252
+ return stringf("v%d", single_idx_count++);
253
+ }
254
+ }
255
+
256
+ return std::string();
257
+ }
258
+
259
+ // Return the pieces of a label joined by a '|' separator
260
+ std::string join_label_pieces(std::vector<std::string> pieces)
261
+ {
262
+ std::string ret = "";
263
+ bool first_piece = true;
264
+
265
+ for (auto &piece : pieces) {
266
+ if (!first_piece)
267
+ ret += "|";
268
+ ret += piece;
269
+ first_piece = false;
270
+ }
271
+
272
+ return ret;
273
+ }
274
+
275
+ std::string gen_portbox(std::string port, RTLIL::SigSpec sig, bool driver, std::string *node = nullptr)
276
+ {
277
+ std::string code;
278
+ std::string net = gen_signode_simple(sig);
279
+ if (net.empty())
280
+ {
281
+ int dot_idx = single_idx_count++;
282
+ std::vector<std::string> label_pieces;
283
+ int bitpos = sig.size()-1;
284
+
285
+ RTLIL::SigSpec::Chunks sig_chunks = sig.chunks();
286
+ for (int rep, chunk_idx = ((int) sig_chunks.size()) - 1; chunk_idx >= 0; chunk_idx -= rep) {
287
+ const RTLIL::SigChunk &c = sig_chunks.at(chunk_idx);
288
+
289
+ // Find the number of times this chunk is repeating
290
+ for (rep = 1; chunk_idx - rep >= 0 && c == sig_chunks.at(chunk_idx - rep); rep++);
291
+
292
+ int cl, cr;
293
+ cl = c.offset + c.width - 1;
294
+ cr = c.offset;
295
+
296
+ if (c.is_wire()) {
297
+ if (c.wire->upto) {
298
+ cr = (c.wire->width - 1) - c.offset;
299
+ cl = cr - (c.width - 1);
300
+ }
301
+
302
+ cl += c.wire->start_offset;
303
+ cr += c.wire->start_offset;
304
+ }
305
+
306
+ // Is this chunk a constant filled with one kind of bit state?
307
+ bool no_signode = !driver && !c.is_wire() \
308
+ && std::equal(c.data.begin() + 1, c.data.end(), c.data.begin());
309
+
310
+ if (!no_signode) {
311
+ net = gen_signode_simple(c, false);
312
+ log_assert(!net.empty());
313
+ }
314
+
315
+ std::string repinfo = rep > 1 ? stringf("%dx ", rep) : "";
316
+ std::string portside = stringf("%d:%d", bitpos, bitpos - rep*c.width + 1);
317
+ std::string remoteside = stringf("%s%d:%d", repinfo, cl, cr);
318
+
319
+ if (driver) {
320
+ log_assert(!net.empty());
321
+ label_pieces.push_back(stringf("<s%d> %s - %s ", chunk_idx, portside, remoteside));
322
+ net_conn_map[net].in.insert({stringf("x%d:s%d", dot_idx, chunk_idx), rep*c.width});
323
+ net_conn_map[net].color = nextColor(c, net_conn_map[net].color);
324
+ } else {
325
+ if (no_signode) {
326
+ log_assert(rep == 1);
327
+ label_pieces.push_back(stringf("%c -&gt; %d:%d ",
328
+ c.data.front() == State::S0 ? '0' :
329
+ c.data.front() == State::S1 ? '1' :
330
+ c.data.front() == State::Sx ? 'X' :
331
+ c.data.front() == State::Sz ? 'Z' : '?',
332
+ bitpos, bitpos-rep*c.width+1));
333
+ } else {
334
+ label_pieces.push_back(stringf("<s%d> %s - %s ", chunk_idx, remoteside, portside));
335
+ net_conn_map[net].out.insert({stringf("x%d:s%d", dot_idx, chunk_idx), rep*c.width});
336
+ net_conn_map[net].color = nextColor(c, net_conn_map[net].color);
337
+ }
338
+ }
339
+
340
+ bitpos -= rep * c.width;
341
+ }
342
+
343
+ code += stringf("x%d [ shape=record, style=rounded, label=\"", dot_idx) \
344
+ + join_label_pieces(label_pieces) + stringf("\", %s ];\n", nextColor(sig));
345
+
346
+ if (!port.empty()) {
347
+ currentColor = xorshift32(currentColor);
348
+ if (driver)
349
+ code += stringf("%s:e -> x%d:w [arrowhead=odiamond, arrowtail=odiamond, dir=both, %s, %s];\n", port, dot_idx, nextColor(sig), widthLabel(sig.size()));
350
+ else
351
+ code += stringf("x%d:e -> %s:w [arrowhead=odiamond, arrowtail=odiamond, dir=both, %s, %s];\n", dot_idx, port, nextColor(sig), widthLabel(sig.size()));
352
+ }
353
+ if (node != nullptr)
354
+ *node = stringf("x%d", dot_idx);
355
+ }
356
+ else
357
+ {
358
+ if (!port.empty()) {
359
+ if (driver)
360
+ net_conn_map[net].in.insert({port, GetSize(sig)});
361
+ else
362
+ net_conn_map[net].out.insert({port, GetSize(sig)});
363
+ net_conn_map[net].color = nextColor(sig, net_conn_map[net].color);
364
+ }
365
+ if (node != nullptr)
366
+ *node = net;
367
+ }
368
+ return code;
369
+ }
370
+
371
+ void collect_proc_signals(std::vector<RTLIL::SigSpec> &obj, std::set<RTLIL::SigSpec> &signals)
372
+ {
373
+ for (auto &it : obj)
374
+ if (!it.is_fully_const())
375
+ signals.insert(it);
376
+ }
377
+
378
+ void collect_proc_signals(std::vector<RTLIL::SigSig> &obj, std::set<RTLIL::SigSpec> &input_signals, std::set<RTLIL::SigSpec> &output_signals)
379
+ {
380
+ for (auto &it : obj) {
381
+ output_signals.insert(it.first);
382
+ if (!it.second.is_fully_const())
383
+ input_signals.insert(it.second);
384
+ }
385
+ }
386
+
387
+ void collect_proc_signals(RTLIL::CaseRule *obj, std::set<RTLIL::SigSpec> &input_signals, std::set<RTLIL::SigSpec> &output_signals)
388
+ {
389
+ collect_proc_signals(obj->compare, input_signals);
390
+ collect_proc_signals(obj->actions, input_signals, output_signals);
391
+ for (auto it : obj->switches)
392
+ collect_proc_signals(it, input_signals, output_signals);
393
+ }
394
+
395
+ void collect_proc_signals(RTLIL::SwitchRule *obj, std::set<RTLIL::SigSpec> &input_signals, std::set<RTLIL::SigSpec> &output_signals)
396
+ {
397
+ input_signals.insert(obj->signal);
398
+ for (auto it : obj->cases)
399
+ collect_proc_signals(it, input_signals, output_signals);
400
+ }
401
+
402
+ void collect_proc_signals(RTLIL::SyncRule *obj, std::set<RTLIL::SigSpec> &input_signals, std::set<RTLIL::SigSpec> &output_signals)
403
+ {
404
+ input_signals.insert(obj->signal);
405
+ collect_proc_signals(obj->actions, input_signals, output_signals);
406
+ for (auto it : obj->mem_write_actions) {
407
+ input_signals.insert(it.address);
408
+ input_signals.insert(it.data);
409
+ input_signals.insert(it.enable);
410
+ }
411
+ }
412
+
413
+ void collect_proc_signals(RTLIL::Process *obj, std::set<RTLIL::SigSpec> &input_signals, std::set<RTLIL::SigSpec> &output_signals)
414
+ {
415
+ collect_proc_signals(&obj->root_case, input_signals, output_signals);
416
+ for (auto it : obj->syncs)
417
+ collect_proc_signals(it, input_signals, output_signals);
418
+ }
419
+
420
+ void handle_module()
421
+ {
422
+ single_idx_count = 0;
423
+ dot_escape_store.clear();
424
+ dot_id2num_store.clear();
425
+ net_conn_map.clear();
426
+
427
+ fprintf(f, "digraph \"%s\" {\n", escape(module->name.str()));
428
+ if (!notitle)
429
+ fprintf(f, "label=\"%s\";\n", escape(module->name.str()));
430
+ fprintf(f, "rankdir=\"LR\";\n");
431
+ fprintf(f, "remincross=true;\n");
432
+
433
+ std::set<std::string> all_sources, all_sinks;
434
+
435
+ std::map<std::string, std::string> wires_on_demand;
436
+ for (auto wire : module->selected_wires()) {
437
+ std::string shape = wireshape;
438
+ if (wire->port_input || wire->port_output)
439
+ shape = "octagon";
440
+ const bool is_borderless = (shape == "plaintext") || (shape == "plain") || (shape == "none");
441
+ if (wire->name.isPublic()) {
442
+ std::string src_href;
443
+ if (href && wire->attributes.count(ID::src) > 0)
444
+ src_href = stringf(", href=\"%s\" ", escape(wire->attributes.at(ID::src).decode_string()));
445
+ fprintf(f, "n%d [ shape=%s,%s label=\"%s\", %s%s];\n",
446
+ id2num(wire->name), shape.c_str(), is_borderless? " margin=0, width=0" : "", findLabel(wire->name.str()),
447
+ is_borderless
448
+ ? "color=\"none\", fontcolor=\"black\""
449
+ : nextColor(RTLIL::SigSpec(wire), "color=\"black\", fontcolor=\"black\"").c_str(),
450
+ src_href.c_str());
451
+ if (wire->port_input)
452
+ all_sources.insert(stringf("n%d", id2num(wire->name)));
453
+ else if (wire->port_output)
454
+ all_sinks.insert(stringf("n%d", id2num(wire->name)));
455
+ } else {
456
+ wires_on_demand[stringf("n%d", id2num(wire->name))] = wire->name.str();
457
+ }
458
+ }
459
+
460
+ if (stretchIO)
461
+ {
462
+ fprintf(f, "{ rank=\"source\";");
463
+ for (auto n : all_sources)
464
+ fprintf(f, " %s;", n.c_str());
465
+ fprintf(f, "}\n");
466
+
467
+ fprintf(f, "{ rank=\"sink\";");
468
+ for (auto n : all_sinks)
469
+ fprintf(f, " %s;", n.c_str());
470
+ fprintf(f, "}\n");
471
+ }
472
+
473
+ for (auto cell : module->selected_cells())
474
+ {
475
+ std::vector<RTLIL::IdString> in_ports, out_ports;
476
+ std::vector<std::string> in_label_pieces, out_label_pieces;
477
+
478
+ for (auto &conn : cell->connections()) {
479
+ if (!ct.cell_output(cell->type, conn.first))
480
+ in_ports.push_back(conn.first);
481
+ else
482
+ out_ports.push_back(conn.first);
483
+ }
484
+
485
+ std::sort(in_ports.begin(), in_ports.end(), RTLIL::sort_by_id_str(design->twines()));
486
+ std::sort(out_ports.begin(), out_ports.end(), RTLIL::sort_by_id_str(design->twines()));
487
+
488
+ for (auto &p : in_ports) {
489
+ std::string p_str = design->twines().str(p);
490
+ IdString signed_param = design->twines().find(p_str + "_SIGNED");
491
+ bool signed_suffix = genSignedLabels && signed_param != IdString::Null
492
+ && cell->hasParam(signed_param)
493
+ && cell->getParam(signed_param).as_bool();
494
+
495
+ in_label_pieces.push_back(stringf("<p%d> %s%s", id2num(p), escape(p_str),
496
+ signed_suffix ? "*" : ""));
497
+ }
498
+
499
+ for (auto &p : out_ports)
500
+ out_label_pieces.push_back(stringf("<p%d> %s", id2num(p), escape(design->twines().str(p))));
501
+
502
+ std::string in_label = join_label_pieces(in_label_pieces);
503
+ std::string out_label = join_label_pieces(out_label_pieces);
504
+
505
+ std::string label_string = stringf("{{%s}|%s\\n%s|{%s}}", in_label,
506
+ findLabel(cell->name.str()), escape(cell->type.str()),
507
+ out_label);
508
+
509
+ std::string code;
510
+ for (auto &conn : cell->connections()) {
511
+ code += gen_portbox(stringf("c%d:p%d", id2num(cell->name), id2num(conn.first)),
512
+ conn.second, ct.cell_output(cell->type, conn.first));
513
+ }
514
+
515
+ std::string src_href;
516
+ if (href && cell->attributes.count(ID::src) > 0) {
517
+ src_href = stringf("%shref=\"%s\" ", (findColor(cell->name).empty() ? "" :" , "), escape(cell->attributes.at(ID::src).decode_string()));
518
+ }
519
+ #ifdef CLUSTER_CELLS_AND_PORTBOXES
520
+ if (!code.empty())
521
+ fprintf(f, "subgraph cluster_c%d {\nc%d [ shape=record, label=\"%s\"%s%s ];\n%s}\n",
522
+ id2num(cell->name), id2num(cell->name), label_string.c_str(), color.c_str(), src_href.c_str(), code.c_str());
523
+ else
524
+ #endif
525
+ fprintf(f, "c%d [ shape=record, label=\"%s\", %s%s ];\n%s",
526
+ id2num(cell->name), label_string.c_str(), findColor(cell->name).c_str(), src_href.c_str(), code.c_str());
527
+ }
528
+
529
+ for (auto &it : module->processes)
530
+ {
531
+ RTLIL::Process *proc = it.second;
532
+
533
+ if (!design->selected_member(module->name, it.first))
534
+ continue;
535
+
536
+ std::set<RTLIL::SigSpec> input_signals, output_signals;
537
+ collect_proc_signals(proc, input_signals, output_signals);
538
+
539
+ int pidx = single_idx_count++;
540
+ input_signals.erase(RTLIL::SigSpec());
541
+ output_signals.erase(RTLIL::SigSpec());
542
+
543
+ for (auto &sig : input_signals) {
544
+ std::string code, node;
545
+ code += gen_portbox("", sig, false, &node);
546
+ fprintf(f, "%s", code.c_str());
547
+ net_conn_map[node].out.insert({stringf("p%d", pidx), GetSize(sig)});
548
+ net_conn_map[node].color = nextColor(sig, net_conn_map[node].color);
549
+ }
550
+
551
+ for (auto &sig : output_signals) {
552
+ std::string code, node;
553
+ code += gen_portbox("", sig, true, &node);
554
+ fprintf(f, "%s", code.c_str());
555
+ net_conn_map[node].in.insert({stringf("p%d", pidx), GetSize(sig)});
556
+ net_conn_map[node].color = nextColor(sig, net_conn_map[node].color);
557
+ }
558
+
559
+ std::string proc_src = proc->name.unescape();
560
+ if (proc->attributes.count(ID::src) > 0)
561
+ proc_src = proc->attributes.at(ID::src).decode_string();
562
+ fprintf(f, "p%d [shape=box, style=rounded, label=\"PROC %s\\n%s\", %s];\n", pidx, findLabel(proc->name.str()), proc_src.c_str(), findColor(proc->name).c_str());
563
+ }
564
+
565
+ for (auto &conn : module->connections())
566
+ {
567
+ bool found_lhs_wire = false;
568
+ for (auto &c : conn.first.chunks()) {
569
+ if (c.wire == nullptr || design->selected_member(module->name, c.wire->name))
570
+ found_lhs_wire = true;
571
+ }
572
+ bool found_rhs_wire = false;
573
+ for (auto &c : conn.second.chunks()) {
574
+ if (c.wire == nullptr || design->selected_member(module->name, c.wire->name))
575
+ found_rhs_wire = true;
576
+ }
577
+ if (!found_lhs_wire || !found_rhs_wire)
578
+ continue;
579
+
580
+ std::string code, left_node, right_node;
581
+ code += gen_portbox("", conn.second, false, &left_node);
582
+ code += gen_portbox("", conn.first, true, &right_node);
583
+ fprintf(f, "%s", code.c_str());
584
+
585
+ if (left_node[0] == 'x' && right_node[0] == 'x') {
586
+ currentColor = xorshift32(currentColor);
587
+ fprintf(f, "%s:e -> %s:w [arrowhead=odiamond, arrowtail=odiamond, dir=both, %s, %s];\n", left_node.c_str(), right_node.c_str(), nextColor(conn).c_str(), widthLabel(conn.first.size()).c_str());
588
+ } else {
589
+ net_conn_map[right_node].color = nextColor(conn, net_conn_map[right_node].color);
590
+ net_conn_map[left_node].color = nextColor(conn, net_conn_map[left_node].color);
591
+ if (left_node[0] == 'x') {
592
+ net_conn_map[right_node].in.insert({left_node, GetSize(conn.first)});
593
+ } else if (right_node[0] == 'x') {
594
+ net_conn_map[left_node].out.insert({right_node, GetSize(conn.first)});
595
+ } else {
596
+ net_conn_map[right_node].in.insert({stringf("x%d", single_idx_count), GetSize(conn.first)});
597
+ net_conn_map[left_node].out.insert({stringf("x%d", single_idx_count), GetSize(conn.first)});
598
+ fprintf(f, "x%d [shape=point, %s];\n", single_idx_count++, findColor(conn).c_str());
599
+ }
600
+ }
601
+ }
602
+
603
+ for (auto &it : net_conn_map)
604
+ {
605
+ currentColor = xorshift32(currentColor);
606
+ if (wires_on_demand.count(it.first) > 0) {
607
+ if (it.second.in.size() == 1 && it.second.out.size() > 1 && it.second.in.begin()->first.compare(0, 1, "p") == 0)
608
+ it.second.out.erase(*it.second.in.begin());
609
+ if (it.second.in.size() == 1 && it.second.out.size() == 1) {
610
+ std::string from = it.second.in.begin()->first, to = it.second.out.begin()->first;
611
+ int bits = it.second.in.begin()->second;
612
+ if (from != to || from.compare(0, 1, "p") != 0)
613
+ fprintf(f, "%s:e -> %s:w [%s, %s];\n", from.c_str(), to.c_str(), nextColor(it.second.color).c_str(), widthLabel(bits).c_str());
614
+ continue;
615
+ }
616
+ if (it.second.in.size() == 0 || it.second.out.size() == 0)
617
+ fprintf(f, "%s [ shape=diamond, label=\"%s\" ];\n", it.first.c_str(), findLabel(wires_on_demand[it.first]));
618
+ else
619
+ fprintf(f, "%s [ shape=point ];\n", it.first.c_str());
620
+ }
621
+ for (auto &it2 : it.second.in)
622
+ fprintf(f, "%s:e -> %s:w [%s, %s];\n", it2.first.c_str(), it.first.c_str(), nextColor(it.second.color).c_str(), widthLabel(it2.second).c_str());
623
+ for (auto &it2 : it.second.out)
624
+ fprintf(f, "%s:e -> %s:w [%s, %s];\n", it.first.c_str(), it2.first.c_str(), nextColor(it.second.color).c_str(), widthLabel(it2.second).c_str());
625
+ }
626
+
627
+ fprintf(f, "}\n");
628
+ }
629
+
630
+ ShowWorker(FILE *f, RTLIL::Design *design, std::vector<std::unique_ptr<RTLIL::Design>> &libs, uint32_t colorSeed, bool genWidthLabels,
631
+ const std::string wireshape, bool genSignedLabels, bool stretchIO, bool enumerateIds, bool abbreviateIds, bool notitle, bool href,
632
+ const std::vector<std::pair<std::string, RTLIL::Selection>> &color_selections,
633
+ const std::vector<std::pair<std::string, RTLIL::Selection>> &label_selections, RTLIL::IdString colorattr) :
634
+ f(f), design(design), currentColor(colorSeed), genWidthLabels(genWidthLabels), wireshape(wireshape),
635
+ genSignedLabels(genSignedLabels), stretchIO(stretchIO), enumerateIds(enumerateIds), abbreviateIds(abbreviateIds),
636
+ notitle(notitle), href(href), color_selections(color_selections), label_selections(label_selections), colorattr(colorattr)
637
+ {
638
+ ct.setup_internals();
639
+ ct.setup_internals_mem();
640
+ ct.setup_internals_anyinit();
641
+ ct.setup_stdcells();
642
+ ct.setup_stdcells_mem();
643
+ ct.setup_design(design);
644
+
645
+ for (auto &lib : libs)
646
+ ct.setup_design(lib.get());
647
+
648
+ design->optimize();
649
+ page_counter = 0;
650
+ for (auto mod : design->selected_modules())
651
+ {
652
+ module = mod;
653
+ if (design->selected_whole_module(module->name)) {
654
+ if (module->get_blackbox_attribute()) {
655
+ //log("Skipping blackbox module %s.\n", module->name.unescape());
656
+ continue;
657
+ } else
658
+ if (module->cells().size() == 0 && module->connections().empty() && module->processes.empty()) {
659
+ log("Skipping empty module %s.\n", module);
660
+ continue;
661
+ } else
662
+ log("Dumping module %s to page %d.\n", module, ++page_counter);
663
+ } else
664
+ log("Dumping selected parts of module %s to page %d.\n", module, ++page_counter);
665
+ handle_module();
666
+ }
667
+ }
668
+ };
669
+
670
+ struct ShowPass : public Pass {
671
+ ShowPass() : Pass("show", "generate schematics using graphviz") { }
672
+ bool formatted_help() override {
673
+ auto *help = PrettyHelp::get_current();
674
+ help->set_group("passes/status");
675
+ return false;
676
+ }
677
+ void help() override
678
+ {
679
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
680
+ log("\n");
681
+ log(" show [options] [selection]\n");
682
+ log("\n");
683
+ log("Create a graphviz DOT file for the selected part of the design and compile it\n");
684
+ log("to a graphics file (usually SVG or PostScript).\n");
685
+ log("\n");
686
+ log(" -viewer <viewer>\n");
687
+ log(" Run the specified command with the graphics file as parameter.\n");
688
+ log(" On Windows, this pauses yosys until the viewer exits.\n");
689
+ log(" Use \"-viewer none\" to not run any command.\n");
690
+ log("\n");
691
+ log(" -format <format>\n");
692
+ log(" Generate a graphics file in the specified format. Use 'dot' to just\n");
693
+ log(" generate a .dot file, or other <format> strings such as 'svg' or 'ps'\n");
694
+ log(" to generate files in other formats (this calls the 'dot' command).\n");
695
+ log("\n");
696
+ log(" -lib <verilog_or_rtlil_file>\n");
697
+ log(" Use the specified library file for determining whether cell ports are\n");
698
+ log(" inputs or outputs. This option can be used multiple times to specify\n");
699
+ log(" more than one library.\n");
700
+ log("\n");
701
+ log(" note: in most cases it is better to load the library before calling\n");
702
+ log(" show with 'read_verilog -lib <filename>'. it is also possible to\n");
703
+ log(" load liberty files with 'read_liberty -lib <filename>'.\n");
704
+ log("\n");
705
+ log(" -prefix <prefix>\n");
706
+ log(" generate <prefix>.* instead of ~/.yosys_show.*\n");
707
+ log("\n");
708
+ log(" -color <color> <object>\n");
709
+ log(" assign the specified color to the specified object. The object can be\n");
710
+ log(" a single selection wildcard expressions or a saved set of objects in\n");
711
+ log(" the @<name> syntax (see \"help select\" for details).\n");
712
+ log("\n");
713
+ log(" -label <text> <object>\n");
714
+ log(" assign the specified label text to the specified object. The object can\n");
715
+ log(" be a single selection wildcard expressions or a saved set of objects in\n");
716
+ log(" the @<name> syntax (see \"help select\" for details).\n");
717
+ log("\n");
718
+ log(" -colors <seed>\n");
719
+ log(" Randomly assign colors to the wires. The integer argument is the seed\n");
720
+ log(" for the random number generator. Change the seed value if the colored\n");
721
+ log(" graph still is ambiguous. A seed of zero deactivates the coloring.\n");
722
+ log("\n");
723
+ log(" -colorattr <attribute_name>\n");
724
+ log(" Use the specified attribute to assign colors. A unique color is\n");
725
+ log(" assigned to each unique value of this attribute.\n");
726
+ log("\n");
727
+ log(" -wireshape <graphviz_shape>\n");
728
+ log(" Use the specified shape for wire nodes. E.g. plaintext.\n");
729
+ log("\n");
730
+ log(" -width\n");
731
+ log(" annotate buses with a label indicating the width of the bus.\n");
732
+ log("\n");
733
+ log(" -signed\n");
734
+ log(" mark ports (A, B) that are declared as signed (using the [AB]_SIGNED\n");
735
+ log(" cell parameter) with an asterisk next to the port name.\n");
736
+ log("\n");
737
+ log(" -stretch\n");
738
+ log(" stretch the graph so all inputs are on the left side and all outputs\n");
739
+ log(" (including inout ports) are on the right side.\n");
740
+ log("\n");
741
+ log(" -pause\n");
742
+ log(" wait for the user to press enter to before returning\n");
743
+ log("\n");
744
+ log(" -enum\n");
745
+ log(" enumerate objects with internal ($-prefixed) names\n");
746
+ log("\n");
747
+ log(" -long\n");
748
+ log(" do not abbreviate objects with internal ($-prefixed) names\n");
749
+ log("\n");
750
+ log(" -notitle\n");
751
+ log(" do not add the module name as graph title to the dot file\n");
752
+ log("\n");
753
+ log(" -nobg\n");
754
+ log(" don't run viewer in the background, IE wait for the viewer tool to\n");
755
+ log(" exit before returning\n");
756
+ log("\n");
757
+ log(" -href\n");
758
+ log(" adds href attribute to all items representing cells and wires, using\n");
759
+ log(" src attribute of origin\n");
760
+ log("\n");
761
+ log("When no <format> is specified, 'dot' is used. When no <format> and <viewer> is\n");
762
+ log("specified, 'xdot' is used to display the schematic (POSIX systems only).\n");
763
+ log("\n");
764
+ log("The generated output files are '~/.yosys_show.dot' and '~/.yosys_show.<format>',\n");
765
+ log("unless another prefix is specified using -prefix <prefix>.\n");
766
+ log("\n");
767
+ log("Yosys on Windows and YosysJS use different defaults: The output is written\n");
768
+ log("to 'show.dot' in the current directory and new viewer is launched each time\n");
769
+ log("the 'show' command is executed.\n");
770
+ log("\n");
771
+ }
772
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
773
+ {
774
+ log_header(design, "Generating Graphviz representation of design.\n");
775
+ log_push();
776
+
777
+ std::vector<std::pair<std::string, RTLIL::Selection>> color_selections;
778
+ std::vector<std::pair<std::string, RTLIL::Selection>> label_selections;
779
+
780
+ #if defined(_WIN32) || !defined(YOSYS_ENABLE_SPAWN)
781
+ std::string format = "dot";
782
+ std::string prefix = "show";
783
+ #else
784
+ std::string format;
785
+ std::string prefix = stringf("%s/.yosys_show", getenv("HOME") ? getenv("HOME") : ".");
786
+ #endif
787
+ std::string viewer_exe;
788
+ std::string flag_wireshape = "diamond";
789
+ std::vector<std::string> libfiles;
790
+ std::vector<std::unique_ptr<RTLIL::Design>> libs;
791
+ uint32_t colorSeed = 0;
792
+ bool flag_width = false;
793
+ bool flag_signed = false;
794
+ bool flag_stretch = false;
795
+ bool flag_pause = false;
796
+ bool flag_enum = false;
797
+ bool flag_abbreviate = true;
798
+ bool flag_notitle = false;
799
+ bool flag_href = false;
800
+ bool custom_prefix = false;
801
+ std::string background = "&";
802
+ RTLIL::IdString colorattr;
803
+
804
+ size_t argidx;
805
+ for (argidx = 1; argidx < args.size(); argidx++)
806
+ {
807
+ std::string arg = args[argidx];
808
+ if (arg == "-viewer" && argidx+1 < args.size()) {
809
+ viewer_exe = args[++argidx];
810
+ continue;
811
+ }
812
+ if (arg == "-lib" && argidx+1 < args.size()) {
813
+ libfiles.push_back(args[++argidx]);
814
+ continue;
815
+ }
816
+ if (arg == "-prefix" && argidx+1 < args.size()) {
817
+ prefix = args[++argidx];
818
+ custom_prefix = true;
819
+ continue;
820
+ }
821
+ if (arg == "-color" && argidx+2 < args.size()) {
822
+ std::pair<std::string, RTLIL::Selection> data;
823
+ data.first = args[++argidx], argidx++;
824
+ handle_extra_select_args(this, args, argidx, argidx+1, design);
825
+ data.second = design->selection();
826
+ design->pop_selection();
827
+ color_selections.push_back(data);
828
+ continue;
829
+ }
830
+ if (arg == "-label" && argidx+2 < args.size()) {
831
+ std::pair<std::string, RTLIL::Selection> data;
832
+ data.first = args[++argidx], argidx++;
833
+ handle_extra_select_args(this, args, argidx, argidx+1, design);
834
+ data.second = design->selection();
835
+ design->pop_selection();
836
+ label_selections.push_back(data);
837
+ continue;
838
+ }
839
+ if (arg == "-colors" && argidx+1 < args.size()) {
840
+ colorSeed = atoi(args[++argidx].c_str());
841
+ for (int i = 0; i < 100; i++)
842
+ colorSeed = ShowWorker::xorshift32(colorSeed);
843
+ continue;
844
+ }
845
+ if (arg == "-colorattr" && argidx+1 < args.size()) {
846
+ colorattr = design->twines().add(RTLIL::escape_id(args[++argidx]));
847
+ continue;
848
+ }
849
+ if (arg == "-format" && argidx+1 < args.size()) {
850
+ format = args[++argidx];
851
+ continue;
852
+ }
853
+ if (arg == "-wireshape" && argidx+1 < args.size()) {
854
+ flag_wireshape = args[++argidx];
855
+ continue;
856
+ }
857
+ if (arg == "-width") {
858
+ flag_width= true;
859
+ continue;
860
+ }
861
+ if (arg == "-signed") {
862
+ flag_signed= true;
863
+ continue;
864
+ }
865
+ if (arg == "-stretch") {
866
+ flag_stretch= true;
867
+ continue;
868
+ }
869
+ if (arg == "-pause") {
870
+ flag_pause= true;
871
+ continue;
872
+ }
873
+ if (arg == "-enum") {
874
+ flag_enum = true;
875
+ flag_abbreviate = false;
876
+ continue;
877
+ }
878
+ if (arg == "-long") {
879
+ flag_enum = false;
880
+ flag_abbreviate = false;
881
+ continue;
882
+ }
883
+ if (arg == "-notitle") {
884
+ flag_notitle = true;
885
+ continue;
886
+ }
887
+ if (arg == "-nobg") {
888
+ background= "";
889
+ continue;
890
+ }
891
+ if (arg == "-href") {
892
+ flag_href = true;
893
+ continue;
894
+ }
895
+ break;
896
+ }
897
+ extra_args(args, argidx, design);
898
+
899
+ if (format != "ps" && format != "dot") {
900
+ int modcount = 0;
901
+ for (auto module : design->selected_modules()) {
902
+ if (module->get_blackbox_attribute())
903
+ continue;
904
+ if (module->cells().size() == 0 && module->connections().empty())
905
+ continue;
906
+ modcount++;
907
+ }
908
+ if (modcount > 1)
909
+ log_cmd_error("For formats different than 'ps' or 'dot' only one module must be selected.\n");
910
+ }
911
+
912
+ for (auto filename : libfiles) {
913
+ std::ifstream f;
914
+ rewrite_filename(filename);
915
+ f.open(filename.c_str());
916
+ yosys_input_files.insert(filename);
917
+ if (f.fail())
918
+ log_error("Can't open lib file `%s'.\n", filename);
919
+ auto &lib = libs.emplace_back(std::make_unique<RTLIL::Design>());
920
+ Frontend::frontend_call(lib.get(), &f, filename, (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".il") == 0 ? "rtlil" : "verilog"));
921
+ }
922
+
923
+ if (libs.size() > 0)
924
+ log_header(design, "Continuing show pass.\n");
925
+
926
+ std::string dot_file = stringf("%s.dot", prefix);
927
+ std::string out_file = stringf("%s.%s", prefix, format.empty() ? "svg" : format);
928
+
929
+ log("Writing dot description to `%s'.\n", dot_file);
930
+ FILE *f = fopen(dot_file.c_str(), "w");
931
+ if (custom_prefix)
932
+ yosys_output_files.insert(dot_file);
933
+ if (f == nullptr)
934
+ log_cmd_error("Can't open dot file `%s' for writing.\n", dot_file);
935
+ ShowWorker worker(f, design, libs, colorSeed, flag_width, flag_wireshape, flag_signed, flag_stretch, flag_enum, flag_abbreviate, flag_notitle, flag_href, color_selections, label_selections, colorattr);
936
+ fclose(f);
937
+
938
+ if (worker.page_counter == 0)
939
+ log_cmd_error("Nothing there to show.\n");
940
+
941
+ if (format != "dot" && !format.empty()) {
942
+ #ifdef _WIN32
943
+ // system()/cmd.exe does not understand single quotes on Windows.
944
+ #define DOT_CMD "dot -T%s \"%s\" > \"%s.new\" && move \"%s.new\" \"%s\""
945
+ #else
946
+ #define DOT_CMD "dot -T%s '%s' > '%s.new' && mv '%s.new' '%s'"
947
+ #endif
948
+ std::string cmd = stringf(DOT_CMD, format, dot_file, out_file, out_file, out_file);
949
+ #undef DOT_CMD
950
+ log("Exec: %s\n", cmd);
951
+ #if defined(YOSYS_ENABLE_SPAWN)
952
+ if (run_command(cmd) != 0)
953
+ log_cmd_error("Shell command failed!\n");
954
+ #endif
955
+ }
956
+
957
+ #if !defined(YOSYS_ENABLE_SPAWN)
958
+ log_assert(viewer_exe.empty() && !format.empty());
959
+ #else
960
+ if (viewer_exe != "none") {
961
+ if (!viewer_exe.empty()) {
962
+ #ifdef _WIN32
963
+ // system()/cmd.exe does not understand single quotes nor
964
+ // background tasks on Windows. So we have to pause yosys
965
+ // until the viewer exits.
966
+ std::string cmd = stringf("%s \"%s\"", viewer_exe, out_file);
967
+ #else
968
+ std::string cmd = stringf("%s '%s' %s", viewer_exe, out_file, background);
969
+ #endif
970
+ log("Exec: %s\n", cmd);
971
+ if (run_command(cmd) != 0)
972
+ log_cmd_error("Shell command failed!\n");
973
+ } else
974
+ if (format.empty()) {
975
+ #ifdef __APPLE__
976
+ std::string cmd = stringf("ps -fu %d | grep -q '[ ]%s' || xdot '%s' %s", getuid(), dot_file, dot_file, background);
977
+ #else
978
+ std::string cmd = stringf("{ test -f '%s.pid' && fuser -s '%s.pid' 2> /dev/null; } || ( echo $$ >&3; exec xdot '%s'; ) 3> '%s.pid' %s", dot_file, dot_file, dot_file, dot_file, background);
979
+ #endif
980
+ log("Exec: %s\n", cmd);
981
+ if (run_command(cmd) != 0)
982
+ log_cmd_error("Shell command failed!\n");
983
+ }
984
+ }
985
+ #endif
986
+
987
+ if (flag_pause) {
988
+ #ifdef YOSYS_ENABLE_READLINE
989
+ char *input = nullptr;
990
+ while ((input = readline("Press ENTER to continue (or type 'shell' to open a shell)> ")) != nullptr) {
991
+ if (input[strspn(input, " \t\r\n")] == 0)
992
+ break;
993
+ char *p = input + strspn(input, " \t\r\n");
994
+ if (!strcmp(p, "shell")) {
995
+ Pass::call(design, "shell");
996
+ break;
997
+ }
998
+ }
999
+ #else
1000
+ log_cmd_error("This version of yosys is built without readline support => 'show -pause' is not available.\n");
1001
+ #endif
1002
+ }
1003
+
1004
+ log_pop();
1005
+ }
1006
+ } ShowPass;
1007
+
1008
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/shuffle.cc ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "kernel/yosys.h"
2
+ #include <random>
3
+
4
+ USING_YOSYS_NAMESPACE
5
+ PRIVATE_NAMESPACE_BEGIN
6
+
7
+ // Fisher–Yates shuffle
8
+ // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
9
+ template<typename T>
10
+ static void shuffle_vector(std::vector<T> &vec, std::mt19937 &rng)
11
+ {
12
+ for (size_t i = vec.size(); i > 1; i--)
13
+ std::swap(vec[i-1], vec[rng() % i]);
14
+ }
15
+
16
+ template<typename K, typename T>
17
+ static void shuffle_dict(dict<K, T> &d, std::mt19937 &rng)
18
+ {
19
+ std::vector<std::pair<K, T>> entries(d.begin(), d.end());
20
+ shuffle_vector(entries, rng);
21
+ dict<K, T> shuffled;
22
+ for (auto &entry : entries)
23
+ shuffled.insert(std::move(entry));
24
+ d.swap(shuffled);
25
+ }
26
+
27
+ struct ShufflePass : public Pass {
28
+ ShufflePass() : Pass("shuffle", "deterministically reorder design objects") { }
29
+ void help() override
30
+ {
31
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
32
+ log("\n");
33
+ log(" shuffle [-seed <seed>] [selection]\n");
34
+ log("\n");
35
+ log("Deterministically reorder design objects.\n");
36
+ log("\n");
37
+ log(" -seed <seed>\n");
38
+ log(" use the given random number generator seed (default: 1)\n");
39
+ log("\n");
40
+ }
41
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
42
+ {
43
+ unsigned int seed = 1;
44
+
45
+ log_header(design, "Executing SHUFFLE pass (deterministically reorder design objects).\n");
46
+
47
+ size_t argidx;
48
+ for (argidx = 1; argidx < args.size(); argidx++)
49
+ {
50
+ if (args[argidx] == "-seed" && argidx+1 < args.size()) {
51
+ seed = std::stoul(args[++argidx]);
52
+ continue;
53
+ }
54
+ break;
55
+ }
56
+ extra_args(args, argidx, design);
57
+
58
+ std::mt19937 rng(seed);
59
+
60
+ for (auto module : design->selected_whole_modules_warn())
61
+ {
62
+ log("Shuffling module %s.\n", module);
63
+ shuffle_dict(module->wires_, rng);
64
+ shuffle_dict(module->cells_, rng);
65
+ shuffle_vector(module->connections_, rng);
66
+ shuffle_dict(module->memories, rng);
67
+ shuffle_dict(module->processes, rng);
68
+ }
69
+ }
70
+ } ShufflePass;
71
+
72
+ PRIVATE_NAMESPACE_END
chips/yosys/passes/cmds/sort.cc ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "kernel/yosys.h"
2
+
3
+ USING_YOSYS_NAMESPACE
4
+ PRIVATE_NAMESPACE_BEGIN
5
+
6
+ struct SortPass : Pass {
7
+ SortPass() : Pass("sort", "sort the design objects") {}
8
+ void help() override
9
+ {
10
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
11
+ log("\n");
12
+ log(" sort\n");
13
+ log("\n");
14
+ log("Sorts the design objects.\n");
15
+ log("\n");
16
+ }
17
+ void execute(std::vector<std::string> args, RTLIL::Design *d) override
18
+ {
19
+ log_header(d, "Executing SORT pass.\n");
20
+ if (args.size() != 1)
21
+ log_cmd_error("This pass takes no arguments.\n");
22
+ d->sort();
23
+ }
24
+ } SortPass;
25
+
26
+ PRIVATE_NAMESPACE_END