8000 mjit.c: introduce JIT compaction [experimental] · github/ruby@443f4d5 · GitHub
[go: up one dir, main page]

Skip to content

Commit 443f4d5

Browse files
committed
mjit.c: introduce JIT compaction [experimental]
When all compilation finishes or the number of JIT-ed code reaches --jit-max-cache, this compacts all generated code to a single .so file and re-loads all methods from it. In the future, it may trigger compaction more frequently and/or limit the maximum times of compaction to prevent unlimited memory usage. So the current behavior is experimental, but at least the performance improvement in this commit won't be removed. === Benchmark === In this benchmark, I'll compare following four conditions: * trunk: r64082 * trunk JIT: r64082 w/ --jit * single-so JIT: This commit w/ --jit * objfcn JIT: This branch https://github.com/k0kubun/ruby/tree/objfcn w/ --jit, which is shinh's objfcn https://github.com/shinh/ruby/tree/objfcn rebased from this commit ``` $ uname -a Linux bionic 4.15.0-29-generic #31-Ubuntu SMP Tue Jul 17 15:39:52 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux ``` * Micro benchmark Using this script https://gist.github.com/k0kubun/10e6d3387c9ab1b134622b2c9d76ef51, calls some amount of different methods that just return `nil`. The following tables are its average duration seconds of 3 measurements. Smaller is better. ** 1 method (seconds) | | trunk | trunk JIT | single-so JIT | objfcn JIT | |:------|:------------------|:------------------|:------------------|:------------------| | Time | 5.576067774333296 | 5.915551971666446 | 5.833641665666619 | 5.845915191666639 | | Ratio | 1.00x | 1.06x | 1.05x | 1.05x | ** 50 methods (seconds) | | trunk | trunk JIT | single-so JIT | objfcn JIT | |:------|:------------------|:------------------|:------------------|:------------------| | Time | 3.1661167996666677| 6.125825928333342 | 4.135432743666665 | 3.750358728333348 | | Ratio | 1.00x | 1.93x | 1.31x | 1.18x | ** 1500 methods (seconds) | | trunk | trunk JIT | single-so JIT | objfcn JIT | |:------|:------------------|:------------------|:------------------|:------------------| | Time | 5.971650823666664 | 19.579182102999994| 10.511108153999961| 10.854653588999932| | Ratio | 1.00x | 3.28x | 1.76x | 1.82x | * Discourse Using the same benchmark strategy as https://bugs.ruby-lang.org/issues/14490 with this branch https://github.com/k0kubun/discourse/commits/benchmark2 forked from discourse v1.8.11 to support running trunk. 1. Run ruby script/bench.rb to warm up profiling database 2. Run RUBYOPT='--jit-verbose=1 --jit-max-cache=10000' RAILS_ENV=profile bin/puma -e production 3. WAIT 5-15 or so minutes for all jitting to stop so we have no cross talk 4. Run ab -n 100 http://localhost:9292/ 5. Wait for all new jitting to finish 6. Run ab -n 100 http://localhost:9292/ ** Response time (ms) Here is the response time milliseconds for each percentile. Skipping 99%ile because it's the same as 100%ile in 100 calls. | | trunk| trunk|single|objfcn| | | | JIT|so JIT| JIT| |:----|:-----|:-----|:-----|:-----| | 50% | 38 | 45 | 41 | 43 | | 66% | 39 | 50 | 44 | 44 | | 75% | 47 | 51 | 46 | 45 | | 80% | 49 | 52 | 47 | 47 | | 90% | 50 | 63 | 50 | 52 | | 95% | 60 | 79 | 52 | 55 | | 98% | 91 | 114 | 91 | 91 | |100% | 97 | 133 | 96 | 99 | ** Ratio (smaller is better) Here is the response time increase ratio against no-JIT trunk's one. | | trunk| trunk|single|objfcn| | | | JIT|so JIT| JIT| |:----|:-----|:-----|:-----|:-----| | 50% | 1.00x| 1.18x| 1.08x| 1.13x| | 66% | 1.00x| 1.28x| 1.13x| 1.13x| | 75% | 1.00x| 1.09x| 0.98x| 0.96x| | 80% | 1.00x| 1.06x| 0.96x| 0.96x| | 90% | 1.00x| 1.26x| 1.00x| 1.04x| | 95% | 1.00x| 1.32x| 0.87x| 0.92x| | 98% | 1.00x| 1.25x| 1.00x| 1.00x| |100% | 1.00x| 1.37x| 0.99x| 1.02x| While 50 and 60 %ile are still worse than no-JIT trunk, 75, 80, 90, 95, 98 and 100% are not slower than that. So now it's a little harder to say "MJIT slows down Rails applications". Probably I can close [Bug #14490] now. Let's start improving it. Close ruby#1921 git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@64094 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
1 parent 2a9cae3 commit 443f4d5

