2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
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.
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.
20 #include "kernel/yosys.h"
21 #include "kernel/celltypes.h"
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
28 #ifdef YOSYS_ENABLE_EDITLINE
29 # include <editline/readline.h>
32 #ifdef YOSYS_ENABLE_PLUGINS
39 #elif defined(__APPLE__)
40 # include <mach-o/dyld.h>
43 # include <sys/stat.h>
47 # include <sys/types.h>
48 # include <sys/wait.h>
49 # include <sys/stat.h>
52 #if !defined(_WIN32) && defined(YOSYS_ENABLE_GLOB)
57 # include <sys/sysctl.h>
61 #if PY_MAJOR_VERSION >= 3
62 # define INIT_MODULE PyInit_libyosys
63 extern "C" PyObject
* INIT_MODULE();
65 # define INIT_MODULE initlibyosys
66 extern "C" void INIT_MODULE();
77 RTLIL::Design
*yosys_design
= NULL
;
78 CellTypes yosys_celltypes
;
80 #ifdef YOSYS_ENABLE_TCL
81 Tcl_Interp
*yosys_tcl_interp
= NULL
;
84 std::set
<std::string
> yosys_input_files
, yosys_output_files
;
86 bool memhasher_active
= false;
87 uint32_t memhasher_rng
= 123456;
88 std::vector
<void*> memhasher_store
;
92 #if defined(__linux__) || defined(__FreeBSD__)
93 memhasher_rng
+= time(NULL
) << 16 ^ getpid();
95 memhasher_store
.resize(0x10000);
96 memhasher_active
= true;
101 for (auto p
: memhasher_store
)
103 memhasher_store
.clear();
104 memhasher_active
= false;
109 memhasher_rng
^= memhasher_rng
<< 13;
110 memhasher_rng
^= memhasher_rng
>> 17;
111 memhasher_rng
^= memhasher_rng
<< 5;
113 int size
, index
= (memhasher_rng
>> 4) & 0xffff;
114 switch (memhasher_rng
& 7) {
115 case 0: size
= 16; break;
116 case 1: size
= 256; break;
117 case 2: size
= 1024; break;
118 case 3: size
= 4096; break;
121 if (index
< 16) size
*= 16;
122 memhasher_store
[index
] = realloc(memhasher_store
[index
], size
);
128 log(" /----------------------------------------------------------------------------\\\n");
130 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
132 log(" | Copyright (C) 2012 - 2019 Clifford Wolf <clifford@clifford.at> |\n");
134 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
135 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
136 log(" | copyright notice and this permission notice appear in all copies. |\n");
138 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
139 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
140 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
141 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
142 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
143 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
144 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
146 log(" \\----------------------------------------------------------------------------/\n");
148 log(" %s\n", yosys_version_str
);
154 #if defined(__GNUC__)
155 return x
> 1 ? (8*sizeof(int)) - __builtin_clz(x
-1) : 0;
159 for (int i
= 0; i
< 32; i
++)
160 if (((x
-1) >> i
) == 0)
166 std::string
stringf(const char *fmt
, ...)
172 string
= vstringf(fmt
, ap
);
178 std::string
vstringf(const char *fmt
, va_list ap
)
183 #if defined(_WIN32 )|| defined(__CYGWIN__)
188 str
= (char*)realloc(str
, sz
);
189 rc
= vsnprintf(str
, sz
, fmt
, apc
);
191 if (rc
>= 0 && rc
< sz
)
196 if (vasprintf(&str
, fmt
, ap
) < 0)
208 int readsome(std::istream
&f
, char *s
, int n
)
210 int rc
= int(f
.readsome(s
, n
));
212 // f.readsome() sometimes returns 0 on a non-empty stream..
224 std::string
next_token(std::string
&text
, const char *sep
, bool long_strings
)
226 size_t pos_begin
= text
.find_first_not_of(sep
);
228 if (pos_begin
== std::string::npos
)
229 pos_begin
= text
.size();
231 if (long_strings
&& pos_begin
!= text
.size() && text
[pos_begin
] == '"') {
232 string sep_string
= sep
;
233 for (size_t i
= pos_begin
+1; i
< text
.size(); i
++) {
234 if (text
[i
] == '"' && (i
+1 == text
.size() || sep_string
.find(text
[i
+1]) != std::string::npos
)) {
235 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
236 text
= text
.substr(i
+1);
239 if (i
+1 < text
.size() && text
[i
] == '"' && text
[i
+1] == ';' && (i
+2 == text
.size() || sep_string
.find(text
[i
+2]) != std::string::npos
)) {
240 std::string token
= text
.substr(pos_begin
, i
-pos_begin
+1);
241 text
= text
.substr(i
+2);
247 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
249 if (pos_end
== std::string::npos
)
250 pos_end
= text
.size();
252 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
253 text
= text
.substr(pos_end
);
257 std::vector
<std::string
> split_tokens(const std::string
&text
, const char *sep
)
259 std::vector
<std::string
> tokens
;
260 std::string current_token
;
261 for (char c
: text
) {
262 if (strchr(sep
, c
)) {
263 if (!current_token
.empty()) {
264 tokens
.push_back(current_token
);
265 current_token
.clear();
270 if (!current_token
.empty()) {
271 tokens
.push_back(current_token
);
272 current_token
.clear();
277 // this is very similar to fnmatch(). the exact rules used by this
280 // ? matches any character except
281 // * matches any sequence of characters
282 // [...] matches any of the characters in the list
283 // [!..] matches any of the characters not in the list
285 // a backslash may be used to escape the next characters in the
286 // pattern. each special character can also simply match itself.
288 bool patmatch(const char *pattern
, const char *string
)
293 if (*pattern
== '\\') {
294 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
298 if (*pattern
== '?') {
301 return patmatch(pattern
+1, string
+1);
304 if (*pattern
== '*') {
306 if (patmatch(pattern
+1, string
++))
309 return pattern
[1] == 0;
312 if (*pattern
== '[') {
313 bool found_match
= false;
314 bool inverted_list
= pattern
[1] == '!';
315 const char *p
= pattern
+ (inverted_list
? 1 : 0);
319 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
333 if (*pattern
== *string
)
334 return patmatch(pattern
+1, string
+1);
339 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
342 return system(command
.c_str());
344 FILE *f
= popen(command
.c_str(), "r");
350 while (fgets(logbuf
, 128, f
) != NULL
) {
352 if (!line
.empty() && line
.back() == '\n')
353 process_line(line
), line
.clear();
364 return WEXITSTATUS(ret
);
368 std::string
make_temp_file(std::string template_str
)
371 if (template_str
.rfind("/tmp/", 0) == 0) {
373 char longpath
[MAX_PATH
+ 1];
374 char shortpath
[MAX_PATH
+ 1];
376 WCHAR longpath
[MAX_PATH
+ 1];
377 TCHAR shortpath
[MAX_PATH
+ 1];
379 if (!GetTempPath(MAX_PATH
+1, longpath
))
380 log_error("GetTempPath() failed.\n");
381 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+ 1))
382 log_error("GetShortPathName() failed.\n");
384 for (int i
= 0; shortpath
[i
]; i
++)
385 path
+= char(shortpath
[i
]);
386 template_str
= stringf("%s\\%s", path
.c_str(), template_str
.c_str() + 5);
389 size_t pos
= template_str
.rfind("XXXXXX");
390 log_assert(pos
!= std::string::npos
);
393 for (int i
= 0; i
< 6; i
++) {
394 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
395 static uint32_t x
= 314159265 ^ uint32_t(time(NULL
));
396 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
397 template_str
[pos
+i
] = y
[x
% y
.size()];
399 if (_access(template_str
.c_str(), 0) != 0)
403 size_t pos
= template_str
.rfind("XXXXXX");
404 log_assert(pos
!= std::string::npos
);
406 int suffixlen
= GetSize(template_str
) - pos
- 6;
408 char *p
= strdup(template_str
.c_str());
409 close(mkstemps(p
, suffixlen
));
417 std::string
make_temp_dir(std::string template_str
)
420 template_str
= make_temp_file(template_str
);
421 mkdir(template_str
.c_str());
425 size_t pos
= template_str
.rfind("XXXXXX");
426 log_assert(pos
!= std::string::npos
);
428 int suffixlen
= GetSize(template_str
) - pos
- 6;
429 log_assert(suffixlen
== 0);
432 char *p
= strdup(template_str
.c_str());
434 log_assert(p
!= NULL
);
443 bool check_file_exists(std::string filename
, bool)
445 return _access(filename
.c_str(), 0) == 0;
448 bool check_file_exists(std::string filename
, bool is_exec
)
450 return access(filename
.c_str(), is_exec
? X_OK
: F_OK
) == 0;
454 bool is_absolute_path(std::string filename
)
457 return filename
[0] == '/' || filename
[0] == '\\' || (filename
[0] != 0 && filename
[1] == ':');
459 return filename
[0] == '/';
463 void remove_directory(std::string dirname
)
466 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
469 struct dirent
**namelist
;
470 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
472 for (int i
= 0; i
< n
; i
++) {
473 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
474 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
475 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
476 remove(buffer
.c_str());
478 remove_directory(buffer
);
483 rmdir(dirname
.c_str());
487 std::string
escape_filename_spaces(const std::string
& filename
)
490 out
.reserve(filename
.size());
491 for (auto c
: filename
)
501 int GetSize(RTLIL::Wire
*wire
)
506 bool already_setup
= false;
512 already_setup
= true;
514 RTLIL::ID::A
= "\\A";
515 RTLIL::ID::B
= "\\B";
516 RTLIL::ID::Y
= "\\Y";
517 RTLIL::ID::keep
= "\\keep";
518 RTLIL::ID::whitebox
= "\\whitebox";
519 RTLIL::ID::blackbox
= "\\blackbox";
522 PyImport_AppendInittab((char*)"libyosys", INIT_MODULE
);
524 PyRun_SimpleString("import sys");
527 RTLIL::constpad
["abc9.script.default"] = "&scorr; &sweep; &dc2; &dch -f; &ps; &if {C} {W} {D} {R} -v; &mfs";
528 RTLIL::constpad
["abc9.script.default.area"] = "&scorr; &sweep; &dc2; &dch -f; &ps; &if {C} {W} {D} {R} -a -v; &mfs";
529 RTLIL::constpad
["abc9.script.default.fast"] = "&if {C} {W} {D} {R}";
530 // Based on ABC's &flow
531 RTLIL::constpad
["abc9.script.flow"] = "&scorr; &sweep;" \
533 "&unmap; &if {C} {W} {D} {R}; &mfs;" \
535 "&unmap; &if {C} {W} {D} {R}; &mfs;" \
536 "&st; &syn2 -m -R 10; &dsdb;" \
538 "&unmap; &if {C} {W} {D} {R}; &mfs;" \
541 "&unmap; &if {C} {W} {D} {R}; &mfs;" \
543 "&unmap; &if {C} {W} {D} {R}; &mfs;" \
544 "&st; &syn2 -m -R 10; &dsdb;" \
546 "&unmap; &if {C} {W} {D} {R} -v; &mfs";
547 // Based on ABC's &flow2
548 RTLIL::constpad
["abc9.script.flow2"] = "&scorr; &sweep;" \
549 /* Comm1 */ "&synch2 -K 6 -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
550 /* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
551 "&load; &st; &sopb -R 10 -C 4; " \
552 /* Comm3 */ "&synch2 -K 6 -C 500; &if -m "/*"-E 5"*/" {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
553 /* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save; "\
555 // Based on ABC's &flow3
556 RTLIL::constpad
["abc9.script.flow3"] = "&scorr; &sweep;" \
557 "&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;"\
558 "&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &save; &load;"\
559 "&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &save; &load;"\
562 Pass::init_register();
563 yosys_design
= new RTLIL::Design
;
564 yosys_celltypes
.setup();
568 bool yosys_already_setup()
570 return already_setup
;
573 bool already_shutdown
= false;
575 void yosys_shutdown()
579 already_shutdown
= true;
582 Pass::done_register();
587 for (auto f
: log_files
)
593 yosys_celltypes
.clear();
595 #ifdef YOSYS_ENABLE_TCL
596 if (yosys_tcl_interp
!= NULL
) {
597 Tcl_DeleteInterp(yosys_tcl_interp
);
599 yosys_tcl_interp
= NULL
;
603 #ifdef YOSYS_ENABLE_PLUGINS
604 for (auto &it
: loaded_plugins
)
607 loaded_plugins
.clear();
609 loaded_python_plugins
.clear();
611 loaded_plugin_aliases
.clear();
619 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
622 size_t pos
= file
.find_last_of("/\\");
624 size_t pos
= file
.find_last_of('/');
626 if (pos
!= std::string::npos
)
627 file
= file
.substr(pos
+1);
629 pos
= func
.find_last_of(':');
630 if (pos
!= std::string::npos
)
631 func
= func
.substr(pos
+1);
633 return stringf("$auto$%s:%d:%s$%d", file
.c_str(), line
, func
.c_str(), autoidx
++);
636 RTLIL::Design
*yosys_get_design()
641 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
643 static char buffer
[100];
644 std::string str
= "\n";
645 if (recursion_counter
> 1)
646 str
+= stringf("(%d) ", recursion_counter
);
648 if (!design
->selected_active_module
.empty())
649 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
650 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
651 if (design
->selected_active_module
.empty())
653 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
654 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
657 snprintf(buffer
, 100, "%s> ", str
.c_str());
661 std::vector
<std::string
> glob_filename(const std::string
&filename_pattern
)
663 std::vector
<std::string
> results
;
665 #if defined(_WIN32) || !defined(YOSYS_ENABLE_GLOB)
666 results
.push_back(filename_pattern
);
670 int err
= glob(filename_pattern
.c_str(), 0, NULL
, &globbuf
);
673 for (size_t i
= 0; i
< globbuf
.gl_pathc
; i
++)
674 results
.push_back(globbuf
.gl_pathv
[i
]);
677 results
.push_back(filename_pattern
);
684 void rewrite_filename(std::string
&filename
)
686 if (filename
.compare(0, 1, "\"") == 0 && filename
.compare(GetSize(filename
)-1, std::string::npos
, "\"") == 0)
687 filename
= filename
.substr(1, GetSize(filename
)-2);
688 if (filename
.compare(0, 2, "+/") == 0)
689 filename
= proc_share_dirname() + filename
.substr(2);
691 if (filename
.compare(0, 2, "~/") == 0)
692 filename
= filename
.replace(0, 1, getenv("HOME"));
696 #ifdef YOSYS_ENABLE_TCL
697 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
699 std::vector
<std::string
> args
;
700 for (int i
= 1; i
< argc
; i
++)
701 args
.push_back(argv
[i
]);
703 if (args
.size() >= 1 && args
[0] == "-import") {
704 for (auto &it
: pass_register
) {
705 std::string tcl_command_name
= it
.first
;
706 if (tcl_command_name
== "proc")
707 tcl_command_name
= "procs";
708 else if (tcl_command_name
== "rename")
709 tcl_command_name
= "renames";
711 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
712 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
714 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
715 Tcl_Eval(interp
, tcl_script
.c_str());
721 if (args
.size() == 1) {
722 Pass::call(yosys_get_design(), args
[0]);
726 Pass::call(yosys_get_design(), args
);
730 extern Tcl_Interp
*yosys_get_tcl_interp()
732 if (yosys_tcl_interp
== NULL
) {
733 yosys_tcl_interp
= Tcl_CreateInterp();
734 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
736 return yosys_tcl_interp
;
739 struct TclPass
: public Pass
{
740 TclPass() : Pass("tcl", "execute a TCL script file") { }
741 void help() YS_OVERRIDE
{
742 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
744 log(" tcl <filename> [args]\n");
746 log("This command executes the tcl commands in the specified file.\n");
747 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
749 log("The tcl command 'yosys -import' can be used to import all yosys\n");
750 log("commands directly as tcl commands to the tcl shell. Yosys commands\n");
751 log("'proc' and 'rename' are wrapped to tcl commands 'procs' and 'renames'\n");
752 log("in order to avoid a name collision with the built in commands.\n");
754 log("If any arguments are specified, these arguments are provided to the script via\n");
755 log("the standard $argc and $argv variables.\n");
758 void execute(std::vector
<std::string
> args
, RTLIL::Design
*) YS_OVERRIDE
{
760 log_cmd_error("Missing script file.\n");
762 std::vector
<Tcl_Obj
*> script_args
;
763 for (auto it
= args
.begin() + 2; it
!= args
.end(); ++it
)
764 script_args
.push_back(Tcl_NewStringObj((*it
).c_str(), (*it
).size()));
766 Tcl_Interp
*interp
= yosys_get_tcl_interp();
767 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argc", 4), NULL
, Tcl_NewIntObj(script_args
.size()), 0);
768 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argv", 4), NULL
, Tcl_NewListObj(script_args
.size(), script_args
.data()), 0);
769 Tcl_ObjSetVar2(interp
, Tcl_NewStringObj("argv0", 5), NULL
, Tcl_NewStringObj(args
[1].c_str(), args
[1].size()), 0);
770 if (Tcl_EvalFile(interp
, args
[1].c_str()) != TCL_OK
)
771 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp
));
776 #if defined(__linux__) || defined(__CYGWIN__)
777 std::string
proc_self_dirname()
780 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
782 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
784 while (buflen
> 0 && path
[buflen
-1] != '/')
786 return std::string(path
, buflen
);
788 #elif defined(__FreeBSD__)
789 std::string
proc_self_dirname()
791 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1};
795 if (sysctl(mib
, 4, NULL
, &buflen
, NULL
, 0) != 0)
796 log_error("sysctl failed: %s\n", strerror(errno
));
797 buffer
= (char*)malloc(buflen
);
799 log_error("malloc failed: %s\n", strerror(errno
));
800 if (sysctl(mib
, 4, buffer
, &buflen
, NULL
, 0) != 0)
801 log_error("sysctl failed: %s\n", strerror(errno
));
802 while (buflen
> 0 && buffer
[buflen
-1] != '/')
804 path
.assign(buffer
, buflen
);
808 #elif defined(__APPLE__)
809 std::string
proc_self_dirname()
813 while (_NSGetExecutablePath(path
, &buflen
) != 0)
814 path
= (char *) realloc((void *) path
, buflen
);
815 while (buflen
> 0 && path
[buflen
-1] != '/')
817 return std::string(path
, buflen
);
819 #elif defined(_WIN32)
820 std::string
proc_self_dirname()
824 char longpath
[MAX_PATH
+ 1];
825 char shortpath
[MAX_PATH
+ 1];
827 WCHAR longpath
[MAX_PATH
+ 1];
828 TCHAR shortpath
[MAX_PATH
+ 1];
830 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
831 log_error("GetModuleFileName() failed.\n");
832 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
833 log_error("GetShortPathName() failed.\n");
834 while (shortpath
[i
] != 0)
836 while (i
> 0 && shortpath
[i
-1] != '/' && shortpath
[i
-1] != '\\')
839 for (i
= 0; shortpath
[i
]; i
++)
840 path
+= char(shortpath
[i
]);
843 #elif defined(EMSCRIPTEN)
844 std::string
proc_self_dirname()
849 #error "Don't know how to determine process executable base path!"
853 std::string
proc_share_dirname()
858 std::string
proc_share_dirname()
860 std::string proc_self_path
= proc_self_dirname();
861 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
862 std::string proc_share_path
= proc_self_path
+ "share\\";
863 if (check_file_exists(proc_share_path
, true))
864 return proc_share_path
;
865 proc_share_path
= proc_self_path
+ "..\\share\\";
866 if (check_file_exists(proc_share_path
, true))
867 return proc_share_path
;
869 std::string proc_share_path
= proc_self_path
+ "share/";
870 if (check_file_exists(proc_share_path
, true))
871 return proc_share_path
;
872 proc_share_path
= proc_self_path
+ "../share/yosys/";
873 if (check_file_exists(proc_share_path
, true))
874 return proc_share_path
;
876 proc_share_path
= YOSYS_DATDIR
"/";
877 if (check_file_exists(proc_share_path
, true))
878 return proc_share_path
;
881 log_error("proc_share_dirname: unable to determine share/ directory!\n");
885 bool fgetline(FILE *f
, std::string
&buffer
)
890 if (fgets(block
, 4096, f
) == NULL
)
893 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
894 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
895 buffer
.resize(buffer
.size()-1);
901 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
906 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
909 if (pos
< GetSize(command
) && command
[pos
] == '#')
912 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
913 label
+= command
[pos
++];
915 if (GetSize(label
) > 1 && label
.back() == ':')
917 label
= label
.substr(0, GetSize(label
)-1);
918 command
= command
.substr(pos
);
920 if (label
== run_from
)
921 from_to_active
= true;
922 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
923 from_to_active
= false;
927 void run_frontend(std::string filename
, std::string command
, std::string
*backend_command
, std::string
*from_to_label
, RTLIL::Design
*design
)
929 if (design
== nullptr)
930 design
= yosys_design
;
932 if (command
== "auto") {
933 std::string filename_trim
= filename
;
934 if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".gz") == 0)
935 filename_trim
.erase(filename_trim
.size()-3);
936 if (filename_trim
.size() > 2 && filename_trim
.compare(filename_trim
.size()-2, std::string::npos
, ".v") == 0)
938 else if (filename_trim
.size() > 2 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".sv") == 0)
939 command
= "verilog -sv";
940 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-4, std::string::npos
, ".vhd") == 0)
942 else if (filename_trim
.size() > 4 && filename_trim
.compare(filename_trim
.size()-5, std::string::npos
, ".blif") == 0)
944 else if (filename_trim
.size() > 5 && filename_trim
.compare(filename_trim
.size()-6, std::string::npos
, ".eblif") == 0)
946 else if (filename_trim
.size() > 4 && filename_trim
.compare(filename_trim
.size()-5, std::string::npos
, ".json") == 0)
948 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".il") == 0)
950 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-3, std::string::npos
, ".ys") == 0)
952 else if (filename_trim
.size() > 3 && filename_trim
.compare(filename_trim
.size()-4, std::string::npos
, ".tcl") == 0)
954 else if (filename
== "-")
957 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
960 if (command
== "script")
962 std::string run_from
, run_to
;
963 bool from_to_active
= true;
965 if (from_to_label
!= NULL
) {
966 size_t pos
= from_to_label
->find(':');
967 if (pos
== std::string::npos
) {
968 run_from
= *from_to_label
;
969 run_to
= *from_to_label
;
971 run_from
= from_to_label
->substr(0, pos
);
972 run_to
= from_to_label
->substr(pos
+1);
974 from_to_active
= run_from
.empty();
977 log("\n-- Executing script file `%s' --\n", filename
.c_str());
981 if (filename
!= "-") {
982 f
= fopen(filename
.c_str(), "r");
983 yosys_input_files
.insert(filename
);
987 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
989 FILE *backup_script_file
= Frontend::current_script_file
;
990 Frontend::current_script_file
= f
;
994 while (fgetline(f
, command
)) {
995 while (!command
.empty() && command
[command
.size()-1] == '\\') {
996 std::string next_line
;
997 if (!fgetline(f
, next_line
))
999 command
.resize(command
.size()-1);
1000 command
+= next_line
;
1002 handle_label(command
, from_to_active
, run_from
, run_to
);
1003 if (from_to_active
) {
1004 Pass::call(design
, command
);
1009 if (!command
.empty()) {
1010 handle_label(command
, from_to_active
, run_from
, run_to
);
1011 if (from_to_active
) {
1012 Pass::call(design
, command
);
1018 Frontend::current_script_file
= backup_script_file
;
1022 Frontend::current_script_file
= backup_script_file
;
1024 if (filename
!= "-")
1027 if (backend_command
!= NULL
&& *backend_command
== "auto")
1028 *backend_command
= "";
1033 if (filename
== "-") {
1034 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
1036 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
1039 if (command
== "tcl")
1040 Pass::call(design
, vector
<string
>({command
, filename
}));
1042 Frontend::frontend_call(design
, NULL
, filename
, command
);
1046 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
)
1048 run_frontend(filename
, command
, nullptr, nullptr, design
);
1051 void run_pass(std::string command
, RTLIL::Design
*design
)
1053 if (design
== nullptr)
1054 design
= yosys_design
;
1056 log("\n-- Running command `%s' --\n", command
.c_str());
1058 Pass::call(design
, command
);
1061 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
1063 if (design
== nullptr)
1064 design
= yosys_design
;
1066 if (command
== "auto") {
1067 if (filename
.size() > 2 && filename
.compare(filename
.size()-2, std::string::npos
, ".v") == 0)
1068 command
= "verilog";
1069 else if (filename
.size() > 3 && filename
.compare(filename
.size()-3, std::string::npos
, ".il") == 0)
1071 else if (filename
.size() > 4 && filename
.compare(filename
.size()-4, std::string::npos
, ".aig") == 0)
1073 else if (filename
.size() > 5 && filename
.compare(filename
.size()-5, std::string::npos
, ".blif") == 0)
1075 else if (filename
.size() > 5 && filename
.compare(filename
.size()-5, std::string::npos
, ".edif") == 0)
1077 else if (filename
.size() > 5 && filename
.compare(filename
.size()-5, std::string::npos
, ".json") == 0)
1079 else if (filename
== "-")
1081 else if (filename
.empty())
1084 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
1087 if (filename
.empty())
1090 if (filename
== "-") {
1091 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
1093 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
1096 Backend::backend_call(design
, NULL
, filename
, command
);
1099 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1100 static char *readline_cmd_generator(const char *text
, int state
)
1102 static std::map
<std::string
, Pass
*>::iterator it
;
1106 it
= pass_register
.begin();
1110 for (; it
!= pass_register
.end(); it
++) {
1111 if (it
->first
.compare(0, len
, text
) == 0)
1112 return strdup((it
++)->first
.c_str());
1117 static char *readline_obj_generator(const char *text
, int state
)
1119 static std::vector
<char*> obj_names
;
1127 RTLIL::Design
*design
= yosys_get_design();
1128 int len
= strlen(text
);
1130 if (design
->selected_active_module
.empty())
1132 for (auto &it
: design
->modules_
)
1133 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1134 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1137 if (design
->modules_
.count(design
->selected_active_module
) > 0)
1139 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
1141 for (auto &it
: module
->wires_
)
1142 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1143 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1145 for (auto &it
: module
->memories
)
1146 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1147 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1149 for (auto &it
: module
->cells_
)
1150 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1151 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1153 for (auto &it
: module
->processes
)
1154 if (RTLIL::unescape_id(it
.first
).compare(0, len
, text
) == 0)
1155 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
1158 std::sort(obj_names
.begin(), obj_names
.end());
1161 if (idx
< obj_names
.size())
1162 return strdup(obj_names
[idx
++]);
1169 static char **readline_completion(const char *text
, int start
, int)
1172 return rl_completion_matches(text
, readline_cmd_generator
);
1173 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
1174 return rl_completion_matches(text
, readline_obj_generator
);
1179 void shell(RTLIL::Design
*design
)
1181 static int recursion_counter
= 0;
1183 recursion_counter
++;
1184 log_cmd_error_throw
= true;
1186 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1187 rl_readline_name
= (char*)"yosys";
1188 rl_attempted_completion_function
= readline_completion
;
1189 rl_basic_word_break_characters
= (char*)" \t\n";
1192 char *command
= NULL
;
1193 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1194 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
1197 char command_buffer
[4096];
1200 fputs(create_prompt(design
, recursion_counter
), stdout
);
1202 if ((command
= fgets(command_buffer
, 4096, stdin
)) == NULL
)
1205 if (command
[strspn(command
, " \t\r\n")] == 0)
1207 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1208 add_history(command
);
1211 char *p
= command
+ strspn(command
, " \t\r\n");
1212 if (!strncmp(p
, "exit", 4)) {
1214 p
+= strspn(p
, " \t\r\n");
1220 log_assert(design
->selection_stack
.size() == 1);
1221 Pass::call(design
, command
);
1222 } catch (log_cmd_error_exception
) {
1223 while (design
->selection_stack
.size() > 1)
1224 design
->selection_stack
.pop_back();
1229 if (command
== NULL
)
1232 recursion_counter
--;
1233 log_cmd_error_throw
= false;
1236 struct ShellPass
: public Pass
{
1237 ShellPass() : Pass("shell", "enter interactive command mode") { }
1238 void help() YS_OVERRIDE
{
1242 log("This command enters the interactive command mode. This can be useful\n");
1243 log("in a script to interrupt the script at a certain point and allow for\n");
1244 log("interactive inspection or manual synthesis of the design at this point.\n");
1246 log("The command prompt of the interactive shell indicates the current\n");
1247 log("selection (see 'help select'):\n");
1250 log(" the entire design is selected\n");
1253 log(" only part of the design is selected\n");
1255 log(" yosys [modname]>\n");
1256 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1258 log(" yosys [modname]*>\n");
1259 log(" only part of current module 'modname' is selected\n");
1261 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1262 log("do not terminate yosys but return to the command prompt.\n");
1264 log("This command is the default action if nothing else has been specified\n");
1265 log("on the command line.\n");
1267 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1270 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
{
1271 extra_args(args
, 1, design
, false);
1276 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1277 struct HistoryPass
: public Pass
{
1278 HistoryPass() : Pass("history", "show last interactive commands") { }
1279 void help() YS_OVERRIDE
{
1283 log("This command prints all commands in the shell history buffer. This are\n");
1284 log("all commands executed in an interactive session, but not the commands\n");
1285 log("from executed scripts.\n");
1288 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
{
1289 extra_args(args
, 1, design
, false);
1290 #ifdef YOSYS_ENABLE_READLINE
1291 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
1292 log("%s\n", (*list
)->line
);
1294 for (int i
= where_history(); history_get(i
); i
++)
1295 log("%s\n", history_get(i
)->line
);
1301 struct ScriptCmdPass
: public Pass
{
1302 ScriptCmdPass() : Pass("script", "execute commands from file or wire") { }
1303 void help() YS_OVERRIDE
{
1304 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1306 log(" script <filename> [<from_label>:<to_label>]\n");
1307 log(" script -scriptwire [selection]\n");
1309 log("This command executes the yosys commands in the specified file (default\n");
1310 log("behaviour), or commands embedded in the constant text value connected to the\n");
1311 log("selected wires.\n");
1313 log("In the default (file) case, the 2nd argument can be used to only execute the\n");
1314 log("section of the file between the specified labels. An empty from label is\n");
1315 log("synonymous with the beginning of the file and an empty to label is synonymous\n");
1316 log("with the end of the file.\n");
1318 log("If only one label is specified (without ':') then only the block\n");
1319 log("marked with that label (until the next label) is executed.\n");
1321 log("In \"-scriptwire\" mode, the commands on the selected wire(s) will be executed\n");
1322 log("in the scope of (and thus, relative to) the wires' owning module(s). This\n");
1323 log("'-module' mode can be exited by using the 'cd' command.\n");
1326 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
1328 bool scriptwire
= false;
1331 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
1332 if (args
[argidx
] == "-scriptwire") {
1339 extra_args(args
, argidx
, design
);
1341 for (auto mod
: design
->selected_modules())
1342 for (auto &c
: mod
->connections()) {
1343 if (!c
.first
.is_wire())
1345 auto w
= c
.first
.as_wire();
1346 if (!mod
->selected(w
))
1348 if (!c
.second
.is_fully_const())
1349 log_error("RHS of selected wire %s.%s is not constant.\n", log_id(mod
), log_id(w
));
1350 auto v
= c
.second
.as_const();
1351 Pass::call_on_module(design
, mod
, v
.decode_string());
1354 else if (args
.size() < 2)
1355 log_cmd_error("Missing script file.\n");
1356 else if (args
.size() == 2)
1357 run_frontend(args
[1], "script", design
);
1358 else if (args
.size() == 3)
1359 run_frontend(args
[1], "script", NULL
, &args
[2], design
);
1361 extra_args(args
, 2, design
, false);