Add shregmap -init_msb_first and use in synth_xilinx
[yosys.git] / passes / techmap / shregmap.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
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 USING_YOSYS_NAMESPACE
24 PRIVATE_NAMESPACE_BEGIN
25
26 struct ShregmapTech
27 {
28 virtual ~ShregmapTech() { }
29 virtual bool analyze(vector<int> &taps) = 0;
30 virtual bool fixup(Cell *cell, dict<int, SigBit> &taps) = 0;
31 };
32
33 struct ShregmapOptions
34 {
35 int minlen, maxlen;
36 int keep_before, keep_after;
37 bool zinit, init, params, ffe, init_msb_first;
38 dict<IdString, pair<IdString, IdString>> ffcells;
39 ShregmapTech *tech;
40
41 ShregmapOptions()
42 {
43 minlen = 2;
44 maxlen = 0;
45 keep_before = 0;
46 keep_after = 0;
47 zinit = false;
48 init = false;
49 params = false;
50 ffe = false;
51 init_msb_first = false;
52 tech = nullptr;
53 }
54 };
55
56 struct ShregmapTechGreenpak4 : ShregmapTech
57 {
58 bool analyze(vector<int> &taps)
59 {
60 if (GetSize(taps) > 2 && taps[0] == 0 && taps[2] < 17) {
61 taps.clear();
62 return true;
63 }
64
65 if (GetSize(taps) > 2)
66 return false;
67
68 if (taps.back() > 16) return false;
69
70 return true;
71 }
72
73 bool fixup(Cell *cell, dict<int, SigBit> &taps)
74 {
75 auto D = cell->getPort("\\D");
76 auto C = cell->getPort("\\C");
77
78 auto newcell = cell->module->addCell(NEW_ID, "\\GP_SHREG");
79 newcell->setPort("\\nRST", State::S1);
80 newcell->setPort("\\CLK", C);
81 newcell->setPort("\\IN", D);
82
83 int i = 0;
84 for (auto tap : taps) {
85 newcell->setPort(i ? "\\OUTB" : "\\OUTA", tap.second);
86 newcell->setParam(i ? "\\OUTB_TAP" : "\\OUTA_TAP", tap.first + 1);
87 i++;
88 }
89
90 cell->setParam("\\OUTA_INVERT", 0);
91 return false;
92 }
93 };
94
95 struct ShregmapWorker
96 {
97 Module *module;
98 SigMap sigmap;
99
100 const ShregmapOptions &opts;
101 int dff_count, shreg_count;
102
103 pool<Cell*> remove_cells;
104 pool<SigBit> remove_init;
105
106 dict<SigBit, bool> sigbit_init;
107 dict<SigBit, Cell*> sigbit_chain_next;
108 dict<SigBit, Cell*> sigbit_chain_prev;
109 pool<SigBit> sigbit_with_non_chain_users;
110 pool<Cell*> chain_start_cells;
111
112 void make_sigbit_chain_next_prev()
113 {
114 for (auto wire : module->wires())
115 {
116 if (wire->port_output || wire->get_bool_attribute("\\keep")) {
117 for (auto bit : sigmap(wire))
118 sigbit_with_non_chain_users.insert(bit);
119 }
120
121 if (wire->attributes.count("\\init")) {
122 SigSpec initsig = sigmap(wire);
123 Const initval = wire->attributes.at("\\init");
124 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
125 if (initval[i] == State::S0 && !opts.zinit)
126 sigbit_init[initsig[i]] = false;
127 else if (initval[i] == State::S1)
128 sigbit_init[initsig[i]] = true;
129 }
130 }
131
132 for (auto cell : module->cells())
133 {
134 if (opts.ffcells.count(cell->type) && !cell->get_bool_attribute("\\keep"))
135 {
136 IdString d_port = opts.ffcells.at(cell->type).first;
137 IdString q_port = opts.ffcells.at(cell->type).second;
138
139 SigBit d_bit = sigmap(cell->getPort(d_port).as_bit());
140 SigBit q_bit = sigmap(cell->getPort(q_port).as_bit());
141
142 if (opts.init || sigbit_init.count(q_bit) == 0)
143 {
144 if (sigbit_chain_next.count(d_bit)) {
145 sigbit_with_non_chain_users.insert(d_bit);
146 } else
147 sigbit_chain_next[d_bit] = cell;
148
149 sigbit_chain_prev[q_bit] = cell;
150 continue;
151 }
152 }
153
154 for (auto conn : cell->connections())
155 if (cell->input(conn.first))
156 for (auto bit : sigmap(conn.second))
157 sigbit_with_non_chain_users.insert(bit);
158 }
159 }
160
161 void find_chain_start_cells()
162 {
163 for (auto it : sigbit_chain_next)
164 {
165 if (opts.tech == nullptr && sigbit_with_non_chain_users.count(it.first))
166 goto start_cell;
167
168 if (sigbit_chain_prev.count(it.first) != 0)
169 {
170 Cell *c1 = sigbit_chain_prev.at(it.first);
171 Cell *c2 = it.second;
172
173 if (c1->type != c2->type)
174 goto start_cell;
175
176 if (c1->parameters != c2->parameters)
177 goto start_cell;
178
179 IdString d_port = opts.ffcells.at(c1->type).first;
180 IdString q_port = opts.ffcells.at(c1->type).second;
181
182 auto c1_conn = c1->connections();
183 auto c2_conn = c1->connections();
184
185 c1_conn.erase(d_port);
186 c1_conn.erase(q_port);
187
188 c2_conn.erase(d_port);
189 c2_conn.erase(q_port);
190
191 if (c1_conn != c2_conn)
192 goto start_cell;
193
194 continue;
195 }
196
197 start_cell:
198 chain_start_cells.insert(it.second);
199 }
200 }
201
202 vector<Cell*> create_chain(Cell *start_cell)
203 {
204 vector<Cell*> chain;
205
206 Cell *c = start_cell;
207 while (c != nullptr)
208 {
209 chain.push_back(c);
210
211 IdString q_port = opts.ffcells.at(c->type).second;
212 SigBit q_bit = sigmap(c->getPort(q_port).as_bit());
213
214 if (sigbit_chain_next.count(q_bit) == 0)
215 break;
216
217 c = sigbit_chain_next.at(q_bit);
218 if (chain_start_cells.count(c) != 0)
219 break;
220 }
221
222 return chain;
223 }
224
225 void process_chain(vector<Cell*> &chain)
226 {
227 if (GetSize(chain) < opts.keep_before + opts.minlen + opts.keep_after)
228 return;
229
230 int cursor = opts.keep_before;
231 while (cursor < GetSize(chain) - opts.keep_after)
232 {
233 int depth = GetSize(chain) - opts.keep_after - cursor;
234
235 if (opts.maxlen > 0)
236 depth = std::min(opts.maxlen, depth);
237
238 Cell *first_cell = chain[cursor];
239 IdString q_port = opts.ffcells.at(first_cell->type).second;
240 dict<int, SigBit> taps_dict;
241
242 if (opts.tech)
243 {
244 vector<SigBit> qbits;
245 vector<int> taps;
246
247 for (int i = 0; i < depth; i++)
248 {
249 Cell *cell = chain[cursor+i];
250 auto qbit = sigmap(cell->getPort(q_port));
251 qbits.push_back(qbit);
252
253 if (sigbit_with_non_chain_users.count(qbit))
254 taps.push_back(i);
255 }
256
257 while (depth > 0)
258 {
259 if (taps.empty() || taps.back() < depth-1)
260 taps.push_back(depth-1);
261
262 if (opts.tech->analyze(taps))
263 break;
264
265 taps.pop_back();
266 depth--;
267 }
268
269 depth = 0;
270 for (auto tap : taps) {
271 taps_dict[tap] = qbits.at(tap);
272 log_assert(depth < tap+1);
273 depth = tap+1;
274 }
275 }
276
277 if (depth < 2) {
278 cursor++;
279 continue;
280 }
281
282 Cell *last_cell = chain[cursor+depth-1];
283
284 log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n",
285 log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), depth);
286
287 dff_count += depth;
288 shreg_count += 1;
289
290 string shreg_cell_type_str = "$__SHREG";
291 if (opts.params) {
292 shreg_cell_type_str += "_";
293 } else {
294 if (first_cell->type[1] != '_')
295 shreg_cell_type_str += "_";
296 shreg_cell_type_str += first_cell->type.substr(1);
297 }
298
299 if (opts.init) {
300 vector<State> initval;
301 for (int i = depth-1; i >= 0; i--) {
302 SigBit bit = sigmap(chain[cursor+i]->getPort(q_port).as_bit());
303 if (sigbit_init.count(bit) == 0)
304 initval.push_back(State::Sx);
305 else if (sigbit_init.at(bit))
306 initval.push_back(State::S1);
307 else
308 initval.push_back(State::S0);
309 remove_init.insert(bit);
310 }
311 if (opts.init_msb_first)
312 std::reverse(initval.begin(), initval.end());
313 first_cell->setParam("\\INIT", initval);
314 }
315
316 if (opts.zinit)
317 for (int i = depth-1; i >= 0; i--) {
318 SigBit bit = sigmap(chain[cursor+i]->getPort(q_port).as_bit());
319 remove_init.insert(bit);
320 }
321
322 if (opts.params)
323 {
324 int param_clkpol = -1;
325 int param_enpol = 2;
326
327 if (first_cell->type == "$_DFF_N_") param_clkpol = 0;
328 if (first_cell->type == "$_DFF_P_") param_clkpol = 1;
329
330 if (first_cell->type == "$_DFFE_NN_") param_clkpol = 0, param_enpol = 0;
331 if (first_cell->type == "$_DFFE_NP_") param_clkpol = 0, param_enpol = 1;
332 if (first_cell->type == "$_DFFE_PN_") param_clkpol = 1, param_enpol = 0;
333 if (first_cell->type == "$_DFFE_PP_") param_clkpol = 1, param_enpol = 1;
334
335 log_assert(param_clkpol >= 0);
336 first_cell->setParam("\\CLKPOL", param_clkpol);
337 if (opts.ffe) first_cell->setParam("\\ENPOL", param_enpol);
338 }
339
340 first_cell->type = shreg_cell_type_str;
341 first_cell->setPort(q_port, last_cell->getPort(q_port));
342 first_cell->setParam("\\DEPTH", depth);
343
344 if (opts.tech != nullptr && !opts.tech->fixup(first_cell, taps_dict))
345 remove_cells.insert(first_cell);
346
347 for (int i = 1; i < depth; i++)
348 remove_cells.insert(chain[cursor+i]);
349 cursor += depth;
350 }
351 }
352
353 void cleanup()
354 {
355 for (auto cell : remove_cells)
356 module->remove(cell);
357
358 for (auto wire : module->wires())
359 {
360 if (wire->attributes.count("\\init") == 0)
361 continue;
362
363 SigSpec initsig = sigmap(wire);
364 Const &initval = wire->attributes.at("\\init");
365
366 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
367 if (remove_init.count(initsig[i]))
368 initval[i] = State::Sx;
369
370 if (SigSpec(initval).is_fully_undef())
371 wire->attributes.erase("\\init");
372 }
373
374 remove_cells.clear();
375 sigbit_chain_next.clear();
376 sigbit_chain_prev.clear();
377 chain_start_cells.clear();
378 }
379
380 ShregmapWorker(Module *module, const ShregmapOptions &opts) :
381 module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0)
382 {
383 make_sigbit_chain_next_prev();
384 find_chain_start_cells();
385
386 for (auto c : chain_start_cells) {
387 vector<Cell*> chain = create_chain(c);
388 process_chain(chain);
389 }
390
391 cleanup();
392 }
393 };
394
395 struct ShregmapPass : public Pass {
396 ShregmapPass() : Pass("shregmap", "map shift registers") { }
397 void help() YS_OVERRIDE
398 {
399 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
400 log("\n");
401 log(" shregmap [options] [selection]\n");
402 log("\n");
403 log("This pass converts chains of $_DFF_[NP]_ gates to target specific shift register\n");
404 log("primitives. The generated shift register will be of type $__SHREG_DFF_[NP]_ and\n");
405 log("will use the same interface as the original $_DFF_*_ cells. The cell parameter\n");
406 log("'DEPTH' will contain the depth of the shift register. Use a target-specific\n");
407 log("'techmap' map file to convert those cells to the actual target cells.\n");
408 log("\n");
409 log(" -minlen N\n");
410 log(" minimum length of shift register (default = 2)\n");
411 log(" (this is the length after -keep_before and -keep_after)\n");
412 log("\n");
413 log(" -maxlen N\n");
414 log(" maximum length of shift register (default = no limit)\n");
415 log(" larger chains will be mapped to multiple shift register instances\n");
416 log("\n");
417 log(" -keep_before N\n");
418 log(" number of DFFs to keep before the shift register (default = 0)\n");
419 log("\n");
420 log(" -keep_after N\n");
421 log(" number of DFFs to keep after the shift register (default = 0)\n");
422 log("\n");
423 log(" -clkpol pos|neg|any\n");
424 log(" limit match to only positive or negative edge clocks. (default = any)\n");
425 log("\n");
426 log(" -enpol pos|neg|none|any_or_none|any\n");
427 log(" limit match to FFs with the specified enable polarity. (default = none)\n");
428 log("\n");
429 log(" -match <cell_type>[:<d_port_name>:<q_port_name>]\n");
430 log(" match the specified cells instead of $_DFF_N_ and $_DFF_P_. If\n");
431 log(" ':<d_port_name>:<q_port_name>' is omitted then 'D' and 'Q' is used\n");
432 log(" by default. E.g. the option '-clkpol pos' is just an alias for\n");
433 log(" '-match $_DFF_P_', which is an alias for '-match $_DFF_P_:D:Q'.\n");
434 log("\n");
435 log(" -params\n");
436 log(" instead of encoding the clock and enable polarity in the cell name by\n");
437 log(" deriving from the original cell name, simply name all generated cells\n");
438 log(" $__SHREG_ and use CLKPOL and ENPOL parameters. An ENPOL value of 2 is\n");
439 log(" used to denote cells without enable input. The ENPOL parameter is\n");
440 log(" omitted when '-enpol none' (or no -enpol option) is passed.\n");
441 log("\n");
442 log(" -zinit\n");
443 log(" assume the shift register is automatically zero-initialized, so it\n");
444 log(" becomes legal to merge zero initialized FFs into the shift register.\n");
445 log("\n");
446 log(" -init\n");
447 log(" map initialized registers to the shift reg, add an INIT parameter to\n");
448 log(" generated cells with the initialization value. (First bit to shift out\n");
449 log(" in LSB position)\n");
450 log("\n");
451 log(" -init_msb_first\n");
452 log(" same as -init, but INIT parameter to have first bit to shift out\n");
453 log(" in MSB position.\n");
454 log("\n");
455 log(" -tech greenpak4\n");
456 log(" map to greenpak4 shift registers.\n");
457 log("\n");
458 }
459 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
460 {
461 ShregmapOptions opts;
462 string clkpol, enpol;
463
464 log_header(design, "Executing SHREGMAP pass (map shift registers).\n");
465
466 size_t argidx;
467 for (argidx = 1; argidx < args.size(); argidx++)
468 {
469 if (args[argidx] == "-clkpol" && argidx+1 < args.size()) {
470 clkpol = args[++argidx];
471 continue;
472 }
473 if (args[argidx] == "-enpol" && argidx+1 < args.size()) {
474 enpol = args[++argidx];
475 continue;
476 }
477 if (args[argidx] == "-match" && argidx+1 < args.size()) {
478 vector<string> match_args = split_tokens(args[++argidx], ":");
479 if (GetSize(match_args) < 2)
480 match_args.push_back("D");
481 if (GetSize(match_args) < 3)
482 match_args.push_back("Q");
483 IdString id_cell_type(RTLIL::escape_id(match_args[0]));
484 IdString id_d_port_name(RTLIL::escape_id(match_args[1]));
485 IdString id_q_port_name(RTLIL::escape_id(match_args[2]));
486 opts.ffcells[id_cell_type] = make_pair(id_d_port_name, id_q_port_name);
487 continue;
488 }
489 if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
490 opts.minlen = atoi(args[++argidx].c_str());
491 continue;
492 }
493 if (args[argidx] == "-maxlen" && argidx+1 < args.size()) {
494 opts.maxlen = atoi(args[++argidx].c_str());
495 continue;
496 }
497 if (args[argidx] == "-keep_before" && argidx+1 < args.size()) {
498 opts.keep_before = atoi(args[++argidx].c_str());
499 continue;
500 }
501 if (args[argidx] == "-keep_after" && argidx+1 < args.size()) {
502 opts.keep_after = atoi(args[++argidx].c_str());
503 continue;
504 }
505 if (args[argidx] == "-tech" && argidx+1 < args.size() && opts.tech == nullptr) {
506 string tech = args[++argidx];
507 if (tech == "greenpak4") {
508 clkpol = "pos";
509 opts.zinit = true;
510 opts.tech = new ShregmapTechGreenpak4;
511 } else {
512 argidx--;
513 break;
514 }
515 continue;
516 }
517 if (args[argidx] == "-zinit") {
518 opts.zinit = true;
519 continue;
520 }
521 if (args[argidx] == "-init") {
522 opts.init = true;
523 continue;
524 }
525 if (args[argidx] == "-init_msb_first") {
526 opts.init = true;
527 opts.init_msb_first = true;
528 continue;
529 }
530 if (args[argidx] == "-params") {
531 opts.params = true;
532 continue;
533 }
534 break;
535 }
536 extra_args(args, argidx, design);
537
538 if (opts.zinit && opts.init)
539 log_cmd_error("Options -zinit and -init are exclusive!\n");
540
541 if (opts.ffcells.empty())
542 {
543 bool clk_pos = clkpol == "" || clkpol == "pos" || clkpol == "any";
544 bool clk_neg = clkpol == "" || clkpol == "neg" || clkpol == "any";
545
546 bool en_none = enpol == "" || enpol == "none" || enpol == "any_or_none";
547 bool en_pos = enpol == "pos" || enpol == "any" || enpol == "any_or_none";
548 bool en_neg = enpol == "neg" || enpol == "any" || enpol == "any_or_none";
549
550 if (clk_pos && en_none)
551 opts.ffcells["$_DFF_P_"] = make_pair(IdString("\\D"), IdString("\\Q"));
552 if (clk_neg && en_none)
553 opts.ffcells["$_DFF_N_"] = make_pair(IdString("\\D"), IdString("\\Q"));
554
555 if (clk_pos && en_pos)
556 opts.ffcells["$_DFFE_PP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
557 if (clk_pos && en_neg)
558 opts.ffcells["$_DFFE_PN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
559
560 if (clk_neg && en_pos)
561 opts.ffcells["$_DFFE_NP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
562 if (clk_neg && en_neg)
563 opts.ffcells["$_DFFE_NN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
564
565 if (en_pos || en_neg)
566 opts.ffe = true;
567 }
568 else
569 {
570 if (!clkpol.empty())
571 log_cmd_error("Options -clkpol and -match are exclusive!\n");
572 if (!enpol.empty())
573 log_cmd_error("Options -enpol and -match are exclusive!\n");
574 if (opts.params)
575 log_cmd_error("Options -params and -match are exclusive!\n");
576 }
577
578 int dff_count = 0;
579 int shreg_count = 0;
580
581 for (auto module : design->selected_modules()) {
582 ShregmapWorker worker(module, opts);
583 dff_count += worker.dff_count;
584 shreg_count += worker.shreg_count;
585 }
586
587 log("Converted %d dff cells into %d shift registers.\n", dff_count, shreg_count);
588
589 if (opts.tech != nullptr) {
590 delete opts.tech;
591 opts.tech = nullptr;
592 }
593 }
594 } ShregmapPass;
595
596 PRIVATE_NAMESPACE_END