File tree

2 files changed

+121
-15
lines changed

2 files changed

+121
-15
lines changed

mjit.c

Lines changed: 110 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,8 @@ int mjit_call_p = FALSE;
198198
static struct rb_mjit_unit_list unit_queue;
199199
/* List of units which are successfully compiled. */
200200
static struct rb_mjit_unit_list active_units;
201+
/* List of compacted so files which will be deleted in `mjit_finish()`. */
202+
static struct rb_mjit_unit_list compact_units;
201203
/* The number of so far processed ISEQs, used to generate unique id. */
202204
static int current_unit_num;
203205
/* A mutex for conitionals and critical sections. */
@@ -774,6 +776,8 @@ make_pch(void)
774776
#define append_str(p, str) append_str2(p, str, sizeof(str)-1)
775777
#define append_lit(p, str) append_str2(p, str, rb_strlen_lit(str))
776778

779+
#define MJIT_TMP_PREFIX "_ruby_mjit_"
780+
777781
#ifdef _MSC_VER
778782

779783
/* Compile C file to so. It returns 1 if it succeeds. (mswin) */
@@ -808,7 +812,7 @@ compile_c_to_so(const char *c_file, const char *so_file)
808812
return exit_code == 0;
809813
}
810814

811-
#else
815+
#else /* _MSC_VER */
812816

813817
/* Compile .c file to .o file. It returns 1 if it succeeds. (non-mswin) */
814818
static int
@@ -841,24 +845,23 @@ compile_c_to_o(const char *c_file, const char *o_file)
841845
return exit_code == 0;
842846
}
843847

