Merge pull request #562 from udif/pr_fix_illegal_port_decl
[yosys.git] / kernel / driver.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 "libs/sha1/sha1.h"
22
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
26 #endif
27
28 #ifdef YOSYS_ENABLE_EDITLINE
29 # include <editline/readline.h>
30 #endif
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <limits.h>
35 #include <errno.h>
36
37 #if defined (__linux__) || defined(__FreeBSD__)
38 # include <sys/resource.h>
39 # include <sys/types.h>
40 # include <unistd.h>
41 #endif
42
43 #ifdef __FreeBSD__
44 # include <sys/sysctl.h>
45 # include <sys/user.h>
46 #endif
47
48 #if !defined(_WIN32) || defined(__MINGW32__)
49 # include <unistd.h>
50 #else
51 char *optarg;
52 int optind = 1, optcur = 1;
53 int getopt(int argc, char **argv, const char *optstring)
54 {
55 if (optind >= argc || argv[optind][0] != '-')
56 return -1;
57
58 bool takes_arg = false;
59 int opt = argv[optind][optcur];
60 for (int i = 0; optstring[i]; i++)
61 if (opt == optstring[i] && optstring[i + 1] == ':')
62 takes_arg = true;
63
64 if (!takes_arg) {
65 if (argv[optind][++optcur] == 0)
66 optind++, optcur = 1;
67 return opt;
68 }
69
70 if (argv[optind][++optcur]) {
71 optarg = argv[optind++] + optcur;
72 optcur = 1;
73 return opt;
74 }
75
76 optarg = argv[++optind];
77 optind++, optcur = 1;
78 return opt;
79 }
80 #endif
81
82
83 USING_YOSYS_NAMESPACE
84
85 #ifdef EMSCRIPTEN
86 # include <sys/stat.h>
87 # include <sys/types.h>
88 # include <emscripten.h>
89
90 extern "C" int main(int, char**);
91 extern "C" void run(const char*);
92 extern "C" const char *errmsg();
93 extern "C" const char *prompt();
94
95 int main(int argc, char **argv)
96 {
97 EM_ASM(
98 if (ENVIRONMENT_IS_NODE)
99 {
100 FS.mkdir('/hostcwd');
101 FS.mount(NODEFS, { root: '.' }, '/hostcwd');
102 FS.mkdir('/hostfs');
103 FS.mount(NODEFS, { root: '/' }, '/hostfs');
104 }
105 );
106
107 mkdir("/work", 0777);
108 chdir("/work");
109 log_files.push_back(stdout);
110 log_error_stderr = true;
111 yosys_banner();
112 yosys_setup();
113
114 if (argc == 2)
115 {
116 // Run the first argument as a script file
117 run_frontend(argv[1], "script", 0, 0, 0);
118 }
119 }
120
121 void run(const char *command)
122 {
123 int selSize = GetSize(yosys_get_design()->selection_stack);
124 try {
125 log_last_error = "Internal error (see JavaScript console for details)";
126 run_pass(command);
127 log_last_error = "";
128 } catch (...) {
129 while (GetSize(yosys_get_design()->selection_stack) > selSize)
130 yosys_get_design()->selection_stack.pop_back();
131 throw;
132 }
133 }
134
135 const char *errmsg()
136 {
137 return log_last_error.c_str();
138 }
139
140 const char *prompt()
141 {
142 const char *p = create_prompt(yosys_get_design(), 0);
143 while (*p == '\n') p++;
144 return p;
145 }
146
147 #else /* EMSCRIPTEN */
148
149 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
150 int yosys_history_offset = 0;
151 std::string yosys_history_file;
152 #endif
153
154 void yosys_atexit()
155 {
156 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
157 if (!yosys_history_file.empty()) {
158 #if defined(YOSYS_ENABLE_READLINE)
159 if (yosys_history_offset > 0) {
160 history_truncate_file(yosys_history_file.c_str(), 100);
161 append_history(where_history() - yosys_history_offset, yosys_history_file.c_str());
162 } else
163 write_history(yosys_history_file.c_str());
164 #else
165 write_history(yosys_history_file.c_str());
166 #endif
167 }
168
169 clear_history();
170 #if defined(YOSYS_ENABLE_READLINE)
171 HIST_ENTRY **hist_list = history_list();
172 if (hist_list != NULL)
173 free(hist_list);
174 #endif
175 #endif
176 }
177
178 int main(int argc, char **argv)
179 {
180 std::string frontend_command = "auto";
181 std::string backend_command = "auto";
182 std::vector<std::string> passes_commands;
183 std::vector<std::string> plugin_filenames;
184 std::string output_filename = "";
185 std::string scriptfile = "";
186 std::string depsfile = "";
187 bool scriptfile_tcl = false;
188 bool got_output_filename = false;
189 bool print_banner = true;
190 bool print_stats = true;
191 bool call_abort = false;
192 bool timing_details = false;
193 bool mode_v = false;
194 bool mode_q = false;
195
196 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
197 if (getenv("HOME") != NULL) {
198 yosys_history_file = stringf("%s/.yosys_history", getenv("HOME"));
199 read_history(yosys_history_file.c_str());
200 yosys_history_offset = where_history();
201 }
202 #endif
203
204 if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-help") || !strcmp(argv[1], "--help")))
205 {
206 printf("\n");
207 printf("Usage: %s [options] [<infile> [..]]\n", argv[0]);
208 printf("\n");
209 printf(" -Q\n");
210 printf(" suppress printing of banner (copyright, disclaimer, version)\n");
211 printf("\n");
212 printf(" -T\n");
213 printf(" suppress printing of footer (log hash, version, timing statistics)\n");
214 printf("\n");
215 printf(" -q\n");
216 printf(" quiet operation. only write warnings and error messages to console\n");
217 printf(" use this option twice to also quiet warning messages\n");
218 printf("\n");
219 printf(" -v <level>\n");
220 printf(" print log headers up to level <level> to the console. (this\n");
221 printf(" implies -q for everything except the 'End of script.' message.)\n");
222 printf("\n");
223 printf(" -t\n");
224 printf(" annotate all log messages with a time stamp\n");
225 printf("\n");
226 printf(" -d\n");
227 printf(" print more detailed timing stats at exit\n");
228 printf("\n");
229 printf(" -l logfile\n");
230 printf(" write log messages to the specified file\n");
231 printf("\n");
232 printf(" -L logfile\n");
233 printf(" like -l but open log file in line buffered mode\n");
234 printf("\n");
235 printf(" -o outfile\n");
236 printf(" write the design to the specified file on exit\n");
237 printf("\n");
238 printf(" -b backend\n");
239 printf(" use this backend for the output file specified on the command line\n");
240 printf("\n");
241 printf(" -f frontend\n");
242 printf(" use the specified frontend for the input files on the command line\n");
243 printf("\n");
244 printf(" -H\n");
245 printf(" print the command list\n");
246 printf("\n");
247 printf(" -h command\n");
248 printf(" print the help message for the specified command\n");
249 printf("\n");
250 printf(" -s scriptfile\n");
251 printf(" execute the commands in the script file\n");
252 printf("\n");
253 printf(" -c tcl_scriptfile\n");
254 printf(" execute the commands in the tcl script file (see 'help tcl' for details)\n");
255 printf("\n");
256 printf(" -p command\n");
257 printf(" execute the commands\n");
258 printf("\n");
259 printf(" -m module_file\n");
260 printf(" load the specified module (aka plugin)\n");
261 printf("\n");
262 printf(" -X\n");
263 printf(" enable tracing of core data structure changes. for debugging\n");
264 printf("\n");
265 printf(" -M\n");
266 printf(" will slightly randomize allocated pointer addresses. for debugging\n");
267 printf("\n");
268 printf(" -A\n");
269 printf(" will call abort() at the end of the script. for debugging\n");
270 printf("\n");
271 printf(" -D <header_id>[:<filename>]\n");
272 printf(" dump the design when printing the specified log header to a file.\n");
273 printf(" yosys_dump_<header_id>.il is used as filename if none is specified.\n");
274 printf(" Use 'ALL' as <header_id> to dump at every header.\n");
275 printf("\n");
276 printf(" -W regex\n");
277 printf(" print a warning for all log messages matching the regex.\n");
278 printf("\n");
279 printf(" -w regex\n");
280 printf(" if a warning message matches the regex, it is printed as regular\n");
281 printf(" message instead.\n");
282 printf("\n");
283 printf(" -e regex\n");
284 printf(" if a warning message matches the regex, it is printed as error\n");
285 printf(" message instead and the tool terminates with a nonzero return code.\n");
286 printf("\n");
287 printf(" -E <depsfile>\n");
288 printf(" write a Makefile dependencies file with in- and output file names\n");
289 printf("\n");
290 printf(" -V\n");
291 printf(" print version information and exit\n");
292 printf("\n");
293 printf("The option -S is an shortcut for calling the \"synth\" command, a default\n");
294 printf("script for transforming the Verilog input to a gate-level netlist. For example:\n");
295 printf("\n");
296 printf(" yosys -o output.blif -S input.v\n");
297 printf("\n");
298 printf("For more complex synthesis jobs it is recommended to use the read_* and write_*\n");
299 printf("commands in a script file instead of specifying input and output files on the\n");
300 printf("command line.\n");
301 printf("\n");
302 printf("When no commands, script files or input files are specified on the command\n");
303 printf("line, yosys automatically enters the interactive command mode. Use the 'help'\n");
304 printf("command to get information on the individual commands.\n");
305 printf("\n");
306 exit(0);
307 }
308
309 int opt;
310 while ((opt = getopt(argc, argv, "MXAQTVSm:f:Hh:b:o:p:l:L:qv:tds:c:W:w:e:D:E:")) != -1)
311 {
312 switch (opt)
313 {
314 case 'M':
315 memhasher_on();
316 break;
317 case 'X':
318 yosys_xtrace++;
319 break;
320 case 'A':
321 call_abort = true;
322 break;
323 case 'Q':
324 print_banner = false;
325 break;
326 case 'T':
327 print_stats = false;
328 break;
329 case 'V':
330 printf("%s\n", yosys_version_str);
331 exit(0);
332 case 'S':
333 passes_commands.push_back("synth");
334 break;
335 case 'm':
336 plugin_filenames.push_back(optarg);
337 break;
338 case 'f':
339 frontend_command = optarg;
340 break;
341 case 'H':
342 passes_commands.push_back("help");
343 break;
344 case 'h':
345 passes_commands.push_back(stringf("help %s", optarg));
346 break;
347 case 'b':
348 backend_command = optarg;
349 break;
350 case 'p':
351 passes_commands.push_back(optarg);
352 break;
353 case 'o':
354 output_filename = optarg;
355 got_output_filename = true;
356 break;
357 case 'l':
358 case 'L':
359 log_files.push_back(fopen(optarg, "wt"));
360 if (log_files.back() == NULL) {
361 fprintf(stderr, "Can't open log file `%s' for writing!\n", optarg);
362 exit(1);
363 }
364 if (opt == 'L')
365 setvbuf(log_files.back(), NULL, _IOLBF, 0);
366 break;
367 case 'q':
368 mode_q = true;
369 if (log_errfile == stderr)
370 log_quiet_warnings = true;
371 log_errfile = stderr;
372 break;
373 case 'v':
374 mode_v = true;
375 log_errfile = stderr;
376 log_verbose_level = atoi(optarg);
377 break;
378 case 't':
379 log_time = true;
380 break;
381 case 'd':
382 timing_details = true;
383 break;
384 case 's':
385 scriptfile = optarg;
386 scriptfile_tcl = false;
387 break;
388 case 'c':
389 scriptfile = optarg;
390 scriptfile_tcl = true;
391 break;
392 case 'W':
393 log_warn_regexes.push_back(std::regex(optarg,
394 std::regex_constants::nosubs |
395 std::regex_constants::optimize |
396 std::regex_constants::egrep));
397 break;
398 case 'w':
399 log_nowarn_regexes.push_back(std::regex(optarg,
400 std::regex_constants::nosubs |
401 std::regex_constants::optimize |
402 std::regex_constants::egrep));
403 break;
404 case 'e':
405 log_werror_regexes.push_back(std::regex(optarg,
406 std::regex_constants::nosubs |
407 std::regex_constants::optimize |
408 std::regex_constants::egrep));
409 break;
410 case 'D':
411 {
412 auto args = split_tokens(optarg, ":");
413 if (!args.empty() && args[0] == "ALL") {
414 if (GetSize(args) != 1) {
415 fprintf(stderr, "Invalid number of tokens in -D ALL.\n");
416 exit(1);
417 }
418 log_hdump_all = true;
419 } else {
420 if (!args.empty() && !args[0].empty() && args[0].back() == '.')
421 args[0].pop_back();
422 if (GetSize(args) == 1)
423 args.push_back("yosys_dump_" + args[0] + ".il");
424 if (GetSize(args) != 2) {
425 fprintf(stderr, "Invalid number of tokens in -D.\n");
426 exit(1);
427 }
428 log_hdump[args[0]].insert(args[1]);
429 }
430 }
431 break;
432 case 'E':
433 depsfile = optarg;
434 break;
435 default:
436 fprintf(stderr, "Run '%s -h' for help.\n", argv[0]);
437 exit(1);
438 }
439 }
440
441 if (log_errfile == NULL) {
442 log_files.push_back(stdout);
443 log_error_stderr = true;
444 }
445
446 if (print_banner)
447 yosys_banner();
448
449 if (print_stats)
450 log_hasher = new SHA1;
451
452 #if defined(__linux__)
453 // set stack size to >= 128 MB
454 {
455 struct rlimit rl;
456 const rlim_t stack_size = 128L * 1024L * 1024L;
457 if (getrlimit(RLIMIT_STACK, &rl) == 0 && rl.rlim_cur < stack_size) {
458 rl.rlim_cur = stack_size;
459 setrlimit(RLIMIT_STACK, &rl);
460 }
461 }
462 #endif
463
464 yosys_setup();
465 log_error_atexit = yosys_atexit;
466
467 for (auto &fn : plugin_filenames)
468 load_plugin(fn, {});
469
470 if (optind == argc && passes_commands.size() == 0 && scriptfile.empty()) {
471 if (!got_output_filename)
472 backend_command = "";
473 shell(yosys_design);
474 }
475
476 while (optind < argc)
477 run_frontend(argv[optind++], frontend_command, output_filename == "-" ? &backend_command : NULL);
478
479 if (!scriptfile.empty()) {
480 if (scriptfile_tcl) {
481 #ifdef YOSYS_ENABLE_TCL
482 if (Tcl_EvalFile(yosys_get_tcl_interp(), scriptfile.c_str()) != TCL_OK)
483 log_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
484 #else
485 log_error("Can't exectue TCL script: this version of yosys is not built with TCL support enabled.\n");
486 #endif
487 } else
488 run_frontend(scriptfile, "script", output_filename == "-" ? &backend_command : NULL);
489 }
490
491 for (auto it = passes_commands.begin(); it != passes_commands.end(); it++)
492 run_pass(*it);
493
494 if (!backend_command.empty())
495 run_backend(output_filename, backend_command);
496
497 if (!depsfile.empty())
498 {
499 FILE *f = fopen(depsfile.c_str(), "wt");
500 if (f == nullptr)
501 log_error("Can't open dependencies file for writing: %s\n", strerror(errno));
502 bool first = true;
503 for (auto fn : yosys_output_files) {
504 fprintf(f, "%s%s", first ? "" : " ", fn.c_str());
505 first = false;
506 }
507 fprintf(f, ":");
508 for (auto fn : yosys_input_files) {
509 if (yosys_output_files.count(fn) == 0)
510 fprintf(f, " %s", fn.c_str());
511 }
512 fprintf(f, "\n");
513 }
514
515 if (print_stats)
516 {
517 std::string hash = log_hasher->final().substr(0, 10);
518 delete log_hasher;
519 log_hasher = nullptr;
520
521 log_time = false;
522 yosys_xtrace = 0;
523 log_spacer();
524
525 if (mode_v && !mode_q)
526 log_files.push_back(stderr);
527
528 if (log_warnings_count)
529 log("Warnings: %d unique messages, %d total\n", GetSize(log_warnings), log_warnings_count);
530 #ifdef _WIN32
531 log("End of script. Logfile hash: %s\n", hash.c_str());
532 #else
533 std::string meminfo;
534 std::string stats_divider = ", ";
535 # if defined(__linux__)
536 std::ifstream statm;
537 statm.open(stringf("/proc/%lld/statm", (long long)getpid()));
538 if (statm.is_open()) {
539 int sz_total, sz_resident;
540 statm >> sz_total >> sz_resident;
541 meminfo = stringf(", MEM: %.2f MB total, %.2f MB resident",
542 sz_total * (getpagesize() / 1024.0 / 1024.0),
543 sz_resident * (getpagesize() / 1024.0 / 1024.0));
544 stats_divider = "\n";
545 }
546 # elif defined(__FreeBSD__)
547 pid_t pid = getpid();
548 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid};
549 struct kinfo_proc kip;
550 size_t kip_len = sizeof(kip);
551 if (sysctl(mib, 4, &kip, &kip_len, NULL, 0) == 0) {
552 vm_size_t sz_total = kip.ki_size;
553 segsz_t sz_resident = kip.ki_rssize;
554 meminfo = stringf(", MEM: %.2f MB total, %.2f MB resident",
555 (int)sz_total / 1024.0 / 1024.0,
556 (int)sz_resident * (getpagesize() / 1024.0 / 1024.0));
557 stats_divider = "\n";
558 }
559 # endif
560
561 struct rusage ru_buffer;
562 getrusage(RUSAGE_SELF, &ru_buffer);
563 log("End of script. Logfile hash: %s%sCPU: user %.2fs system %.2fs%s\n", hash.c_str(),
564 stats_divider.c_str(), ru_buffer.ru_utime.tv_sec + 1e-6 * ru_buffer.ru_utime.tv_usec,
565 ru_buffer.ru_stime.tv_sec + 1e-6 * ru_buffer.ru_stime.tv_usec, meminfo.c_str());
566 #endif
567 log("%s\n", yosys_version_str);
568
569 int64_t total_ns = 0;
570 std::set<tuple<int64_t, int, std::string>> timedat;
571
572 for (auto &it : pass_register)
573 if (it.second->call_counter) {
574 total_ns += it.second->runtime_ns + 1;
575 timedat.insert(make_tuple(it.second->runtime_ns + 1, it.second->call_counter, it.first));
576 }
577
578 if (timing_details)
579 {
580 log("Time spent:\n");
581 for (auto it = timedat.rbegin(); it != timedat.rend(); it++) {
582 log("%5d%% %5d calls %8.3f sec %s\n", int(100*std::get<0>(*it) / total_ns),
583 std::get<1>(*it), std::get<0>(*it) / 1000000000.0, std::get<2>(*it).c_str());
584 }
585 }
586 else
587 {
588 int out_count = 0;
589 log("Time spent:");
590 for (auto it = timedat.rbegin(); it != timedat.rend() && out_count < 4; it++, out_count++) {
591 if (out_count >= 2 && (std::get<0>(*it) < 1000000000 || int(100*std::get<0>(*it) / total_ns) < 20)) {
592 log(", ...");
593 break;
594 }
595 log("%s %d%% %dx %s (%d sec)", out_count ? "," : "", int(100*std::get<0>(*it) / total_ns),
596 std::get<1>(*it), std::get<2>(*it).c_str(), int(std::get<0>(*it) / 1000000000));
597 }
598 log("%s\n", out_count ? "" : " no commands executed");
599 }
600 }
601
602 #if defined(YOSYS_ENABLE_COVER) && (defined(__linux__) || defined(__FreeBSD__))
603 if (getenv("YOSYS_COVER_DIR") || getenv("YOSYS_COVER_FILE"))
604 {
605 string filename;
606 FILE *f;
607
608 if (getenv("YOSYS_COVER_DIR")) {
609 filename = stringf("%s/yosys_cover_%d_XXXXXX.txt", getenv("YOSYS_COVER_DIR"), getpid());
610 filename = make_temp_file(filename);
611 } else {
612 filename = getenv("YOSYS_COVER_FILE");
613 }
614
615 f = fopen(filename.c_str(), "a+");
616
617 if (f == NULL)
618 log_error("Can't create coverage file `%s'.\n", filename.c_str());
619
620 log("<writing coverage file \"%s\">\n", filename.c_str());
621
622 for (auto &it : get_coverage_data())
623 fprintf(f, "%-60s %10d %s\n", it.second.first.c_str(), it.second.second, it.first.c_str());
624
625 fclose(f);
626 }
627 #endif
628
629 yosys_atexit();
630
631 memhasher_off();
632 if (call_abort)
633 abort();
634
635 log_flush();
636 #if defined(_MSC_VER)
637 _exit(0);
638 #elif defined(_WIN32)
639 _Exit(0);
640 #endif
641
642 yosys_shutdown();
643
644 return 0;
645 }
646
647 #endif /* EMSCRIPTEN */
648