Fixed "flatten" top-module detection: Only use on fully selected designs
[yosys.git] / passes / techmap / techmap.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/register.h"
21 #include "kernel/sigtools.h"
22 #include "kernel/log.h"
23 #include <stdlib.h>
24 #include <assert.h>
25 #include <stdio.h>
26 #include <string.h>
27
28 #include "passes/techmap/stdcells.inc"
29
30 static void apply_prefix(std::string prefix, std::string &id)
31 {
32 if (id[0] == '\\')
33 id = prefix + "." + id.substr(1);
34 else
35 id = "$techmap" + prefix + "." + id;
36 }
37
38 static void apply_prefix(std::string prefix, RTLIL::SigSpec &sig, RTLIL::Module *module)
39 {
40 for (size_t i = 0; i < sig.chunks.size(); i++) {
41 if (sig.chunks[i].wire == NULL)
42 continue;
43 std::string wire_name = sig.chunks[i].wire->name;
44 apply_prefix(prefix, wire_name);
45 assert(module->wires.count(wire_name) > 0);
46 sig.chunks[i].wire = module->wires[wire_name];
47 }
48 }
49
50 std::map<std::pair<RTLIL::IdString, std::map<RTLIL::IdString, RTLIL::Const>>, RTLIL::Module*> techmap_cache;
51 std::map<RTLIL::Module*, bool> techmap_do_cache;
52
53 struct TechmapWireData {
54 RTLIL::Wire *wire;
55 RTLIL::SigSpec value;
56 };
57
58 typedef std::map<std::string, std::vector<TechmapWireData>> TechmapWires;
59
60 static TechmapWires techmap_find_special_wires(RTLIL::Module *module)
61 {
62 TechmapWires result;
63
64 if (module == NULL)
65 return result;
66
67 for (auto &it : module->wires) {
68 const char *p = it.first.c_str();
69 if (*p == '$')
70 continue;
71
72 const char *q = strrchr(p+1, '.');
73 p = q ? q : p+1;
74
75 if (!strncmp(p, "_TECHMAP_", 9)) {
76 TechmapWireData record;
77 record.wire = it.second;
78 record.value = it.second;
79 result[p].push_back(record);
80 it.second->attributes["\\keep"] = RTLIL::Const(1);
81 it.second->attributes["\\_techmap_special_"] = RTLIL::Const(1);
82 }
83 }
84
85 if (!result.empty()) {
86 SigMap sigmap(module);
87 for (auto &it1 : result)
88 for (auto &it2 : it1.second)
89 sigmap.apply(it2.value);
90 }
91
92 return result;
93 }
94
95 static void techmap_module_worker(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::Module *tpl, bool flatten_mode)
96 {
97 log("Mapping `%s.%s' using `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(tpl->name));
98
99 if (tpl->memories.size() != 0)
100 log_error("Technology map yielded memories -> this is not supported.\n");
101
102 if (tpl->processes.size() != 0)
103 log_error("Technology map yielded processes -> this is not supported.\n");
104
105 std::map<RTLIL::IdString, RTLIL::IdString> positional_ports;
106
107 for (auto &it : tpl->wires) {
108 if (it.second->port_id > 0)
109 positional_ports[stringf("$%d", it.second->port_id)] = it.first;
110 RTLIL::Wire *w = new RTLIL::Wire(*it.second);
111 apply_prefix(cell->name, w->name);
112 w->port_input = false;
113 w->port_output = false;
114 w->port_id = 0;
115 if (it.second->get_bool_attribute("\\_techmap_special_"))
116 w->attributes.clear();
117 module->wires[w->name] = w;
118 design->select(module, w);
119 }
120
121 SigMap port_signal_map;
122
123 for (auto &it : cell->connections) {
124 RTLIL::IdString portname = it.first;
125 if (positional_ports.count(portname) > 0)
126 portname = positional_ports.at(portname);
127 if (tpl->wires.count(portname) == 0 || tpl->wires.at(portname)->port_id == 0) {
128 if (portname.substr(0, 1) == "$")
129 log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", portname.c_str(), cell->name.c_str(), tpl->name.c_str());
130 continue;
131 }
132 RTLIL::Wire *w = tpl->wires.at(portname);
133 RTLIL::SigSig c;
134 if (w->port_output) {
135 c.first = it.second;
136 c.second = RTLIL::SigSpec(w);
137 apply_prefix(cell->name, c.second, module);
138 } else {
139 c.first = RTLIL::SigSpec(w);
140 c.second = it.second;
141 apply_prefix(cell->name, c.first, module);
142 }
143 if (c.second.width > c.first.width)
144 c.second.remove(c.first.width, c.second.width - c.first.width);
145 if (c.second.width < c.first.width)
146 c.second.append(RTLIL::SigSpec(RTLIL::State::S0, c.first.width - c.second.width));
147 assert(c.first.width == c.second.width);
148 #if 0
149 // more conservative approach:
150 // connect internal and external wires
151 module->connections.push_back(c);
152 #else
153 // approach that yields nicer outputs:
154 // replace internal wires that are connected to external wires
155 if (w->port_output)
156 port_signal_map.add(c.second, c.first);
157 else
158 port_signal_map.add(c.first, c.second);
159 #endif
160 }
161
162 for (auto &it : tpl->cells) {
163 RTLIL::Cell *c = new RTLIL::Cell(*it.second);
164 if (!flatten_mode && c->type.substr(0, 2) == "\\$")
165 c->type = c->type.substr(1);
166 apply_prefix(cell->name, c->name);
167 for (auto &it2 : c->connections) {
168 apply_prefix(cell->name, it2.second, module);
169 port_signal_map.apply(it2.second);
170 }
171 module->cells[c->name] = c;
172 design->select(module, c);
173 }
174
175 for (auto &it : tpl->connections) {
176 RTLIL::SigSig c = it;
177 apply_prefix(cell->name, c.first, module);
178 apply_prefix(cell->name, c.second, module);
179 port_signal_map.apply(c.first);
180 port_signal_map.apply(c.second);
181 module->connections.push_back(c);
182 }
183
184 module->cells.erase(cell->name);
185 delete cell;
186 }
187
188 static bool techmap_module(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Design *map, std::set<RTLIL::Cell*> &handled_cells,
189 const std::map<RTLIL::IdString, std::set<RTLIL::IdString>> &celltypeMap, bool flatten_mode)
190 {
191 if (!design->selected(module))
192 return false;
193
194 bool log_continue = false;
195 bool did_something = false;
196 std::vector<std::string> cell_names;
197
198 for (auto &cell_it : module->cells)
199 cell_names.push_back(cell_it.first);
200
201 for (auto &cell_name : cell_names)
202 {
203 if (module->cells.count(cell_name) == 0)
204 continue;
205
206 RTLIL::Cell *cell = module->cells[cell_name];
207
208 if (!design->selected(module, cell) || handled_cells.count(cell) > 0)
209 continue;
210
211 if (celltypeMap.count(cell->type) == 0)
212 continue;
213
214 for (auto &tpl_name : celltypeMap.at(cell->type))
215 {
216 std::string derived_name = tpl_name;
217 RTLIL::Module *tpl = map->modules[tpl_name];
218 std::map<RTLIL::IdString, RTLIL::Const> parameters = cell->parameters;
219
220 if (!flatten_mode) {
221 for (auto conn : cell->connections) {
222 if (conn.first.substr(0, 1) == "$")
223 continue;
224 if (tpl->wires.count(conn.first) > 0 && tpl->wires.at(conn.first)->port_id > 0)
225 continue;
226 if (!conn.second.is_fully_const() || parameters.count(conn.first) > 0)
227 goto next_tpl;
228 parameters[conn.first] = conn.second.as_const();
229 }
230
231 if (0) {
232 next_tpl:
233 continue;
234 }
235 }
236
237 std::pair<RTLIL::IdString, std::map<RTLIL::IdString, RTLIL::Const>> key(tpl_name, parameters);
238 if (techmap_cache.count(key) > 0) {
239 tpl = techmap_cache[key];
240 } else {
241 if (cell->parameters.size() != 0) {
242 derived_name = tpl->derive(map, parameters);
243 tpl = map->modules[derived_name];
244 log_continue = true;
245 }
246 techmap_cache[key] = tpl;
247 }
248
249 if (flatten_mode)
250 techmap_do_cache[tpl] = true;
251
252 if (techmap_do_cache.count(tpl) == 0)
253 {
254 bool keep_running = true;
255 techmap_do_cache[tpl] = true;
256
257 while (keep_running)
258 {
259 TechmapWires twd = techmap_find_special_wires(tpl);
260 keep_running = false;
261
262 for (auto &it : twd["_TECHMAP_FAIL_"]) {
263 RTLIL::SigSpec value = it.value;
264 if (value.is_fully_const() && value.as_bool()) {
265 log("Not using module `%s' from techmap as it contains a %s marker wire with non-zero value %s.\n",
266 derived_name.c_str(), RTLIL::id2cstr(it.wire->name), log_signal(value));
267 techmap_do_cache[tpl] = false;
268 }
269 }
270
271 if (!techmap_do_cache[tpl])
272 break;
273
274 for (auto &it : twd)
275 {
276 if (it.first.substr(0, 12) != "_TECHMAP_DO_" || it.second.empty())
277 continue;
278
279 auto &data = it.second.front();
280
281 if (!data.value.is_fully_const())
282 log_error("Techmap yielded config wire %s with non-const value %s.\n", RTLIL::id2cstr(data.wire->name), log_signal(data.value));
283
284 tpl->wires.erase(data.wire->name);
285 const char *p = data.wire->name.c_str();
286 const char *q = strrchr(p+1, '.');
287 q = q ? q : p+1;
288
289 assert(!strncmp(q, "_TECHMAP_DO_", 12));
290 std::string new_name = data.wire->name.substr(0, q-p) + "_TECHMAP_DONE_" + data.wire->name.substr(q-p+12);
291 while (tpl->wires.count(new_name))
292 new_name += "_";
293 data.wire->name = new_name;
294 tpl->add(data.wire);
295
296 std::string cmd_string;
297 std::vector<char> cmd_string_chars;
298 std::vector<RTLIL::State> bits = data.value.as_const().bits;
299 for (int i = 0; i < int(bits.size()); i += 8) {
300 char ch = 0;
301 for (int j = 0; j < 8 && i+j < int(bits.size()); j++)
302 if (bits[i+j] == RTLIL::State::S1)
303 ch |= 1 << j;
304 if (ch != 0)
305 cmd_string_chars.push_back(ch);
306 }
307 for (int i = int(cmd_string_chars.size())-1; i >= 0; i--)
308 cmd_string += cmd_string_chars[i];
309
310 RTLIL::Selection tpl_mod_sel(false);
311 tpl_mod_sel.select(tpl);
312 map->selection_stack.push_back(tpl_mod_sel);
313 Pass::call(map, cmd_string);
314 map->selection_stack.pop_back();
315
316 keep_running = true;
317 break;
318 }
319 }
320
321 TechmapWires twd = techmap_find_special_wires(tpl);
322 for (auto &it : twd) {
323 if (it.first != "_TECHMAP_FAIL_" && it.first.substr(0, 12) != "_TECHMAP_DO_" && it.first.substr(0, 14) != "_TECHMAP_DONE_")
324 log_error("Techmap yielded unknown config wire %s.\n", it.first.c_str());
325 if (techmap_do_cache[tpl])
326 for (auto &it2 : it.second)
327 if (!it2.value.is_fully_const())
328 log_error("Techmap yielded config wire %s with non-const value %s.\n", RTLIL::id2cstr(it2.wire->name), log_signal(it2.value));
329 }
330 }
331
332 if (techmap_do_cache.at(tpl) == false)
333 continue;
334
335 if (log_continue) {
336 log_header("Continuing TECHMAP pass.\n");
337 log_continue = false;
338 }
339
340 techmap_module_worker(design, module, cell, tpl, flatten_mode);
341 did_something = true;
342 cell = NULL;
343 break;
344 }
345
346 handled_cells.insert(cell);
347 }
348
349 if (log_continue) {
350 log_header("Continuing TECHMAP pass.\n");
351 log_continue = false;
352 }
353
354 return did_something;
355 }
356
357 struct TechmapPass : public Pass {
358 TechmapPass() : Pass("techmap", "simple technology mapper") { }
359 virtual void help()
360 {
361 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
362 log("\n");
363 log(" techmap [-map filename] [selection]\n");
364 log("\n");
365 log("This pass implements a very simple technology mapper that replaces cells in\n");
366 log("the design with implementations given in form of a verilog or ilang source\n");
367 log("file.\n");
368 log("\n");
369 log(" -map filename\n");
370 log(" the library of cell implementations to be used.\n");
371 log(" without this parameter a builtin library is used that\n");
372 log(" transforms the internal RTL cells to the internal gate\n");
373 log(" library.\n");
374 log("\n");
375 log("When a module in the map file has the 'techmap_celltype' attribute set, it will\n");
376 log("match cells with a type that match the text value of this attribute.\n");
377 log("\n");
378 log("All wires in the modules from the map file matching the pattern _TECHMAP_*\n");
379 log("or *._TECHMAP_* are special wires that are used to pass instructions from\n");
380 log("the mapping module to the techmap command. At the moment the following spoecial\n");
381 log("wires are supported:\n");
382 log("\n");
383 log(" _TECHMAP_FAIL_\n");
384 log(" When this wire is set to a non-zero constant value, techmap will not\n");
385 log(" use this module and instead try the next module with a matching\n");
386 log(" 'techmap_celltype' attribute.\n");
387 log("\n");
388 log(" When such a wire exists but does not have a constant value after all\n");
389 log(" _TECHMAP_DO_* commands have been executed, an error is generated.\n");
390 log("\n");
391 log(" _TECHMAP_DO_*\n");
392 log(" This wires are evaluated in alphabetical order. The constant text value\n");
393 log(" of this wire is a yosys command (or sequence of commands) that is run\n");
394 log(" by techmap on the module. A common use case is to run 'proc' on modules\n");
395 log(" that are written using always-statements.\n");
396 log("\n");
397 log(" When such a wire has a non-constant value at the time it is to be\n");
398 log(" evaluated, an error is produced. That means it is possible for such a\n");
399 log(" wire to start out as non-constant and evaluate to a constant value\n");
400 log(" during processing of other _TECHMAP_DO_* commands.\n");
401 log("\n");
402 log("When a module in the map file has a parameter where the according cell in the\n");
403 log("design has a port, the module from the map file is only used if the port in\n");
404 log("the design is connected to a constant value. The parameter is then set to the\n");
405 log("constant value.\n");
406 log("\n");
407 log("See 'help extract' for a pass that does the opposite thing.\n");
408 log("\n");
409 log("See 'help flatten' for a pass that does flatten the design (which is\n");
410 log("esentially techmap but using the design itself as map library).\n");
411 log("\n");
412 }
413 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
414 {
415 log_header("Executing TECHMAP pass (map to technology primitives).\n");
416 log_push();
417
418 std::vector<std::string> map_files;
419
420 size_t argidx;
421 for (argidx = 1; argidx < args.size(); argidx++) {
422 if (args[argidx] == "-map" && argidx+1 < args.size()) {
423 map_files.push_back(args[++argidx]);
424 continue;
425 }
426 break;
427 }
428 extra_args(args, argidx, design);
429
430 RTLIL::Design *map = new RTLIL::Design;
431 if (map_files.empty()) {
432 FILE *f = fmemopen(stdcells_code, strlen(stdcells_code), "rt");
433 Frontend::frontend_call(map, f, "<stdcells.v>", "verilog");
434 fclose(f);
435 } else
436 for (auto &fn : map_files) {
437 FILE *f = fopen(fn.c_str(), "rt");
438 if (f == NULL)
439 log_cmd_error("Can't open map file `%s'\n", fn.c_str());
440 Frontend::frontend_call(map, f, fn, (fn.size() > 3 && fn.substr(fn.size()-3) == ".il") ? "ilang" : "verilog");
441 fclose(f);
442 }
443
444 std::map<RTLIL::IdString, RTLIL::Module*> modules_new;
445 for (auto &it : map->modules) {
446 if (it.first.substr(0, 2) == "\\$")
447 it.second->name = it.first.substr(1);
448 modules_new[it.second->name] = it.second;
449 }
450 map->modules.swap(modules_new);
451
452 std::map<RTLIL::IdString, std::set<RTLIL::IdString>> celltypeMap;
453 for (auto &it : map->modules) {
454 if (it.second->attributes.count("\\techmap_celltype") && !it.second->attributes.at("\\techmap_celltype").str.empty()) {
455 celltypeMap[RTLIL::escape_id(it.second->attributes.at("\\techmap_celltype").str)].insert(it.first);
456 } else
457 celltypeMap[it.first].insert(it.first);
458 }
459
460 bool did_something = true;
461 std::set<RTLIL::Cell*> handled_cells;
462 while (did_something) {
463 did_something = false;
464 for (auto &mod_it : design->modules)
465 if (techmap_module(design, mod_it.second, map, handled_cells, celltypeMap, false))
466 did_something = true;
467 if (did_something)
468 design->check();
469 }
470
471 log("No more expansions possible.\n");
472 techmap_cache.clear();
473 techmap_do_cache.clear();
474 delete map;
475 log_pop();
476 }
477 } TechmapPass;
478
479 struct FlattenPass : public Pass {
480 FlattenPass() : Pass("flatten", "flatten design") { }
481 virtual void help()
482 {
483 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
484 log("\n");
485 log(" flatten [selection]\n");
486 log("\n");
487 log("This pass flattens the design by replacing cells by their implementation. This\n");
488 log("pass is very simmilar to the 'techmap' pass. The only difference is that this\n");
489 log("pass is using the current design as mapping library.\n");
490 log("\n");
491 }
492 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
493 {
494 log_header("Executing FLATTEN pass (flatten design).\n");
495 log_push();
496
497 extra_args(args, 1, design);
498
499 std::map<RTLIL::IdString, std::set<RTLIL::IdString>> celltypeMap;
500 for (auto &it : design->modules)
501 celltypeMap[it.first].insert(it.first);
502
503 RTLIL::Module *top_mod = NULL;
504 if (design->full_selection())
505 for (auto &mod_it : design->modules)
506 if (mod_it.second->get_bool_attribute("\\top"))
507 top_mod = mod_it.second;
508
509 bool did_something = true;
510 std::set<RTLIL::Cell*> handled_cells;
511 while (did_something) {
512 did_something = false;
513 if (top_mod != NULL) {
514 if (techmap_module(design, top_mod, design, handled_cells, celltypeMap, true))
515 did_something = true;
516 } else {
517 for (auto &mod_it : design->modules)
518 if (techmap_module(design, mod_it.second, design, handled_cells, celltypeMap, true))
519 did_something = true;
520 }
521 }
522
523 log("No more expansions possible.\n");
524
525 if (top_mod != NULL) {
526 std::map<RTLIL::IdString, RTLIL::Module*> new_modules;
527 for (auto &mod_it : design->modules)
528 if (mod_it.second == top_mod) {
529 new_modules[mod_it.first] = mod_it.second;
530 } else {
531 log("Deleting now unused module %s.\n", RTLIL::id2cstr(mod_it.first));
532 delete mod_it.second;
533 }
534 design->modules.swap(new_modules);
535 }
536
537 techmap_cache.clear();
538 techmap_do_cache.clear();
539 log_pop();
540 }
541 } FlattenPass;
542