844-
/* Link .o file to .so file. It returns 1 if it succeeds. (non-mswin) */
848+
/* Link .o files to .so file. It returns 1 if it succeeds. (non-mswin) */
845849
static int
846-
link_o_to_so(const char *o_file, const char *so_file)
850+
link_o_to_so(const char **o_files, const char *so_file)
847851
{
848852
int exit_code;
849-
const char *files[] = {
850-
"-o", NULL, NULL,
853+
const char *options[] = {
854+
"-o", NULL,
851855
# ifdef _WIN32
852856
libruby_pathflag,
853857
# endif
854858
NULL
855859
};
856860
char **args;
857861

858-
files[1] = so_file;
859-
files[2] = o_file;
860-
args = form_args(5, CC_LDSHARED_ARGS, CC_CODEFLAG_ARGS,
861-
files, CC_LIBS, CC_DLDFLAGS_ARGS);
862+
options[1] = so_file;
863+
args = form_args(6, CC_LDSHARED_ARGS, CC_CODEFLAG_ARGS,
864+
options, o_files, CC_LIBS, CC_DLDFLAGS_ARGS);
862865
if (args == NULL)
863866
return FALSE;
864867

@@ -870,7 +873,94 @@ link_o_to_so(const char *o_file, const char *so_file)
870873
return exit_code == 0;
871874
}
872875

876+
/* Link all cached .o files and build a .so file. Reload all JIT func from it. This
877+
allows to avoid JIT code fragmentation and improve performance to call JIT-ed code. */
878+
static void
879+
compact_all_jit_code(void)
880+
{
881+
struct rb_mjit_unit *unit;
882+
struct rb_mjit_unit_node *node;
883+
double start_time, end_time;
884+
static const char so_ext[] = DLEXT;
885+
char so_file[MAXPATHLEN];
886+
const char **o_files;
887+
int i = 0, success;
888+
889+
/* Abnormal use case of rb_mjit_unit that doesn't have ISeq */
890+
unit = (struct rb_mjit_unit *)calloc(1, sizeof(struct rb_mjit_unit)); /* To prevent GC, don't use ZALLOC */
891+
if (unit == NULL) return;
892+
unit->id = current_unit_num++;
893+
sprint_uniq_filename(so_file, (int)sizeof(so_file), unit->id, MJIT_TMP_PREFIX, so_ext);
894+
895+
/* NULL-ending for form_args */
896+
o_files = (const char **)alloca(sizeof(char *) * (active_units.length + 1));
897+
o_files[active_units.length] = NULL;
898+
CRITICAL_SECTION_START(3, "in compact_all_jit_code to keep .o files");
899+
for (node = active_units.head; node != NULL; node = node->next) {
900+
o_files[i] = node->unit->o_file;
901+
i++;
902+
}
903+
904+
start_time = real_ms_time();
905+
success = link_o_to_so(o_files, so_file);
906+
end_time = real_ms_time();
907< F438 code class="diff-text syntax-highlighted-line addition">+
908+
/* TODO: Shrink this big critical section. For now, this is needed to prevent failure by missing .o files.
909+
This assumes that o -> so link doesn't take long time because the bottleneck, which is compiler optimization,
910+
is already done. But actually it takes about 500ms for 5,000 methods on my Linux machine, so it's better to
911+
finish this critical section before link_o_to_so by disabling unload_units. */
912+
CRITICAL_SECTION_FINISH(3, "in compact_all_jit_code to keep .o files");
913+
914+
if (success) {
915+
void *handle = dlopen(so_file, RTLD_NOW);
916+
if (handle == NULL) {
917+
if (mjit_opts.warnings || mjit_opts.verbose)
918+
fprintf(stderr, "MJIT warning: failure in loading code from compacted '%s': %s\n", so_file, dlerror());
919+
free(unit);
920+
return;
921+
}
922+
unit->handle = handle;
923+
924+
/* lazily dlclose handle (and .so file for win32) on `mjit_finish()`. */
925+
node = (struct rb_mjit_unit_node *)calloc(1, sizeof(struct rb_mjit_unit_node)); /* To prevent GC, don't use ZALLOC */
926+
node->unit = unit;
927+
add_to_list(node, &compact_units);
928+
929+
if (!mjit_opts.save_temps) {
930+
#ifdef _WIN32
931+
unit->so_file = strdup(so_file); /* lazily delete on `clean_object_files()` */
932+
#else
933+
remove_file(so_file);
873934
#endif
935+
}
936+
937+
CRITICAL_SECTION_START(3, "in compact_all_jit_code to read list");
938+
for (node = active_units.head; node != NULL; node = node->next) {
939+
void *func;
940+
char funcname[35]; /* TODO: reconsider `35` */
941+
sprintf(funcname, "_mjit%d", node->unit->id);
942+
943+
if ((func = dlsym(handle, funcname)) == NULL) {
944+
if (mjit_opts.warnings || mjit_opts.verbose)
945+
fprintf(stderr, "MJIT warning: skipping to reload '%s' from '%s': %s\n", funcname, so_file, dlerror());
946+
continue;
947+
}
948+
949+
if (node->unit->iseq) { /* Check whether GCed or not */
950+
/* Usage of jit_code might be not in a critical section. */
951+
MJIT_ATOMIC_SET(node->unit->iseq->body->jit_func, (mjit_func_t)func);
952+
}
953+
}
954+
CRITICAL_SECTION_FINISH(3, "in compact_all_jit_code to read list");
955+
verbose(1, "JIT compaction (%.1fms): Compacted %d methods -> %s", end_time - start_time, active_units.length, so_file);
956+
}
957+
else {
958+
free(unit);
959+
verbose(1, "JIT compaction failure (%.1fms): Failed to compact methods", end_time - start_time);
960+
}
961+
}
962+
963+
#endif /* _MSC_VER */
874964

875965
static void *
876966
load_func_from_so(const char *so_file, const char *funcname, struct rb_mjit_unit *unit)
@@ -889,8 +979,6 @@ load_func_from_so(const char *so_file, const char *funcname, struct rb_mjit_unit
889979
return func;
890980
}
891981

892-
#define MJIT_TMP_PREFIX "_ruby_mjit_"
893-
894982
#ifndef __clang__
895983
static const char *
896984
header_name_end(const char *s)
@@ -930,7 +1018,7 @@ remove_file(const char *filename)
9301018
static mjit_func_t
9311019
convert_unit_to_func(struct rb_mjit_unit *unit)
9321020
{
933-
char c_file_buff[70], *c_file = c_file_buff, *so_file, funcname[35];
1021+
char c_file_buff[MAXPATHLEN], *c_file = c_file_buff, *so_file, funcname[35]; /* TODO: reconsider `35` */
9341022
int success;
9351023
int fd;
9361024
FILE *f;
@@ -1045,7 +1133,8 @@ convert_unit_to_func(struct rb_mjit_unit *unit)
10451133
#else
10461134
/* splitting .c -> .o step and .o -> .so step, to cache .o files in the future */
10471135
if (success = compile_c_to_o(c_file, o_file)) {
1048-
success = link_o_to_so(o_file, so_file);
1136+
const char *o_files[] = { o_file, NULL };
1137+
success = link_o_to_so(o_files, so_file);
10491138

10501139
if (!mjit_opts.save_temps)
10511140
unit->o_file = strdup(o_file); /* lazily delete on `clean_object_files()` */
@@ -1127,6 +1216,13 @@ worker(void)
11271216
}
11281217
remove_from_list(node, &unit_queue);
11291218
CRITICAL_SECTION_FINISH(3, "in jit func replace");
1219+
1220+
#ifndef _MSC_VER
1221+
/* Combine .o files to one .so and reload all jit_func to improve memory locality */
1222+
if ((unit_queue.length == 0 && active_units.length > 1) || active_units.length == mjit_opts.max_cache_size) {
1223+
compact_all_jit_code();
1224+
}
1225+
#endif
11301226
}
11311227
}
11321228

