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