Use easyer-to-read unoptimized ceil_log2()
[yosys.git] / kernel / yosys.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/celltypes.h"
22
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
26 #endif
27
28 #ifdef YOSYS_ENABLE_PLUGINS
29 # include <dlfcn.h>
30 #endif
31
32 #ifdef _WIN32
33 # include <windows.h>
34 # include <io.h>
35 #elif defined(__APPLE__)
36 # include <mach-o/dyld.h>
37 # include <unistd.h>
38 # include <dirent.h>
39 # include <sys/stat.h>
40 #else
41 # include <unistd.h>
42 # include <dirent.h>
43 # include <sys/types.h>
44 # include <sys/stat.h>
45 #endif
46
47 #include <limits.h>
48 #include <errno.h>
49
50 YOSYS_NAMESPACE_BEGIN
51
52 int autoidx = 1;
53 int yosys_xtrace = 0;
54 RTLIL::Design *yosys_design = NULL;
55 CellTypes yosys_celltypes;
56
57 #ifdef YOSYS_ENABLE_TCL
58 Tcl_Interp *yosys_tcl_interp = NULL;
59 #endif
60
61 bool memhasher_active = false;
62 uint32_t memhasher_rng = 123456;
63 std::vector<void*> memhasher_store;
64
65 void memhasher_on()
66 {
67 #ifdef __linux__
68 memhasher_rng += time(NULL) << 16 ^ getpid();
69 #endif
70 memhasher_store.resize(0x10000);
71 memhasher_active = true;
72 }
73
74 void memhasher_off()
75 {
76 for (auto p : memhasher_store)
77 if (p) free(p);
78 memhasher_store.clear();
79 memhasher_active = false;
80 }
81
82 void memhasher_do()
83 {
84 memhasher_rng ^= memhasher_rng << 13;
85 memhasher_rng ^= memhasher_rng >> 17;
86 memhasher_rng ^= memhasher_rng << 5;
87
88 int size, index = (memhasher_rng >> 4) & 0xffff;
89 switch (memhasher_rng & 7) {
90 case 0: size = 16; break;
91 case 1: size = 256; break;
92 case 2: size = 1024; break;
93 case 3: size = 4096; break;
94 default: size = 0;
95 }
96 if (index < 16) size *= 16;
97 memhasher_store[index] = realloc(memhasher_store[index], size);
98 }
99
100 void yosys_banner()
101 {
102 log("\n");
103 log(" /----------------------------------------------------------------------------\\\n");
104 log(" | |\n");
105 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
106 log(" | |\n");
107 log(" | Copyright (C) 2012 - 2015 Clifford Wolf <clifford@clifford.at> |\n");
108 log(" | |\n");
109 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
110 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
111 log(" | copyright notice and this permission notice appear in all copies. |\n");
112 log(" | |\n");
113 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
114 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
115 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
116 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
117 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
118 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
119 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
120 log(" | |\n");
121 log(" \\----------------------------------------------------------------------------/\n");
122 log("\n");
123 log(" %s\n", yosys_version_str);
124 log("\n");
125 }
126
127 int ceil_log2(int x)
128 {
129 if (x <= 0)
130 return 0;
131
132 for (int i = 0; i < 32; i++)
133 if (((x-1) >> i) == 0)
134 return i;
135
136 log_abort();
137 }
138
139 std::string stringf(const char *fmt, ...)
140 {
141 std::string string;
142 va_list ap;
143
144 va_start(ap, fmt);
145 string = vstringf(fmt, ap);
146 va_end(ap);
147
148 return string;
149 }
150
151 std::string vstringf(const char *fmt, va_list ap)
152 {
153 std::string string;
154 char *str = NULL;
155
156 #ifdef _WIN32
157 int sz = 64, rc;
158 while (1) {
159 va_list apc;
160 va_copy(apc, ap);
161 str = (char*)realloc(str, sz);
162 rc = vsnprintf(str, sz, fmt, apc);
163 va_end(apc);
164 if (rc >= 0 && rc < sz)
165 break;
166 sz *= 2;
167 }
168 #else
169 if (vasprintf(&str, fmt, ap) < 0)
170 str = NULL;
171 #endif
172
173 if (str != NULL) {
174 string = str;
175 free(str);
176 }
177
178 return string;
179 }
180
181 int readsome(std::istream &f, char *s, int n)
182 {
183 int rc = int(f.readsome(s, n));
184
185 // f.readsome() sometimes returns 0 on a non-empty stream..
186 if (rc == 0) {
187 int c = f.get();
188 if (c != EOF) {
189 *s = c;
190 rc = 1;
191 }
192 }
193
194 return rc;
195 }
196
197 std::string next_token(std::string &text, const char *sep, bool long_strings)
198 {
199 size_t pos_begin = text.find_first_not_of(sep);
200
201 if (pos_begin == std::string::npos)
202 pos_begin = text.size();
203
204 if (long_strings && pos_begin != text.size() && text[pos_begin] == '"') {
205 string sep_string = sep;
206 for (size_t i = pos_begin+1; i < text.size(); i++)
207 if (text[i] == '"' && (i+1 == text.size() || sep_string.find(text[i+1]) != std::string::npos)) {
208 std::string token = text.substr(pos_begin, i-pos_begin+1);
209 text = text.substr(i+1);
210 return token;
211 }
212 }
213
214 size_t pos_end = text.find_first_of(sep, pos_begin);
215
216 if (pos_end == std::string::npos)
217 pos_end = text.size();
218
219 std::string token = text.substr(pos_begin, pos_end-pos_begin);
220 text = text.substr(pos_end);
221 return token;
222 }
223
224 std::vector<std::string> split_tokens(const std::string &text, const char *sep)
225 {
226 std::vector<std::string> tokens;
227 std::string current_token;
228 for (char c : text) {
229 if (strchr(sep, c)) {
230 if (!current_token.empty()) {
231 tokens.push_back(current_token);
232 current_token.clear();
233 }
234 } else
235 current_token += c;
236 }
237 if (!current_token.empty()) {
238 tokens.push_back(current_token);
239 current_token.clear();
240 }
241 return tokens;
242 }
243
244 // this is very similar to fnmatch(). the exact rules used by this
245 // function are:
246 //
247 // ? matches any character except
248 // * matches any sequence of characters
249 // [...] matches any of the characters in the list
250 // [!..] matches any of the characters not in the list
251 //
252 // a backslash may be used to escape the next characters in the
253 // pattern. each special character can also simply match itself.
254 //
255 bool patmatch(const char *pattern, const char *string)
256 {
257 if (*pattern == 0)
258 return *string == 0;
259
260 if (*pattern == '\\') {
261 if (pattern[1] == string[0] && patmatch(pattern+2, string+1))
262 return true;
263 }
264
265 if (*pattern == '?') {
266 if (*string == 0)
267 return false;
268 return patmatch(pattern+1, string+1);
269 }
270
271 if (*pattern == '*') {
272 while (*string) {
273 if (patmatch(pattern+1, string++))
274 return true;
275 }
276 return pattern[1] == 0;
277 }
278
279 if (*pattern == '[') {
280 bool found_match = false;
281 bool inverted_list = pattern[1] == '!';
282 const char *p = pattern + (inverted_list ? 1 : 0);
283
284 while (*++p) {
285 if (*p == ']') {
286 if (found_match != inverted_list && patmatch(p+1, string+1))
287 return true;
288 break;
289 }
290
291 if (*p == '\\') {
292 if (*++p == *string)
293 found_match = true;
294 } else
295 if (*p == *string)
296 found_match = true;
297 }
298 }
299
300 if (*pattern == *string)
301 return patmatch(pattern+1, string+1);
302
303 return false;
304 }
305
306 int run_command(const std::string &command, std::function<void(const std::string&)> process_line)
307 {
308 if (!process_line)
309 return system(command.c_str());
310
311 FILE *f = popen(command.c_str(), "r");
312 if (f == nullptr)
313 return -1;
314
315 std::string line;
316 char logbuf[128];
317 while (fgets(logbuf, 128, f) != NULL) {
318 line += logbuf;
319 if (!line.empty() && line.back() == '\n')
320 process_line(line), line.clear();
321 }
322 if (!line.empty())
323 process_line(line);
324
325 int ret = pclose(f);
326 if (ret < 0)
327 return -1;
328 #ifdef _WIN32
329 return ret;
330 #else
331 return WEXITSTATUS(ret);
332 #endif
333 }
334
335 std::string make_temp_file(std::string template_str)
336 {
337 #ifdef _WIN32
338 if (template_str.rfind("/tmp/", 0) == 0) {
339 # ifdef __MINGW32__
340 char longpath[MAX_PATH + 1];
341 char shortpath[MAX_PATH + 1];
342 # else
343 WCHAR longpath[MAX_PATH + 1];
344 TCHAR shortpath[MAX_PATH + 1];
345 # endif
346 if (!GetTempPath(MAX_PATH+1, longpath))
347 log_error("GetTempPath() failed.\n");
348 if (!GetShortPathName(longpath, shortpath, MAX_PATH + 1))
349 log_error("GetShortPathName() failed.\n");
350 std::string path;
351 for (int i = 0; shortpath[i]; i++)
352 path += char(shortpath[i]);
353 template_str = stringf("%s\\%s", path.c_str(), template_str.c_str() + 5);
354 }
355
356 size_t pos = template_str.rfind("XXXXXX");
357 log_assert(pos != std::string::npos);
358
359 while (1) {
360 for (int i = 0; i < 6; i++) {
361 static std::string y = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
362 static uint32_t x = 314159265 ^ uint32_t(time(NULL));
363 x ^= x << 13, x ^= x >> 17, x ^= x << 5;
364 template_str[pos+i] = y[x % y.size()];
365 }
366 if (_access(template_str.c_str(), 0) != 0)
367 break;
368 }
369 #else
370 size_t pos = template_str.rfind("XXXXXX");
371 log_assert(pos != std::string::npos);
372
373 int suffixlen = GetSize(template_str) - pos - 6;
374
375 char *p = strdup(template_str.c_str());
376 close(mkstemps(p, suffixlen));
377 template_str = p;
378 free(p);
379 #endif
380
381 return template_str;
382 }
383
384 std::string make_temp_dir(std::string template_str)
385 {
386 #ifdef _WIN32
387 template_str = make_temp_file(template_str);
388 mkdir(template_str.c_str());
389 return template_str;
390 #else
391 # ifndef NDEBUG
392 size_t pos = template_str.rfind("XXXXXX");
393 log_assert(pos != std::string::npos);
394
395 int suffixlen = GetSize(template_str) - pos - 6;
396 log_assert(suffixlen == 0);
397 # endif
398
399 char *p = strdup(template_str.c_str());
400 p = mkdtemp(p);
401 log_assert(p != NULL);
402 template_str = p;
403 free(p);
404
405 return template_str;
406 #endif
407 }
408
409 #ifdef _WIN32
410 bool check_file_exists(std::string filename, bool)
411 {
412 return _access(filename.c_str(), 0) == 0;
413 }
414 #else
415 bool check_file_exists(std::string filename, bool is_exec)
416 {
417 return access(filename.c_str(), is_exec ? X_OK : F_OK) == 0;
418 }
419 #endif
420
421 bool is_absolute_path(std::string filename)
422 {
423 #ifdef _WIN32
424 return filename[0] == '/' || filename[0] == '\\' || (filename[0] != 0 && filename[1] == ':');
425 #else
426 return filename[0] == '/';
427 #endif
428 }
429
430 void remove_directory(std::string dirname)
431 {
432 #ifdef _WIN32
433 run_command(stringf("rmdir /s /q \"%s\"", dirname.c_str()));
434 #else
435 struct stat stbuf;
436 struct dirent **namelist;
437 int n = scandir(dirname.c_str(), &namelist, nullptr, alphasort);
438 log_assert(n >= 0);
439 for (int i = 0; i < n; i++) {
440 if (strcmp(namelist[i]->d_name, ".") && strcmp(namelist[i]->d_name, "..")) {
441 std::string buffer = stringf("%s/%s", dirname.c_str(), namelist[i]->d_name);
442 if (!stat(buffer.c_str(), &stbuf) && S_ISREG(stbuf.st_mode)) {
443 remove(buffer.c_str());
444 } else
445 remove_directory(buffer);
446 }
447 free(namelist[i]);
448 }
449 free(namelist);
450 rmdir(dirname.c_str());
451 #endif
452 }
453
454 int GetSize(RTLIL::Wire *wire)
455 {
456 return wire->width;
457 }
458
459 void yosys_setup()
460 {
461 // if there are already IdString objects then we have a global initialization order bug
462 IdString empty_id;
463 log_assert(empty_id.index_ == 0);
464 IdString::get_reference(empty_id.index_);
465
466 Pass::init_register();
467 yosys_design = new RTLIL::Design;
468 yosys_celltypes.setup();
469 log_push();
470 }
471
472 void yosys_shutdown()
473 {
474 log_pop();
475
476 delete yosys_design;
477 yosys_design = NULL;
478
479 for (auto f : log_files)
480 if (f != stderr)
481 fclose(f);
482 log_errfile = NULL;
483 log_files.clear();
484
485 Pass::done_register();
486 yosys_celltypes.clear();
487
488 #ifdef YOSYS_ENABLE_TCL
489 if (yosys_tcl_interp != NULL) {
490 Tcl_DeleteInterp(yosys_tcl_interp);
491 Tcl_Finalize();
492 yosys_tcl_interp = NULL;
493 }
494 #endif
495
496 #ifdef YOSYS_ENABLE_PLUGINS
497 for (auto &it : loaded_plugins)
498 dlclose(it.second);
499
500 loaded_plugins.clear();
501 loaded_plugin_aliases.clear();
502 #endif
503
504 IdString empty_id;
505 IdString::put_reference(empty_id.index_);
506 }
507
508 RTLIL::IdString new_id(std::string file, int line, std::string func)
509 {
510 #ifdef _WIN32
511 size_t pos = file.find_last_of("/\\");
512 #else
513 size_t pos = file.find_last_of('/');
514 #endif
515 if (pos != std::string::npos)
516 file = file.substr(pos+1);
517
518 pos = func.find_last_of(':');
519 if (pos != std::string::npos)
520 func = func.substr(pos+1);
521
522 return stringf("$auto$%s:%d:%s$%d", file.c_str(), line, func.c_str(), autoidx++);
523 }
524
525 RTLIL::Design *yosys_get_design()
526 {
527 return yosys_design;
528 }
529
530 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
531 {
532 static char buffer[100];
533 std::string str = "\n";
534 if (recursion_counter > 1)
535 str += stringf("(%d) ", recursion_counter);
536 str += "yosys";
537 if (!design->selected_active_module.empty())
538 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
539 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
540 if (design->selected_active_module.empty())
541 str += "*";
542 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
543 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
544 str += "*";
545 }
546 snprintf(buffer, 100, "%s> ", str.c_str());
547 return buffer;
548 }
549
550 void rewrite_filename(std::string &filename)
551 {
552 if (filename.substr(0, 1) == "\"" && filename.substr(GetSize(filename)-1) == "\"")
553 filename = filename.substr(1, GetSize(filename)-2);
554 if (filename.substr(0, 2) == "+/")
555 filename = proc_share_dirname() + filename.substr(2);
556 }
557
558 #ifdef YOSYS_ENABLE_TCL
559 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
560 {
561 std::vector<std::string> args;
562 for (int i = 1; i < argc; i++)
563 args.push_back(argv[i]);
564
565 if (args.size() >= 1 && args[0] == "-import") {
566 for (auto &it : pass_register) {
567 std::string tcl_command_name = it.first;
568 if (tcl_command_name == "proc")
569 tcl_command_name = "procs";
570 Tcl_CmdInfo info;
571 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
572 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
573 } else {
574 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
575 Tcl_Eval(interp, tcl_script.c_str());
576 }
577 }
578 return TCL_OK;
579 }
580
581 if (args.size() == 1) {
582 Pass::call(yosys_get_design(), args[0]);
583 return TCL_OK;
584 }
585
586 Pass::call(yosys_get_design(), args);
587 return TCL_OK;
588 }
589
590 extern Tcl_Interp *yosys_get_tcl_interp()
591 {
592 if (yosys_tcl_interp == NULL) {
593 yosys_tcl_interp = Tcl_CreateInterp();
594 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
595 }
596 return yosys_tcl_interp;
597 }
598
599 struct TclPass : public Pass {
600 TclPass() : Pass("tcl", "execute a TCL script file") { }
601 virtual void help() {
602 log("\n");
603 log(" tcl <filename>\n");
604 log("\n");
605 log("This command executes the tcl commands in the specified file.\n");
606 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
607 log("\n");
608 log("The tcl command 'yosys -import' can be used to import all yosys\n");
609 log("commands directly as tcl commands to the tcl shell. The yosys\n");
610 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
611 log("to avoid a name collision with the tcl builtin command 'proc'.\n");
612 log("\n");
613 }
614 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
615 if (args.size() < 2)
616 log_cmd_error("Missing script file.\n");
617 if (args.size() > 2)
618 extra_args(args, 1, design, false);
619 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
620 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
621 }
622 } TclPass;
623 #endif
624
625 #if defined(__linux__)
626 std::string proc_self_dirname()
627 {
628 char path[PATH_MAX];
629 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
630 if (buflen < 0) {
631 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
632 }
633 while (buflen > 0 && path[buflen-1] != '/')
634 buflen--;
635 return std::string(path, buflen);
636 }
637 #elif defined(__APPLE__)
638 std::string proc_self_dirname()
639 {
640 char *path = NULL;
641 uint32_t buflen = 0;
642 while (_NSGetExecutablePath(path, &buflen) != 0)
643 path = (char *) realloc((void *) path, buflen);
644 while (buflen > 0 && path[buflen-1] != '/')
645 buflen--;
646 return std::string(path, buflen);
647 }
648 #elif defined(_WIN32)
649 std::string proc_self_dirname()
650 {
651 int i = 0;
652 # ifdef __MINGW32__
653 char longpath[MAX_PATH + 1];
654 char shortpath[MAX_PATH + 1];
655 # else
656 WCHAR longpath[MAX_PATH + 1];
657 TCHAR shortpath[MAX_PATH + 1];
658 # endif
659 if (!GetModuleFileName(0, longpath, MAX_PATH+1))
660 log_error("GetModuleFileName() failed.\n");
661 if (!GetShortPathName(longpath, shortpath, MAX_PATH+1))
662 log_error("GetShortPathName() failed.\n");
663 while (shortpath[i] != 0)
664 i++;
665 while (i > 0 && shortpath[i-1] != '/' && shortpath[i-1] != '\\')
666 shortpath[--i] = 0;
667 std::string path;
668 for (i = 0; shortpath[i]; i++)
669 path += char(shortpath[i]);
670 return path;
671 }
672 #elif defined(EMSCRIPTEN)
673 std::string proc_self_dirname()
674 {
675 return "/";
676 }
677 #else
678 #error Dont know how to determine process executable base path!
679 #endif
680
681 #ifdef EMSCRIPTEN
682 std::string proc_share_dirname()
683 {
684 return "/share";
685 }
686 #else
687 std::string proc_share_dirname()
688 {
689 std::string proc_self_path = proc_self_dirname();
690 # ifdef _WIN32
691 std::string proc_share_path = proc_self_path + "share\\";
692 if (check_file_exists(proc_share_path, true))
693 return proc_share_path;
694 proc_share_path = proc_self_path + "..\\share\\";
695 if (check_file_exists(proc_share_path, true))
696 return proc_share_path;
697 # else
698 std::string proc_share_path = proc_self_path + "share/";
699 if (check_file_exists(proc_share_path, true))
700 return proc_share_path;
701 proc_share_path = proc_self_path + "../share/yosys/";
702 if (check_file_exists(proc_share_path, true))
703 return proc_share_path;
704 # endif
705 log_error("proc_share_dirname: unable to determine share/ directory!\n");
706 }
707 #endif
708
709 bool fgetline(FILE *f, std::string &buffer)
710 {
711 buffer = "";
712 char block[4096];
713 while (1) {
714 if (fgets(block, 4096, f) == NULL)
715 return false;
716 buffer += block;
717 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
718 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
719 buffer.resize(buffer.size()-1);
720 return true;
721 }
722 }
723 }
724
725 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
726 {
727 int pos = 0;
728 std::string label;
729
730 while (pos < GetSize(command) && (command[pos] == ' ' || command[pos] == '\t'))
731 pos++;
732
733 if (pos < GetSize(command) && command[pos] == '#')
734 return;
735
736 while (pos < GetSize(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
737 label += command[pos++];
738
739 if (label.back() == ':' && GetSize(label) > 1)
740 {
741 label = label.substr(0, GetSize(label)-1);
742 command = command.substr(pos);
743
744 if (label == run_from)
745 from_to_active = true;
746 else if (label == run_to || (run_from == run_to && !run_from.empty()))
747 from_to_active = false;
748 }
749 }
750
751 void run_frontend(std::string filename, std::string command, std::string *backend_command, std::string *from_to_label, RTLIL::Design *design)
752 {
753 if (design == nullptr)
754 design = yosys_design;
755
756 if (command == "auto") {
757 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
758 command = "verilog";
759 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
760 command = "verilog -sv";
761 else if (filename.size() > 4 && filename.substr(filename.size()-5) == ".blif")
762 command = "blif";
763 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
764 command = "ilang";
765 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
766 command = "script";
767 else if (filename == "-")
768 command = "script";
769 else
770 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
771 }
772
773 if (command == "script")
774 {
775 std::string run_from, run_to;
776 bool from_to_active = true;
777
778 if (from_to_label != NULL) {
779 size_t pos = from_to_label->find(':');
780 if (pos == std::string::npos) {
781 run_from = *from_to_label;
782 run_to = *from_to_label;
783 } else {
784 run_from = from_to_label->substr(0, pos);
785 run_to = from_to_label->substr(pos+1);
786 }
787 from_to_active = run_from.empty();
788 }
789
790 log("\n-- Executing script file `%s' --\n", filename.c_str());
791
792 FILE *f = stdin;
793
794 if (filename != "-")
795 f = fopen(filename.c_str(), "r");
796
797 if (f == NULL)
798 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
799
800 FILE *backup_script_file = Frontend::current_script_file;
801 Frontend::current_script_file = f;
802
803 try {
804 std::string command;
805 while (fgetline(f, command)) {
806 while (!command.empty() && command[command.size()-1] == '\\') {
807 std::string next_line;
808 if (!fgetline(f, next_line))
809 break;
810 command.resize(command.size()-1);
811 command += next_line;
812 }
813 handle_label(command, from_to_active, run_from, run_to);
814 if (from_to_active)
815 Pass::call(design, command);
816 }
817
818 if (!command.empty()) {
819 handle_label(command, from_to_active, run_from, run_to);
820 if (from_to_active)
821 Pass::call(design, command);
822 }
823 }
824 catch (...) {
825 Frontend::current_script_file = backup_script_file;
826 throw;
827 }
828
829 Frontend::current_script_file = backup_script_file;
830
831 if (filename != "-")
832 fclose(f);
833
834 if (backend_command != NULL && *backend_command == "auto")
835 *backend_command = "";
836
837 return;
838 }
839
840 if (filename == "-") {
841 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
842 } else {
843 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
844 }
845
846 Frontend::frontend_call(design, NULL, filename, command);
847 }
848
849 void run_frontend(std::string filename, std::string command, RTLIL::Design *design)
850 {
851 run_frontend(filename, command, nullptr, nullptr, design);
852 }
853
854 void run_pass(std::string command, RTLIL::Design *design)
855 {
856 if (design == nullptr)
857 design = yosys_design;
858
859 log("\n-- Running command `%s' --\n", command.c_str());
860
861 Pass::call(design, command);
862 }
863
864 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
865 {
866 if (design == nullptr)
867 design = yosys_design;
868
869 if (command == "auto") {
870 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
871 command = "verilog";
872 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
873 command = "ilang";
874 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
875 command = "blif";
876 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".edif")
877 command = "edif";
878 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".json")
879 command = "json";
880 else if (filename == "-")
881 command = "ilang";
882 else if (filename.empty())
883 return;
884 else
885 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
886 }
887
888 if (filename.empty())
889 filename = "-";
890
891 if (filename == "-") {
892 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
893 } else {
894 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
895 }
896
897 Backend::backend_call(design, NULL, filename, command);
898 }
899
900 #ifdef YOSYS_ENABLE_READLINE
901 static char *readline_cmd_generator(const char *text, int state)
902 {
903 static std::map<std::string, Pass*>::iterator it;
904 static int len;
905
906 if (!state) {
907 it = pass_register.begin();
908 len = strlen(text);
909 }
910
911 for (; it != pass_register.end(); it++) {
912 if (it->first.substr(0, len) == text)
913 return strdup((it++)->first.c_str());
914 }
915 return NULL;
916 }
917
918 static char *readline_obj_generator(const char *text, int state)
919 {
920 static std::vector<char*> obj_names;
921 static size_t idx;
922
923 if (!state)
924 {
925 idx = 0;
926 obj_names.clear();
927
928 RTLIL::Design *design = yosys_get_design();
929 int len = strlen(text);
930
931 if (design->selected_active_module.empty())
932 {
933 for (auto &it : design->modules_)
934 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
935 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
936 }
937 else
938 if (design->modules_.count(design->selected_active_module) > 0)
939 {
940 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
941
942 for (auto &it : module->wires_)
943 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
944 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
945
946 for (auto &it : module->memories)
947 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
948 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
949
950 for (auto &it : module->cells_)
951 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
952 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
953
954 for (auto &it : module->processes)
955 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
956 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
957 }
958
959 std::sort(obj_names.begin(), obj_names.end());
960 }
961
962 if (idx < obj_names.size())
963 return strdup(obj_names[idx++]);
964
965 idx = 0;
966 obj_names.clear();
967 return NULL;
968 }
969
970 static char **readline_completion(const char *text, int start, int)
971 {
972 if (start == 0)
973 return rl_completion_matches(text, readline_cmd_generator);
974 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
975 return rl_completion_matches(text, readline_obj_generator);
976 return NULL;
977 }
978 #endif
979
980 void shell(RTLIL::Design *design)
981 {
982 static int recursion_counter = 0;
983
984 recursion_counter++;
985 log_cmd_error_throw = true;
986
987 #ifdef YOSYS_ENABLE_READLINE
988 rl_readline_name = "yosys";
989 rl_attempted_completion_function = readline_completion;
990 rl_basic_word_break_characters = " \t\n";
991 #endif
992
993 char *command = NULL;
994 #ifdef YOSYS_ENABLE_READLINE
995 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
996 {
997 #else
998 char command_buffer[4096];
999 while (1)
1000 {
1001 fputs(create_prompt(design, recursion_counter), stdout);
1002 fflush(stdout);
1003 if ((command = fgets(command_buffer, 4096, stdin)) == NULL)
1004 break;
1005 #endif
1006 if (command[strspn(command, " \t\r\n")] == 0)
1007 continue;
1008 #ifdef YOSYS_ENABLE_READLINE
1009 add_history(command);
1010 #endif
1011
1012 char *p = command + strspn(command, " \t\r\n");
1013 if (!strncmp(p, "exit", 4)) {
1014 p += 4;
1015 p += strspn(p, " \t\r\n");
1016 if (*p == 0)
1017 break;
1018 }
1019
1020 try {
1021 log_assert(design->selection_stack.size() == 1);
1022 Pass::call(design, command);
1023 } catch (log_cmd_error_exception) {
1024 while (design->selection_stack.size() > 1)
1025 design->selection_stack.pop_back();
1026 log_reset_stack();
1027 }
1028 }
1029 if (command == NULL)
1030 printf("exit\n");
1031
1032 recursion_counter--;
1033 log_cmd_error_throw = false;
1034 }
1035
1036 struct ShellPass : public Pass {
1037 ShellPass() : Pass("shell", "enter interactive command mode") { }
1038 virtual void help() {
1039 log("\n");
1040 log(" shell\n");
1041 log("\n");
1042 log("This command enters the interactive command mode. This can be useful\n");
1043 log("in a script to interrupt the script at a certain point and allow for\n");
1044 log("interactive inspection or manual synthesis of the design at this point.\n");
1045 log("\n");
1046 log("The command prompt of the interactive shell indicates the current\n");
1047 log("selection (see 'help select'):\n");
1048 log("\n");
1049 log(" yosys>\n");
1050 log(" the entire design is selected\n");
1051 log("\n");
1052 log(" yosys*>\n");
1053 log(" only part of the design is selected\n");
1054 log("\n");
1055 log(" yosys [modname]>\n");
1056 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1057 log("\n");
1058 log(" yosys [modname]*>\n");
1059 log(" only part of current module 'modname' is selected\n");
1060 log("\n");
1061 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1062 log("do not terminate yosys but return to the command prompt.\n");
1063 log("\n");
1064 log("This command is the default action if nothing else has been specified\n");
1065 log("on the command line.\n");
1066 log("\n");
1067 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1068 log("\n");
1069 }
1070 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
1071 extra_args(args, 1, design, false);
1072 shell(design);
1073 }
1074 } ShellPass;
1075
1076 #ifdef YOSYS_ENABLE_READLINE
1077 struct HistoryPass : public Pass {
1078 HistoryPass() : Pass("history", "show last interactive commands") { }
1079 virtual void help() {
1080 log("\n");
1081 log(" history\n");
1082 log("\n");
1083 log("This command prints all commands in the shell history buffer. This are\n");
1084 log("all commands executed in an interactive session, but not the commands\n");
1085 log("from executed scripts.\n");
1086 log("\n");
1087 }
1088 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
1089 extra_args(args, 1, design, false);
1090 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
1091 log("%s\n", (*list)->line);
1092 }
1093 } HistoryPass;
1094 #endif
1095
1096 struct ScriptPass : public Pass {
1097 ScriptPass() : Pass("script", "execute commands from script file") { }
1098 virtual void help() {
1099 log("\n");
1100 log(" script <filename> [<from_label>:<to_label>]\n");
1101 log("\n");
1102 log("This command executes the yosys commands in the specified file.\n");
1103 log("\n");
1104 log("The 2nd argument can be used to only execute the section of the\n");
1105 log("file between the specified labels. An empty from label is synonymous\n");
1106 log("for the beginning of the file and an empty to label is synonymous\n");
1107 log("for the end of the file.\n");
1108 log("\n");
1109 log("If only one label is specified (without ':') then only the block\n");
1110 log("marked with that label (until the next label) is executed.\n");
1111 log("\n");
1112 }
1113 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
1114 if (args.size() < 2)
1115 log_cmd_error("Missing script file.\n");
1116 else if (args.size() == 2)
1117 run_frontend(args[1], "script", design);
1118 else if (args.size() == 3)
1119 run_frontend(args[1], "script", NULL, &args[2], design);
1120 else
1121 extra_args(args, 2, design, false);
1122 }
1123 } ScriptPass;
1124
1125 YOSYS_NAMESPACE_END
1126