@@ -1699,6 +1795,7 @@ mjit_finish(void)
16991795
mjit_call_p = FALSE;
17001796
free_list(&unit_queue);
17011797
free_list(&active_units);
1798+
free_list(&compact_units);
17021799
finish_conts();
17031800

17041801
mjit_enabled = FALSE;

test/ruby/test_jit.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@
77
class TestJIT < Test::Unit::TestCase
88
include JITSupport
99

10+
IGNORABLE_PATTERNS = [
11+
/\ASuccessful MJIT finish\n\z/,
12+
/\AJIT compaction \(\d+\.\dms\): Compacted \d+ methods ->/,
13+
]
14+
1015
# trace_* insns are not compiled for now...
1116
TEST_PENDING_INSNS = RubyVM::INSTRUCTION_NAMES.select { |n| n.start_with?('trace_') }.map(&:to_sym) + [
1217
# not supported yet
@@ -544,7 +549,9 @@ def mjit#{i}
544549
end
545550
end;
546551
assert_equal('0123456789', out)
547-
errs = err.lines
552+
errs = err.lines.reject do |l|
553+
IGNORABLE_PATTERNS.any? { |pat| pat.match?(l) }
554+
end
548555
assert_match(/\A#{JIT_SUCCESS_PREFIX}: block in <main>@-e:/, errs[0])
549556
9.times do |i|
550557
assert_match(/\A#{JIT_SUCCESS_PREFIX}: mjit#{i}@\(eval\):/, errs[i + 1])
@@ -776,7 +783,9 @@ def assert_eval_with_jit(script, stdout: nil, success_count:, min_calls: 1, insn
776783
if stdout
777784
assert_equal(stdout, out, "Expected stdout #{out.inspect} to match #{stdout.inspect} with script:\n#{code_block(script)}")
778785
end
779-
err_lines = err.lines.reject! { | 5ECC l| l.chomp.empty? || l.match?(/\A#{JIT_SUCCESS_PREFIX}/) || l == "Successful MJIT finish\n" }
786+
err_lines = err.lines.reject! do |l|
787+
l.chomp.empty? || l.match?(/\A#{JIT_SUCCESS_PREFIX}/) || IGNORABLE_PATTERNS.any? { |pat| pat.match?(l) }
788+
end
780789
unless err_lines.empty?
781790
warn err_lines.join(''), uplevel: uplevel
782791
end

0 commit comments

Comments
 (0)
0