forked from The-OpenROAD-Project/OpenROAD
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain.cc
More file actions
663 lines (598 loc) · 21.8 KB
/
Copy pathMain.cc
File metadata and controls
663 lines (598 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2019-2025, The OpenROAD Authors
#include <stdlib.h> // NOLINT(modernize-deprecated-headers): for setenv()
#include <strings.h>
#include <array>
#include <climits>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <memory>
#include <string>
#include <system_error>
#include "boost/stacktrace/stacktrace.hpp"
#include "tcl.h"
#ifdef ENABLE_READLINE
// If you get an error on this include be sure you have
// the package tcl-tclreadline-devel installed
#include "tclreadline.h"
#endif
#ifdef ENABLE_PYTHON3
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#endif
#ifdef BAZEL_CURRENT_REPOSITORY
#include "rules_cc/cc/runfiles/runfiles.h"
using rules_cc::cc::runfiles::Runfiles;
#endif
#ifdef ENABLE_TCLX
#include <tclExtend.h>
#endif
#include "cut/abc_init.h"
#include "gui/gui.h"
#include "ord/Design.h"
#include "ord/InitOpenRoad.hh"
#include "ord/OpenRoad.hh"
#include "ord/Tech.h"
#include "sta/StaMain.hh"
#include "sta/StringUtil.hh"
#include "utl/Logger.h"
#include "utl/decode.h"
using sta::findCmdLineFlag;
using sta::findCmdLineKey;
using sta::sourceTclFile;
using sta::stringEq;
using std::string;
#ifdef ENABLE_PYTHON3
#define FOREACH_TOOL_WITHOUT_OPENROAD(X) \
X(ifp) \
X(utl) \
X(ant) \
X(grt) \
X(gpl) \
X(dpl) \
X(exa) \
X(web) \
X(ppl) \
X(tap) \
X(cts) \
X(drt) \
X(fin) \
X(par) \
X(rcx) \
X(rmp) \
X(cgt) \
X(stt) \
X(psm) \
X(pdn) \
X(odb) \
X(ord)
#define FOREACH_TOOL(X) FOREACH_TOOL_WITHOUT_OPENROAD(X)
extern "C" {
#define X(name) extern PyObject* PyInit__##name##_py();
FOREACH_TOOL(X)
#undef X
}
#endif
int cmd_argc;
char** cmd_argv;
static const char* log_filename = nullptr;
static const char* metrics_filename = nullptr;
static const char* read_odb_filename = nullptr;
static bool no_settings = false;
static bool minimize = false;
static const char* init_filename = ".openroad";
static void showUsage(const char* prog, const char* init_filename);
static void showSplash();
#ifdef ENABLE_PYTHON3
#define X(name) \
namespace name { \
extern const char* name##_py_python_inits[]; \
}
FOREACH_TOOL(X)
#undef X
#if PY_VERSION_HEX >= 0x03080000
static void initPython(int argc, char* argv[], const bool exit_after_cmd_file)
#else
static void initPython()
#endif
{
#define X(name) \
if (PyImport_AppendInittab("_" #name "_py", PyInit__##name##_py) == -1) { \
fprintf(stderr, "Error: could not add module _" #name "_py\n"); \
exit(1); \
}
FOREACH_TOOL(X)
#undef X
#if PY_VERSION_HEX >= 0x03080000
PyConfig config;
PyConfig_InitPythonConfig(&config);
PyConfig_SetBytesArgv(&config, argc, argv);
config.inspect = !exit_after_cmd_file;
Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
#else
Py_Initialize();
#endif
#define X(name) \
{ \
std::string unencoded = utl::base64_decode(name::name##_py_python_inits); \
PyObject* code \
= Py_CompileString(unencoded.c_str(), #name "_py.py", Py_file_input); \
if (code == nullptr) { \
PyErr_Print(); \
fprintf(stderr, "Error: could not compile " #name "_py\n"); \
exit(1); \
} \
if (PyImport_ExecCodeModule(#name, code) == nullptr) { \
PyErr_Print(); \
fprintf(stderr, "Error: could not add module " #name "\n"); \
exit(1); \
} \
}
FOREACH_TOOL_WITHOUT_OPENROAD(X)
#undef X
#undef FOREACH_TOOL
#undef FOREACH_TOOL_WITHOUT_OPENROAD
// Need to separately handle openroad here because we need both
// the names "openroad_swig" and "openroad".
{
std::string unencoded = utl::base64_decode(ord::ord_py_python_inits);
PyObject* code
= Py_CompileString(unencoded.c_str(), "openroad.py", Py_file_input);
if (code == nullptr) {
PyErr_Print();
fprintf(stderr, "Error: could not compile openroad.py\n");
exit(1);
}
if (PyImport_ExecCodeModule("openroad", code) == nullptr) {
PyErr_Print();
fprintf(stderr, "Error: could not add module openroad\n");
exit(1);
}
}
}
#endif
static volatile sig_atomic_t fatal_error_in_progress = 0;
// When we enter through main() we have a single tech and design.
// Custom applications using OR as a library might define multiple.
// Such applications won't allocate or use these objects.
//
// Use a wrapper struct to ensure destruction ordering - design
// then tech (members are destroyed in reverse order).
struct TechAndDesign
{
std::unique_ptr<ord::Tech> tech;
std::unique_ptr<ord::Design> design;
};
static TechAndDesign the_tech_and_design;
static void handler(int sig)
{
if (fatal_error_in_progress) {
raise(sig);
}
fatal_error_in_progress = 1;
std::cerr << "Signal " << sig << " received\n";
std::cerr << "Stack trace:\n";
std::cerr << boost::stacktrace::stacktrace();
signal(sig, SIG_DFL);
raise(sig);
}
int main(int argc, char* argv[])
{
// This avoids problems with locale setting dependent
// C functions like strtod (e.g. 0.5 vs 0,5).
std::array locales = {"en_US.UTF-8", "C.UTF-8", "C"};
for (auto locale : locales) {
if (std::setlocale(LC_ALL, locale) != nullptr) {
setenv("LC_ALL", locale, /* override */ 1);
break;
}
}
// Generate a stacktrace on crash
signal(SIGABRT, handler);
signal(SIGBUS, handler);
signal(SIGFPE, handler);
signal(SIGILL, handler);
signal(SIGSEGV, handler);
if (argc == 2 && stringEq(argv[1], "-help")) {
showUsage(argv[0], init_filename);
return 0;
}
if (argc == 2 && stringEq(argv[1], "-version")) {
printf("%s %s\n",
ord::OpenRoad::getVersion(),
ord::OpenRoad::getGitDescribe());
return 0;
}
log_filename = findCmdLineKey(argc, argv, "-log");
if (log_filename) {
std::error_code err_ignore;
std::filesystem::remove(log_filename, err_ignore);
}
metrics_filename = findCmdLineKey(argc, argv, "-metrics");
if (metrics_filename) {
std::error_code err_ignored;
std::filesystem::remove(metrics_filename, err_ignored);
}
read_odb_filename = findCmdLineKey(argc, argv, "-db");
no_settings = findCmdLineFlag(argc, argv, "-no_settings");
minimize = findCmdLineFlag(argc, argv, "-minimize");
cmd_argc = argc;
cmd_argv = argv;
#ifdef ENABLE_PYTHON3
if (findCmdLineFlag(cmd_argc, cmd_argv, "-python")) {
// Setup the app with tcl
auto* interp = Tcl_CreateInterp();
Tcl_Init(interp);
the_tech_and_design.tech = std::make_unique<ord::Tech>(interp);
the_tech_and_design.design
= std::make_unique<ord::Design>(the_tech_and_design.tech.get());
ord::OpenRoad::setOpenRoad(the_tech_and_design.design->getOpenRoad());
const bool exit = findCmdLineFlag(cmd_argc, cmd_argv, "-exit");
ord::initOpenRoad(interp, log_filename, metrics_filename, exit);
if (!findCmdLineFlag(cmd_argc, cmd_argv, "-no_splash")) {
showSplash();
}
utl::Logger* logger = ord::OpenRoad::openRoad()->getLogger();
if (findCmdLineFlag(cmd_argc, cmd_argv, "-gui")) {
logger->warn(utl::ORD, 38, "-gui is not yet supported with -python");
}
if (!findCmdLineFlag(cmd_argc, cmd_argv, "-no_init")) {
logger->warn(utl::ORD, 39, ".openroad ignored with -python");
}
const char* threads = findCmdLineKey(cmd_argc, cmd_argv, "-threads");
if (threads) {
ord::OpenRoad::openRoad()->setThreadCount(threads);
} else {
// set to default number of threads
ord::OpenRoad::openRoad()->setThreadCount(
ord::OpenRoad::openRoad()->getThreadCount(), false);
}
#if PY_VERSION_HEX >= 0x03080000
initPython(cmd_argc, cmd_argv, exit);
return Py_RunMain();
#else
initPython();
std::vector<wchar_t*> args;
args.push_back(Py_DecodeLocale(cmd_argv[0], nullptr));
if (!exit) {
args.push_back(Py_DecodeLocale("-i", nullptr));
}
for (int i = 1; i < cmd_argc; i++) {
args.push_back(Py_DecodeLocale(cmd_argv[i], nullptr));
}
return Py_Main(args.size(), args.data());
#endif // PY_VERSION_HEX >= 0x03080000
}
#endif // ENABLE_PYTHON3
// Set argc to 1 so Tcl_Main doesn't source any files.
// Tcl_Main never returns.
Tcl_Main(1, argv, ord::tclAppInit);
cut::abcStop();
return 0;
}
#ifdef ENABLE_READLINE
static int tclReadlineInit(Tcl_Interp* interp)
{
std::array<const char*, 2> readline_cmds
= {"ord::setup_tclreadline", "::tclreadline::Loop"};
for (auto cmd : readline_cmds) {
if (TCL_ERROR == Tcl_Eval(interp, cmd)) {
return TCL_ERROR;
}
}
return TCL_OK;
}
#endif
#ifdef ENABLE_READLINE
namespace {
// A stopgap fallback from the hardcoded TCLRL_LIBRARY path for OpenROAD,
// not essential for OpenSTA
std::string findPathToTclreadlineInit(Tcl_Interp* interp)
{
// TL;DR it is possible to run the OpenROAD binary from within the
// official Docker image on a different distribution than the
// distribution within the Docker image.
//
// In this case we have to look up
// the location of the tclreadline scripts instead of using the hardcoded
// path.
//
// It is helpful to use the official Docker image as CI infrastructure and
// also because it is a good way to have as similar an environment as possible
// during testing and deployment.
//
// See
// https://github.com/The-OpenROAD-Project/bazel-orfs/blob/main/docker.BUILD.bazel
// for the details on how this is done.
//
// Running Docker within a bazel isolated environment introduces lots of
// problems and is not really done.
const char* tcl_script = R"(
namespace eval temp {
# Check standard Bazel runfiles relative path
set runfiles_path [file join [pwd] "external/tclreadline/tclreadlineInit.tcl"]
if {[file exists $runfiles_path]} {
return $runfiles_path
}
# Check Bazel runfiles in adjacent directories for other run strategies
set runfiles_execroot_path [file join [pwd] "../tclreadline/tclreadlineInit.tcl"]
if {[file exists $runfiles_execroot_path]} {
return $runfiles_execroot_path
}
foreach dir $::auto_path {
set folder [file join $dir]
set path [file join $folder "tclreadline)" TCLRL_VERSION_STR
R"(" "tclreadlineInit.tcl"]
if {[file exists $path]} {
return $path
}
}
error "tclreadlineInit.tcl not found in any of the directories in auto_path"
}
)";
if (Tcl_Eval(interp, tcl_script) == TCL_ERROR) {
std::cerr << "Tcl_Eval failed: " << Tcl_GetStringResult(interp) << '\n';
return "";
}
return Tcl_GetStringResult(interp);
}
} // namespace
#endif
// Tcl init executed inside Tcl_Main.
static int tclAppInit(int& argc,
char* argv[],
const char* init_filename,
Tcl_Interp* interp)
{
bool exit_after_cmd_file = false;
// first check if gui was requested and launch.
// gui will call this function again as part of setup
// ensuring the else {} will be utilized to initialize tcl and OR.
if (findCmdLineFlag(argc, argv, "-gui")) {
// gobble up remaining -gui flags if present, since this could result in
// second invocation of the GUI
while (findCmdLineFlag(argc, argv, "-gui")) {
;
}
gui::startGui(argc, argv, interp, "", true, !no_settings, minimize);
} else {
// init tcl
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#ifdef ENABLE_TCLX
if (Tclx_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
exit_after_cmd_file = findCmdLineFlag(argc, argv, "-exit");
#ifdef ENABLE_READLINE
if (!exit_after_cmd_file) {
if (Tclreadline_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
// tclreadline is a bit of a tricky dependency because it
// uses absolute path references below, so we don't depend on
// tclreadline for the batch case where we exit as soon as the
// script is done.
Tcl_StaticPackage(
interp, "tclreadline", Tclreadline_Init, Tclreadline_SafeInit);
if (Tcl_EvalFile(interp, TCLRL_LIBRARY "/tclreadlineInit.tcl")
!= TCL_OK) {
bool found = false;
#ifdef BAZEL_CURRENT_REPOSITORY
std::string error;
std::unique_ptr<Runfiles> runfiles(
Runfiles::Create(argv[0], BAZEL_CURRENT_REPOSITORY, &error));
if (runfiles) {
// Under bzlmod, the tclreadline repo might be called
// +_repo_rules+tclreadline
std::string repo_prefix;
std::string path = runfiles->Rlocation(
"+_repo_rules+tclreadline/tclreadlineInit.tcl");
if (!path.empty()) {
repo_prefix = "+_repo_rules+tclreadline";
} else {
path = runfiles->Rlocation("tclreadline/tclreadlineInit.tcl");
if (!path.empty()) {
repo_prefix = "tclreadline";
} else {
path = runfiles->Rlocation(
"_main~override~tclreadline/tclreadlineInit.tcl");
if (!path.empty()) {
repo_prefix = "_main~override~tclreadline";
}
}
}
if (!path.empty()) {
std::string dir = path.substr(0, path.find_last_of("/\\"));
std::string setup_path
= runfiles->Rlocation(repo_prefix + "/tclreadlineSetup.tcl");
std::string completer_path = runfiles->Rlocation(
repo_prefix + "/tclreadlineCompleter.tcl");
// Setup variables so that the scripts can find themselves
std::string cmd
= std::string("namespace eval ::tclreadline {}; ")
+ std::string("set ::tclreadline::library \"") + dir + "\"; "
+ std::string("set ::tclreadline::setup_path \"") + setup_path
+ "\"; " + std::string("set ::tclreadline::completer_path \"")
+ completer_path + "\"; "
+ std::string("lappend ::auto_path \"") + dir + "\"; "
+ std::string(
"if {[info commands history] == \"\"} { proc history "
"{args} {} }; ");
Tcl_Eval(interp, cmd.c_str());
if (Tcl_EvalFile(interp, path.c_str()) == TCL_OK) {
found = true;
} else {
printf("Failed evaluating runfiles tclreadline: %s\n",
Tcl_GetStringResult(interp));
}
} else {
printf(
"Runfiles Rlocation for tclreadlineInit.tcl returned empty.\n");
}
} else {
printf("Runfiles::Create failed: %s\n", error.c_str());
}
#endif
if (!found) {
std::string path = findPathToTclreadlineInit(interp);
if (path.empty() || Tcl_EvalFile(interp, path.c_str()) != TCL_OK) {
printf("Failed to load tclreadline\n");
}
}
}
}
#endif
ord::initOpenRoad(
interp, log_filename, metrics_filename, exit_after_cmd_file);
bool no_splash = findCmdLineFlag(argc, argv, "-no_splash");
if (!no_splash) {
showSplash();
}
const char* threads = findCmdLineKey(argc, argv, "-threads");
if (threads) {
ord::OpenRoad::openRoad()->setThreadCount(threads, !no_splash);
} else {
// set to default number of threads
ord::OpenRoad::openRoad()->setThreadCount(
ord::OpenRoad::openRoad()->getThreadCount(), false);
}
const bool gui_enabled = gui::Gui::enabled();
if (read_odb_filename) {
std::string cmd = fmt::format("read_db {{{}}}", read_odb_filename);
if (!gui_enabled) {
if (Tcl_Eval(interp, cmd.c_str()) != TCL_OK) {
fprintf(stderr,
"Error: failed to read_db %s: %s\n",
read_odb_filename,
Tcl_GetStringResult(interp));
exit(1);
}
} else {
gui::Gui::get()->addRestoreStateCommand(cmd);
}
}
const char* home = getenv("HOME");
if (!findCmdLineFlag(argc, argv, "-no_init") && home) {
const char* restore_state_cmd = "include -echo -verbose {{{}}}";
std::filesystem::path init(home);
init /= init_filename;
if (std::filesystem::is_regular_file(init)) {
if (!gui_enabled) {
sourceTclFile(init.c_str(), true, true, interp);
} else {
// need to delay loading of file until after GUI is completed
// initialized
gui::Gui::get()->addRestoreStateCommand(
fmt::format(FMT_RUNTIME(restore_state_cmd), init.string()));
}
}
}
if (argc > 2 || (argc > 1 && argv[1][0] == '-')) {
showUsage(argv[0], init_filename);
exit(1);
} else {
if (argc == 2) {
char* cmd_file = argv[1];
if (cmd_file) {
if (!gui_enabled) {
int result = sourceTclFile(cmd_file, false, false, interp);
if (exit_after_cmd_file) {
int exit_code = (result == TCL_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
exit(exit_code);
}
} else {
// need to delay loading of file until after GUI is completed
// initialized
gui::Gui::get()->addRestoreStateCommand(
fmt::format("source {{{}}}", cmd_file));
if (exit_after_cmd_file) {
gui::Gui::get()->addRestoreStateCommand("exit");
}
}
}
}
}
}
#ifdef ENABLE_READLINE
if (!gui::Gui::enabled() && !exit_after_cmd_file) {
return tclReadlineInit(interp);
}
#endif
return TCL_OK;
}
int ord::tclAppInit(Tcl_Interp* interp)
{
the_tech_and_design.tech = std::make_unique<ord::Tech>(interp);
the_tech_and_design.design
= std::make_unique<ord::Design>(the_tech_and_design.tech.get());
ord::OpenRoad::setOpenRoad(the_tech_and_design.design->getOpenRoad());
// This is to enable Design.i where a design arg can be
// retrieved from the interpreter. This is necessary for
// cases with more than one interpreter (ie more than one Design).
// This should replace the use of the singleton OpenRoad::openRoad().
Tcl_SetAssocData(interp, "design", nullptr, the_tech_and_design.design.get());
return ord::tclInit(interp);
}
int ord::tclInit(Tcl_Interp* interp)
{
return tclAppInit(cmd_argc, cmd_argv, init_filename, interp);
}
static void showUsage(const char* prog, const char* init_filename)
{
printf("Usage: %s [-help] [-version] [-no_init] [-no_splash] [-exit] ", prog);
printf("[-gui] [-threads count|max] [-log file_name] [-metrics file_name] ");
printf("[-db file_name] [-no_settings] [-minimize] cmd_file\n");
printf(" -help show help and exit\n");
printf(" -version show version and exit\n");
printf(" -no_init do not read %s init file\n", init_filename);
printf(" -threads count|max use count threads\n");
printf(" -no_splash do not show the license splash at startup\n");
printf(" -exit exit after reading cmd_file\n");
printf(" -gui start in gui mode\n");
printf(" -minimize start the gui minimized\n");
printf(" -no_settings do not load the previous gui settings\n");
#ifdef ENABLE_PYTHON3
printf(
" -python start with python interpreter [limited to db "
"operations]\n");
#endif
printf(" -log <file_name> write a log in <file_name>\n");
printf(
" -metrics <file_name> write metrics in <file_name> in JSON format\n");
printf(" -db <file_name> open a .odb database at startup\n");
printf(" cmd_file source cmd_file\n");
}
static void showSplash()
{
utl::Logger* logger = ord::OpenRoad::openRoad()->getLogger();
logger->report("OpenROAD {} {}",
ord::OpenRoad::getVersion(),
ord::OpenRoad::getGitDescribe());
logger->report(
"Features included (+) or not (-): "
"{}GPU {}GUI {}Python{}",
ord::OpenRoad::getGPUCompileOption() ? "+" : "-",
ord::OpenRoad::getGUICompileOption() ? "+" : "-",
ord::OpenRoad::getPythonCompileOption() ? "+" : "-",
#ifdef BAZEL_CURRENT_REPOSITORY
strcasecmp(BUILD_TYPE, "opt") == 0
#else
strcasecmp(BUILD_TYPE, "release") == 0
#endif
? ""
: fmt::format(" : {}", BUILD_TYPE));
logger->report(
"This program is licensed under the BSD-3 license. See the LICENSE file "
"for details.");
logger->report(
"Components of this program may be licensed under more restrictive "
"licenses which must be honored.");
}