Various win32 / vs build fixes
[yosys.git] / passes / hierarchy / hierarchy.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 <stdlib.h>
22 #include <stdio.h>
23 #include <set>
24
25 #ifndef _WIN32
26 # include <unistd.h>
27 #endif
28
29
30 USING_YOSYS_NAMESPACE
31 PRIVATE_NAMESPACE_BEGIN
32
33 struct generate_port_decl_t {
34 bool input, output;
35 RTLIL::IdString portname;
36 int index;
37 };
38
39 void generate(RTLIL::Design *design, const std::vector<std::string> &celltypes, const std::vector<generate_port_decl_t> &portdecls)
40 {
41 std::set<RTLIL::IdString> found_celltypes;
42
43 for (auto i1 : design->modules_)
44 for (auto i2 : i1.second->cells_)
45 {
46 RTLIL::Cell *cell = i2.second;
47 if (design->has(cell->type))
48 continue;
49 if (cell->type.substr(0, 1) == "$" && cell->type.substr(0, 3) != "$__")
50 continue;
51 for (auto &pattern : celltypes)
52 if (patmatch(pattern.c_str(), RTLIL::unescape_id(cell->type).c_str()))
53 found_celltypes.insert(cell->type);
54 }
55
56 for (auto &celltype : found_celltypes)
57 {
58 std::set<RTLIL::IdString> portnames;
59 std::set<RTLIL::IdString> parameters;
60 std::map<RTLIL::IdString, int> portwidths;
61 log("Generate module for cell type %s:\n", celltype.c_str());
62
63 for (auto i1 : design->modules_)
64 for (auto i2 : i1.second->cells_)
65 if (i2.second->type == celltype) {
66 for (auto &conn : i2.second->connections()) {
67 if (conn.first[0] != '$')
68 portnames.insert(conn.first);
69 portwidths[conn.first] = std::max(portwidths[conn.first], conn.second.size());
70 }
71 for (auto &para : i2.second->parameters)
72 parameters.insert(para.first);
73 }
74
75 for (auto &decl : portdecls)
76 if (decl.index > 0)
77 portnames.insert(decl.portname);
78
79 std::set<int> indices;
80 for (int i = 0; i < int(portnames.size()); i++)
81 indices.insert(i+1);
82
83 std::vector<generate_port_decl_t> ports(portnames.size());
84
85 for (auto &decl : portdecls)
86 if (decl.index > 0) {
87 portwidths[decl.portname] = std::max(portwidths[decl.portname], 1);
88 portwidths[decl.portname] = std::max(portwidths[decl.portname], portwidths[stringf("$%d", decl.index)]);
89 log(" port %d: %s [%d:0] %s\n", decl.index, decl.input ? decl.output ? "inout" : "input" : "output", portwidths[decl.portname]-1, RTLIL::id2cstr(decl.portname));
90 if (indices.count(decl.index) > ports.size())
91 log_error("Port index (%d) exceeds number of found ports (%d).\n", decl.index, int(ports.size()));
92 if (indices.count(decl.index) == 0)
93 log_error("Conflict on port index %d.\n", decl.index);
94 indices.erase(decl.index);
95 portnames.erase(decl.portname);
96 ports[decl.index-1] = decl;
97 }
98
99 while (portnames.size() > 0) {
100 RTLIL::IdString portname = *portnames.begin();
101 for (auto &decl : portdecls)
102 if (decl.index == 0 && patmatch(decl.portname.c_str(), RTLIL::unescape_id(portname).c_str())) {
103 generate_port_decl_t d = decl;
104 d.portname = portname;
105 d.index = *indices.begin();
106 log_assert(!indices.empty());
107 indices.erase(d.index);
108 ports[d.index-1] = d;
109 portwidths[d.portname] = std::max(portwidths[d.portname], 1);
110 log(" port %d: %s [%d:0] %s\n", d.index, d.input ? d.output ? "inout" : "input" : "output", portwidths[d.portname]-1, RTLIL::id2cstr(d.portname));
111 goto found_matching_decl;
112 }
113 log_error("Can't match port %s.\n", RTLIL::id2cstr(portname));
114 found_matching_decl:;
115 portnames.erase(portname);
116 }
117
118 log_assert(indices.empty());
119
120 RTLIL::Module *mod = new RTLIL::Module;
121 mod->name = celltype;
122 mod->attributes["\\blackbox"] = RTLIL::Const(1);
123 design->add(mod);
124
125 for (auto &decl : ports) {
126 RTLIL::Wire *wire = mod->addWire(decl.portname, portwidths.at(decl.portname));
127 wire->port_id = decl.index;
128 wire->port_input = decl.input;
129 wire->port_output = decl.output;
130 }
131
132 mod->fixup_ports();
133
134 for (auto &para : parameters)
135 log(" ignoring parameter %s.\n", RTLIL::id2cstr(para));
136
137 log(" module %s created.\n", RTLIL::id2cstr(mod->name));
138 }
139 }
140
141 bool expand_module(RTLIL::Design *design, RTLIL::Module *module, bool flag_check, std::vector<std::string> &libdirs)
142 {
143 bool did_something = false;
144 std::map<RTLIL::Cell*, std::pair<int, int>> array_cells;
145 std::string filename;
146
147 for (auto &cell_it : module->cells_)
148 {
149 RTLIL::Cell *cell = cell_it.second;
150
151 if (cell->type.substr(0, 7) == "$array:") {
152 int pos_idx = cell->type.str().find_first_of(':');
153 int pos_num = cell->type.str().find_first_of(':', pos_idx + 1);
154 int pos_type = cell->type.str().find_first_of(':', pos_num + 1);
155 int idx = atoi(cell->type.str().substr(pos_idx + 1, pos_num).c_str());
156 int num = atoi(cell->type.str().substr(pos_num + 1, pos_type).c_str());
157 array_cells[cell] = std::pair<int, int>(idx, num);
158 cell->type = cell->type.str().substr(pos_type + 1);
159 }
160
161 if (design->modules_.count(cell->type) == 0)
162 {
163 if (design->modules_.count("$abstract" + cell->type.str()))
164 {
165 cell->type = design->modules_.at("$abstract" + cell->type.str())->derive(design, cell->parameters);
166 cell->parameters.clear();
167 did_something = true;
168 continue;
169 }
170
171 if (cell->type[0] == '$')
172 continue;
173
174 for (auto &dir : libdirs)
175 {
176 filename = dir + "/" + RTLIL::unescape_id(cell->type) + ".v";
177 if (check_file_exists(filename)) {
178 std::vector<std::string> args;
179 args.push_back(filename);
180 Frontend::frontend_call(design, NULL, filename, "verilog");
181 goto loaded_module;
182 }
183
184 filename = dir + "/" + RTLIL::unescape_id(cell->type) + ".il";
185 if (check_file_exists(filename)) {
186 std::vector<std::string> args;
187 args.push_back(filename);
188 Frontend::frontend_call(design, NULL, filename, "ilang");
189 goto loaded_module;
190 }
191 }
192
193 if (flag_check && cell->type[0] != '$')
194 log_error("Module `%s' referenced in module `%s' in cell `%s' is not part of the design.\n",
195 cell->type.c_str(), module->name.c_str(), cell->name.c_str());
196 continue;
197
198 loaded_module:
199 if (design->modules_.count(cell->type) == 0)
200 log_error("File `%s' from libdir does not declare module `%s'.\n", filename.c_str(), cell->type.c_str());
201 did_something = true;
202 }
203
204 if (cell->parameters.size() == 0)
205 continue;
206
207 if (design->modules_.at(cell->type)->get_bool_attribute("\\blackbox"))
208 continue;
209
210 RTLIL::Module *mod = design->modules_[cell->type];
211 cell->type = mod->derive(design, cell->parameters);
212 cell->parameters.clear();
213 did_something = true;
214 }
215
216 for (auto &it : array_cells)
217 {
218 RTLIL::Cell *cell = it.first;
219 int idx = it.second.first, num = it.second.second;
220
221 if (design->modules_.count(cell->type) == 0)
222 log_error("Array cell `%s.%s' of unknown type `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
223
224 RTLIL::Module *mod = design->modules_[cell->type];
225
226 for (auto &conn : cell->connections_) {
227 int conn_size = conn.second.size();
228 RTLIL::IdString portname = conn.first;
229 if (portname.substr(0, 1) == "$") {
230 int port_id = atoi(portname.substr(1).c_str());
231 for (auto &wire_it : mod->wires_)
232 if (wire_it.second->port_id == port_id) {
233 portname = wire_it.first;
234 break;
235 }
236 }
237 if (mod->wires_.count(portname) == 0)
238 log_error("Array cell `%s.%s' connects to unknown port `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(conn.first));
239 int port_size = mod->wires_.at(portname)->width;
240 if (conn_size == port_size)
241 continue;
242 if (conn_size != port_size*num)
243 log_error("Array cell `%s.%s' has invalid port vs. signal size for port `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(conn.first));
244 conn.second = conn.second.extract(port_size*idx, port_size);
245 }
246 }
247
248 return did_something;
249 }
250
251 void hierarchy_worker(RTLIL::Design *design, std::set<RTLIL::Module*> &used, RTLIL::Module *mod, int indent)
252 {
253 if (used.count(mod) > 0)
254 return;
255
256 if (indent == 0)
257 log("Top module: %s\n", mod->name.c_str());
258 else
259 log("Used module: %*s%s\n", indent, "", mod->name.c_str());
260 used.insert(mod);
261
262 for (auto &it : mod->cells_) {
263 if (design->modules_.count(it.second->type) > 0)
264 hierarchy_worker(design, used, design->modules_[it.second->type], indent+4);
265 }
266 }
267
268 void hierarchy(RTLIL::Design *design, RTLIL::Module *top, bool purge_lib, bool first_pass)
269 {
270 std::set<RTLIL::Module*> used;
271 hierarchy_worker(design, used, top, 0);
272
273 std::vector<RTLIL::Module*> del_modules;
274 for (auto &it : design->modules_)
275 if (used.count(it.second) == 0)
276 del_modules.push_back(it.second);
277
278 for (auto mod : del_modules) {
279 if (first_pass && mod->name.substr(0, 9) == "$abstract")
280 continue;
281 if (!purge_lib && mod->get_bool_attribute("\\blackbox"))
282 continue;
283 log("Removing unused module `%s'.\n", mod->name.c_str());
284 design->modules_.erase(mod->name);
285 delete mod;
286 }
287
288 log("Removed %d unused modules.\n", GetSize(del_modules));
289 }
290
291 bool set_keep_assert(std::map<RTLIL::Module*, bool> &cache, RTLIL::Module *mod)
292 {
293 if (cache.count(mod) == 0)
294 for (auto c : mod->cells()) {
295 RTLIL::Module *m = mod->design->module(c->type);
296 if ((m != nullptr && set_keep_assert(cache, m)) || c->type == "$assert")
297 return cache[mod] = true;
298 }
299 return cache[mod];
300 }
301
302 struct HierarchyPass : public Pass {
303 HierarchyPass() : Pass("hierarchy", "check, expand and clean up design hierarchy") { }
304 virtual void help()
305 {
306 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
307 log("\n");
308 log(" hierarchy [-check] [-top <module>]\n");
309 log(" hierarchy -generate <cell-types> <port-decls>\n");
310 log("\n");
311 log("In parametric designs, a module might exists in several variations with\n");
312 log("different parameter values. This pass looks at all modules in the current\n");
313 log("design an re-runs the language frontends for the parametric modules as\n");
314 log("needed.\n");
315 log("\n");
316 log(" -check\n");
317 log(" also check the design hierarchy. this generates an error when\n");
318 log(" an unknown module is used as cell type.\n");
319 log("\n");
320 log(" -purge_lib\n");
321 log(" by default the hierarchy command will not remove library (blackbox)\n");
322 log(" module. use this options to also remove unused blackbox modules.\n");
323 log("\n");
324 log(" -libdir <directory>\n");
325 log(" search for files named <module_name>.v in the specified directory\n");
326 log(" for unknown modules and automatically run read_verilog for each\n");
327 log(" unknown module.\n");
328 log("\n");
329 log(" -keep_positionals\n");
330 log(" per default this pass also converts positional arguments in cells\n");
331 log(" to arguments using port names. this option disables this behavior.\n");
332 log("\n");
333 log(" -nokeep_asserts\n");
334 log(" per default this pass sets the \"keep\" attribute on all modules\n");
335 log(" that directly or indirectly contain one or more $assert cells. this\n");
336 log(" option disables this behavior.\n");
337 log("\n");
338 log(" -top <module>\n");
339 log(" use the specified top module to built a design hierarchy. modules\n");
340 log(" outside this tree (unused modules) are removed.\n");
341 log("\n");
342 log(" when the -top option is used, the 'top' attribute will be set on the\n");
343 log(" specified top module. otherwise a module with the 'top' attribute set\n");
344 log(" will implicitly be used as top module, if such a module exists.\n");
345 log("\n");
346 log("In -generate mode this pass generates blackbox modules for the given cell\n");
347 log("types (wildcards supported). For this the design is searched for cells that\n");
348 log("match the given types and then the given port declarations are used to\n");
349 log("determine the direction of the ports. The syntax for a port declaration is:\n");
350 log("\n");
351 log(" {i|o|io}[@<num>]:<portname>\n");
352 log("\n");
353 log("Input ports are specified with the 'i' prefix, output ports with the 'o'\n");
354 log("prefix and inout ports with the 'io' prefix. The optional <num> specifies\n");
355 log("the position of the port in the parameter list (needed when instanciated\n");
356 log("using positional arguments). When <num> is not specified, the <portname> can\n");
357 log("also contain wildcard characters.\n");
358 log("\n");
359 log("This pass ignores the current selection and always operates on all modules\n");
360 log("in the current design.\n");
361 log("\n");
362 }
363 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
364 {
365 log_header("Executing HIERARCHY pass (managing design hierarchy).\n");
366
367 bool flag_check = false;
368 bool purge_lib = false;
369 RTLIL::Module *top_mod = NULL;
370 std::vector<std::string> libdirs;
371
372 bool generate_mode = false;
373 bool keep_positionals = false;
374 bool nokeep_asserts = false;
375 std::vector<std::string> generate_cells;
376 std::vector<generate_port_decl_t> generate_ports;
377
378 size_t argidx;
379 for (argidx = 1; argidx < args.size(); argidx++)
380 {
381 if (args[argidx] == "-generate" && !flag_check && !top_mod) {
382 generate_mode = true;
383 log("Entering generate mode.\n");
384 while (++argidx < args.size()) {
385 const char *p = args[argidx].c_str();
386 generate_port_decl_t decl;
387 if (p[0] == 'i' && p[1] == 'o')
388 decl.input = true, decl.output = true, p += 2;
389 else if (*p == 'i')
390 decl.input = true, decl.output = false, p++;
391 else if (*p == 'o')
392 decl.input = false, decl.output = true, p++;
393 else
394 goto is_celltype;
395 if (*p == '@') {
396 char *endptr;
397 decl.index = strtol(++p, &endptr, 10);
398 if (decl.index < 1)
399 goto is_celltype;
400 p = endptr;
401 } else
402 decl.index = 0;
403 if (*(p++) != ':')
404 goto is_celltype;
405 if (*p == 0)
406 goto is_celltype;
407 decl.portname = p;
408 log("Port declaration: %s", decl.input ? decl.output ? "inout" : "input" : "output");
409 if (decl.index >= 1)
410 log(" [at position %d]", decl.index);
411 log(" %s\n", decl.portname.c_str());
412 generate_ports.push_back(decl);
413 continue;
414 is_celltype:
415 log("Celltype: %s\n", args[argidx].c_str());
416 generate_cells.push_back(RTLIL::unescape_id(args[argidx]));
417 }
418 continue;
419 }
420 if (args[argidx] == "-check") {
421 flag_check = true;
422 continue;
423 }
424 if (args[argidx] == "-purge_lib") {
425 purge_lib = true;
426 continue;
427 }
428 if (args[argidx] == "-keep_positionals") {
429 keep_positionals = true;
430 continue;
431 }
432 if (args[argidx] == "-nokeep_asserts") {
433 nokeep_asserts = true;
434 continue;
435 }
436 if (args[argidx] == "-libdir" && argidx+1 < args.size()) {
437 libdirs.push_back(args[++argidx]);
438 continue;
439 }
440 if (args[argidx] == "-top") {
441 if (++argidx >= args.size())
442 log_cmd_error("Option -top requires an additional argument!\n");
443 top_mod = design->modules_.count(RTLIL::escape_id(args[argidx])) ? design->modules_.at(RTLIL::escape_id(args[argidx])) : NULL;
444 if (top_mod == NULL && design->modules_.count("$abstract" + RTLIL::escape_id(args[argidx]))) {
445 std::map<RTLIL::IdString, RTLIL::Const> empty_parameters;
446 design->modules_.at("$abstract" + RTLIL::escape_id(args[argidx]))->derive(design, empty_parameters);
447 top_mod = design->modules_.count(RTLIL::escape_id(args[argidx])) ? design->modules_.at(RTLIL::escape_id(args[argidx])) : NULL;
448 }
449 if (top_mod == NULL)
450 log_cmd_error("Module `%s' not found!\n", args[argidx].c_str());
451 continue;
452 }
453 break;
454 }
455 extra_args(args, argidx, design, false);
456
457 if (generate_mode) {
458 generate(design, generate_cells, generate_ports);
459 return;
460 }
461
462 log_push();
463
464 if (top_mod == NULL)
465 for (auto &mod_it : design->modules_)
466 if (mod_it.second->get_bool_attribute("\\top"))
467 top_mod = mod_it.second;
468
469 if (top_mod != NULL)
470 hierarchy(design, top_mod, purge_lib, true);
471
472 bool did_something = true;
473 bool did_something_once = false;
474 while (did_something) {
475 did_something = false;
476 std::vector<RTLIL::IdString> modnames;
477 modnames.reserve(design->modules_.size());
478 for (auto &mod_it : design->modules_)
479 modnames.push_back(mod_it.first);
480 for (auto &modname : modnames) {
481 if (design->modules_.count(modname) == 0)
482 continue;
483 if (expand_module(design, design->modules_[modname], flag_check, libdirs))
484 did_something = true;
485 }
486 if (did_something)
487 did_something_once = true;
488 }
489
490 if (top_mod != NULL && did_something_once) {
491 log_header("Re-running hierarchy analysis..\n");
492 hierarchy(design, top_mod, purge_lib, false);
493 }
494
495 if (top_mod != NULL) {
496 for (auto &mod_it : design->modules_)
497 if (mod_it.second == top_mod)
498 mod_it.second->attributes["\\top"] = RTLIL::Const(1);
499 else
500 mod_it.second->attributes.erase("\\top");
501 }
502
503 if (!nokeep_asserts) {
504 std::map<RTLIL::Module*, bool> cache;
505 for (auto mod : design->modules())
506 if (set_keep_assert(cache, mod)) {
507 log("Module %s directly or indirectly contains $assert cells -> setting \"keep\" attribute.\n", log_id(mod));
508 mod->set_bool_attribute("\\keep");
509 }
510 }
511
512 if (!keep_positionals)
513 {
514 std::set<RTLIL::Module*> pos_mods;
515 std::map<std::pair<RTLIL::Module*,int>, RTLIL::IdString> pos_map;
516 std::vector<std::pair<RTLIL::Module*,RTLIL::Cell*>> pos_work;
517
518 for (auto &mod_it : design->modules_)
519 for (auto &cell_it : mod_it.second->cells_) {
520 RTLIL::Cell *cell = cell_it.second;
521 if (design->modules_.count(cell->type) == 0)
522 continue;
523 for (auto &conn : cell->connections())
524 if (conn.first[0] == '$' && '0' <= conn.first[1] && conn.first[1] <= '9') {
525 pos_mods.insert(design->modules_.at(cell->type));
526 pos_work.push_back(std::pair<RTLIL::Module*,RTLIL::Cell*>(mod_it.second, cell));
527 break;
528 }
529 }
530
531 for (auto module : pos_mods)
532 for (auto &wire_it : module->wires_) {
533 RTLIL::Wire *wire = wire_it.second;
534 if (wire->port_id > 0)
535 pos_map[std::pair<RTLIL::Module*,int>(module, wire->port_id)] = wire->name;
536 }
537
538 for (auto &work : pos_work) {
539 RTLIL::Module *module = work.first;
540 RTLIL::Cell *cell = work.second;
541 log("Mapping positional arguments of cell %s.%s (%s).\n",
542 RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
543 std::map<RTLIL::IdString, RTLIL::SigSpec> new_connections;
544 for (auto &conn : cell->connections())
545 if (conn.first[0] == '$' && '0' <= conn.first[1] && conn.first[1] <= '9') {
546 int id = atoi(conn.first.c_str()+1);
547 std::pair<RTLIL::Module*,int> key(design->modules_.at(cell->type), id);
548 if (pos_map.count(key) == 0) {
549 log(" Failed to map positional argument %d of cell %s.%s (%s).\n",
550 id, RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
551 new_connections[conn.first] = conn.second;
552 } else
553 new_connections[pos_map.at(key)] = conn.second;
554 } else
555 new_connections[conn.first] = conn.second;
556 cell->connections_ = new_connections;
557 }
558 }
559
560 log_pop();
561 }
562 } HierarchyPass;
563
564 PRIVATE_NAMESPACE_END