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