-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
pyjit.cpp
1281 lines (1123 loc) · 37.6 KB
/
pyjit.cpp
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
#include "Jit/pyjit.h"
#include "Python.h"
//#include "internal/pycore_pystate.h"
#include "internal/pycore_shadow_frame.h"
#include "Include/internal/pycore_pystate.h"
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <atomic>
#include <chrono>
#include <memory>
#include <thread>
#include <unordered_set>
#include "Jit/codegen/gen_asm.h"
#include "Jit/frame.h"
#include "Jit/hir/builder.h"
#include "Jit/jit_context.h"
#include "Jit/jit_gdb_support.h"
#include "Jit/jit_list.h"
#include "Jit/jit_x_options.h"
#include "Jit/log.h"
#include "Jit/perf_jitdump.h"
#include "Jit/ref.h"
#include "Jit/runtime.h"
#define DEFAULT_CODE_SIZE 2 * 1024 * 1024
using namespace jit;
enum InitState { JIT_NOT_INITIALIZED, JIT_INITIALIZED, JIT_FINALIZED };
enum FrameMode { PY_FRAME = 0, NO_FRAME, SHADOW_FRAME };
struct JitConfig {
InitState init_state{JIT_NOT_INITIALIZED};
int is_enabled{0};
FrameMode frame_mode{PY_FRAME};
int are_type_slots_enabled{0};
int allow_jit_list_wildcards{0};
int compile_all_static_functions{0};
size_t batch_compile_workers{0};
int test_multithreaded_compile{0};
};
JitConfig jit_config;
namespace {
// Extra information needed to compile a PyCodeObject.
struct CodeData {
CodeData(PyObject* m, PyObject* g) : module{m}, globals{g} {}
Ref<> module;
Ref<PyDictObject> globals;
};
} // namespace
static _PyJITContext* jit_ctx;
static JITList* g_jit_list{nullptr};
// Function and code objects registered for compilation. Every entry that is a
// code object has corresponding entry in jit_code_data.
static std::unordered_set<BorrowedRef<>> jit_reg_units;
static std::unordered_map<BorrowedRef<PyCodeObject>, CodeData> jit_code_data;
// Strong references to every function and code object that were ever
// registered, to keep them alive for batch testing.
static std::vector<Ref<>> test_multithreaded_units;
static std::unordered_map<PyFunctionObject*, std::chrono::duration<double>>
jit_time_functions;
// Frequently-used strings that we intern at JIT startup and hold references to.
#define INTERNED_STRINGS(X) \
X(func_fullname) \
X(filename) \
X(lineno) \
X(count) \
X(reason) \
X(guilty_type) \
X(description)
#define DECLARE_STR(s) static PyObject* s_str_##s{nullptr};
INTERNED_STRINGS(DECLARE_STR)
#undef DECLARE_STR
static double total_compliation_time = 0.0;
// This is read directly from ceval.c to minimize overhead.
int g_capture_interp_cost = 0;
static std::unordered_map<std::string, long> g_code_interp_cost;
struct CompilationTimer {
explicit CompilationTimer(BorrowedRef<PyFunctionObject> f)
: start(std::chrono::steady_clock::now()), func(f) {}
~CompilationTimer() {
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> time_span =
std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
double time = time_span.count();
total_compliation_time += time;
jit::ThreadedCompileSerialize guard;
jit_time_functions.emplace(func, time_span);
}
std::chrono::steady_clock::time_point start;
BorrowedRef<PyFunctionObject> func{nullptr};
};
static std::atomic<int> g_compile_workers_attempted;
static int g_compile_workers_retries;
// Compile the given compilation unit, returning the result code.
static _PyJIT_Result compileUnit(BorrowedRef<> unit) {
if (PyFunction_Check(unit)) {
BorrowedRef<PyFunctionObject> func(unit);
CompilationTimer t{func};
return _PyJITContext_CompileFunction(jit_ctx, func);
}
JIT_CHECK(PyCode_Check(unit), "Expected function or code object");
BorrowedRef<PyCodeObject> code(unit);
const CodeData& data = map_get(jit_code_data, code);
return _PyJITContext_CompileCode(jit_ctx, data.module, code, data.globals);
}
static void compile_worker_thread() {
JIT_DLOG("Started compile worker in thread %d", std::this_thread::get_id());
BorrowedRef<> unit;
while ((unit = g_threaded_compile_context.nextUnit()) != nullptr) {
g_compile_workers_attempted++;
if (compileUnit(unit) == PYJIT_RESULT_RETRY) {
ThreadedCompileSerialize guard;
g_compile_workers_retries++;
g_threaded_compile_context.retryUnit(unit);
JIT_LOG(
"Retrying compile of function: %s",
funcFullname(reinterpret_cast<PyFunctionObject*>(unit.get())));
}
}
JIT_DLOG("Finished compile worker in thread %d", std::this_thread::get_id());
}
static void multithread_compile_all(std::vector<BorrowedRef<>>&& work_units) {
JIT_CHECK(jit_ctx, "JIT not initialized");
// Disable checks for using GIL protected data across threads.
// Conceptually what we're doing here is saying we're taking our own
// responsibility for managing locking of CPython runtime data structures.
// Instead of holding the GIL to serialize execution to one thread, we're
// holding the GIL for a group of co-operating threads which are aware of each
// other. We still need the GIL as this protects the cooperating threads from
// unknown other threads. Within our group of cooperating threads we can
// safely do any read-only operations in parallel, but we grab our own lock if
// we do a write (e.g. an incref).
int old_gil_check_enabled = _PyGILState_check_enabled;
_PyGILState_check_enabled = 0;
g_threaded_compile_context.startCompile(std::move(work_units));
std::vector<std::thread> worker_threads;
JIT_CHECK(jit_config.batch_compile_workers, "Zero workers for compile");
{
// Hold a lock while we create threads because IG production has magic to
// wrap pthread_create() and run Python code before threads are created.
ThreadedCompileSerialize guard;
for (size_t i = 0; i < jit_config.batch_compile_workers; i++) {
worker_threads.emplace_back(compile_worker_thread);
}
}
for (std::thread& worker_thread : worker_threads) {
worker_thread.join();
}
std::vector<BorrowedRef<>> retry_list{
g_threaded_compile_context.endCompile()};
for (auto unit : retry_list) {
compileUnit(unit);
}
_PyGILState_check_enabled = old_gil_check_enabled;
}
static PyObject* test_multithreaded_compile(PyObject*, PyObject*) {
if (!jit_config.test_multithreaded_compile) {
PyErr_SetString(
PyExc_NotImplementedError, "test_multithreaded_compile not enabled");
return NULL;
}
g_compile_workers_attempted = 0;
g_compile_workers_retries = 0;
JIT_LOG("(Re)compiling %d units", jit_reg_units.size());
std::chrono::time_point time_start = std::chrono::steady_clock::now();
multithread_compile_all(
{test_multithreaded_units.begin(), test_multithreaded_units.end()});
std::chrono::time_point time_end = std::chrono::steady_clock::now();
JIT_LOG(
"Took %d ms, compiles attempted: %d, compiles retried: %d",
std::chrono::duration_cast<std::chrono::milliseconds>(
time_end - time_start)
.count(),
g_compile_workers_attempted,
g_compile_workers_retries);
test_multithreaded_units.clear();
Py_RETURN_NONE;
}
static PyObject* is_test_multithreaded_compile_enabled(PyObject*, PyObject*) {
if (jit_config.test_multithreaded_compile) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject*
disable_jit(PyObject* /* self */, PyObject* const* args, Py_ssize_t nargs) {
if (nargs > 1) {
PyErr_SetString(PyExc_TypeError, "disable expects 0 or 1 arg");
return NULL;
} else if (nargs == 1 && !PyBool_Check(args[0])) {
PyErr_SetString(
PyExc_TypeError,
"disable expects bool indicating to compile pending functions");
return NULL;
}
if (nargs == 0 || args[0] == Py_True) {
// Compile all of the pending functions/codes before shutting down
if (jit_config.batch_compile_workers > 0) {
multithread_compile_all({jit_reg_units.begin(), jit_reg_units.end()});
jit_reg_units.clear();
} else {
std::unordered_set<BorrowedRef<>> units;
units.swap(jit_reg_units);
for (auto unit : units) {
compileUnit(unit);
}
}
jit_code_data.clear();
}
_PyJIT_Disable();
Py_RETURN_NONE;
}
static PyObject* force_compile(PyObject* /* self */, PyObject* func) {
if (!PyFunction_Check(func)) {
PyErr_SetString(PyExc_TypeError, "force_compile expected a function");
return NULL;
}
if (jit_reg_units.count(func)) {
_PyJIT_CompileFunction((PyFunctionObject*)func);
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
int _PyJIT_IsCompiled(PyObject* func) {
if (jit_ctx == nullptr) {
return 0;
}
if (!PyFunction_Check(func)) {
return 0;
}
return _PyJITContext_DidCompile(jit_ctx, func);
}
static PyObject* is_jit_compiled(PyObject* /* self */, PyObject* func) {
int st = _PyJIT_IsCompiled(func);
PyObject* res = NULL;
if (st == 1) {
res = Py_True;
} else if (st == 0) {
res = Py_False;
}
Py_XINCREF(res);
return res;
}
static PyObject* print_hir(PyObject* /* self */, PyObject* func) {
if (!PyFunction_Check(func)) {
PyErr_SetString(PyExc_TypeError, "arg 1 must be a function");
return NULL;
}
int st = _PyJITContext_DidCompile(jit_ctx, func);
if (st == -1) {
return NULL;
} else if (st == 0) {
PyErr_SetString(PyExc_ValueError, "function is not jit compiled");
return NULL;
}
if (_PyJITContext_PrintHIR(jit_ctx, func) < 0) {
return NULL;
} else {
Py_RETURN_NONE;
}
}
static PyObject* disassemble(PyObject* /* self */, PyObject* func) {
if (!PyFunction_Check(func)) {
PyErr_SetString(PyExc_TypeError, "arg 1 must be a function");
return NULL;
}
int st = _PyJITContext_DidCompile(jit_ctx, func);
if (st == -1) {
return NULL;
} else if (st == 0) {
PyErr_SetString(PyExc_ValueError, "function is not jit compiled");
return NULL;
}
if (_PyJITContext_Disassemble(jit_ctx, func) < 0) {
return NULL;
} else {
Py_RETURN_NONE;
}
}
static PyObject* get_jit_list(PyObject* /* self */, PyObject*) {
if (g_jit_list == nullptr) {
Py_RETURN_NONE;
} else {
auto jit_list = Ref<>::steal(g_jit_list->getList());
return jit_list.release();
}
}
static PyObject* get_compiled_functions(PyObject* /* self */, PyObject*) {
return _PyJITContext_GetCompiledFunctions(jit_ctx);
}
static PyObject* get_compilation_time(PyObject* /* self */, PyObject*) {
PyObject* res =
PyLong_FromLong(static_cast<long>(total_compliation_time * 1000));
return res;
}
static PyObject* get_function_compilation_time(
PyObject* /* self */,
PyObject* func) {
auto iter =
jit_time_functions.find(reinterpret_cast<PyFunctionObject*>(func));
if (iter == jit_time_functions.end()) {
Py_RETURN_NONE;
}
PyObject* res = PyLong_FromLong(iter->second.count() * 1000);
return res;
}
static Ref<> make_deopt_stats() {
Runtime* runtime = codegen::NativeGenerator::runtime();
auto stats = Ref<>::steal(PyList_New(0));
if (stats == nullptr) {
return nullptr;
}
for (auto& pair : runtime->deoptStats()) {
const DeoptMetadata& meta = runtime->getDeoptMetadata(pair.first);
const DeoptStat& stat = pair.second;
CodeRuntime& code_rt = *meta.code_rt;
BorrowedRef<PyCodeObject> code = code_rt.GetCode();
auto event = Ref<>::steal(PyDict_New());
if (event == nullptr) {
return nullptr;
}
auto func_fullname = code->co_qualname;
int lineno_raw = code->co_lnotab != nullptr
? PyCode_Addr2Line(code, meta.next_instr_offset)
: -1;
auto lineno = Ref<>::steal(PyLong_FromLong(lineno_raw));
if (lineno == nullptr) {
return nullptr;
}
auto reason =
Ref<>::steal(PyUnicode_FromString(deoptReasonName(meta.reason)));
if (reason == nullptr) {
return nullptr;
}
auto description = Ref<>::steal(PyUnicode_FromString(meta.descr));
if (description == nullptr) {
return nullptr;
}
if (PyDict_SetItem(event, s_str_func_fullname, func_fullname) < 0 ||
PyDict_SetItem(event, s_str_filename, code->co_filename) < 0 ||
PyDict_SetItem(event, s_str_lineno, lineno) < 0 ||
PyDict_SetItem(event, s_str_reason, reason) < 0 ||
PyDict_SetItem(event, s_str_description, description) < 0) {
return nullptr;
}
Ref<> event_copy;
// Helper to copy the event dict and stick in a new count value, reusing
// the original for the first "copy".
auto append_copy = [&](size_t count_raw, const char* type) {
if (event_copy == nullptr) {
event_copy = std::move(event);
} else {
event_copy = Ref<>::steal(PyDict_Copy(event_copy));
if (event_copy == nullptr) {
return false;
}
}
auto count = Ref<>::steal(PyLong_FromSize_t(count_raw));
if (count == nullptr ||
PyDict_SetItem(event_copy, s_str_count, count) < 0) {
return false;
}
auto type_str = Ref<>::steal(PyUnicode_InternFromString(type));
if (type_str == nullptr ||
PyDict_SetItem(event_copy, s_str_guilty_type, type_str) < 0) {
return false;
}
return PyList_Append(stats, event_copy) == 0;
};
// For deopts with type profiles, add a copy of the dict with counts for
// each type, including "other".
if (!stat.types.empty()) {
for (size_t i = 0; i < stat.types.size && stat.types.types[i] != nullptr;
++i) {
if (!append_copy(stat.types.counts[i], stat.types.types[i]->tp_name)) {
return nullptr;
}
}
if (stat.types.other > 0 && !append_copy(stat.types.other, "other")) {
return nullptr;
}
} else if (!append_copy(stat.count, "<none>")) {
return nullptr;
}
}
runtime->clearDeoptStats();
return stats;
}
static PyObject* get_and_clear_runtime_stats(PyObject* /* self */, PyObject*) {
auto stats = Ref<>::steal(PyDict_New());
if (stats == nullptr) {
return nullptr;
}
Ref<> deopt_stats = make_deopt_stats();
if (deopt_stats == nullptr) {
return nullptr;
}
if (PyDict_SetItemString(stats, "deopt", deopt_stats) < 0) {
return nullptr;
}
return stats.release();
}
static PyObject* clear_runtime_stats(PyObject* /* self */, PyObject*) {
codegen::NativeGenerator::runtime()->clearDeoptStats();
Py_RETURN_NONE;
}
static PyObject* get_compiled_size(PyObject* /* self */, PyObject* func) {
if (jit_ctx == NULL) {
return PyLong_FromLong(0);
}
long size = _PyJITContext_GetCodeSize(jit_ctx, func);
PyObject* res = PyLong_FromLong(size);
return res;
}
static PyObject* get_compiled_stack_size(PyObject* /* self */, PyObject* func) {
if (jit_ctx == NULL) {
return PyLong_FromLong(0);
}
long size = _PyJITContext_GetStackSize(jit_ctx, func);
PyObject* res = PyLong_FromLong(size);
return res;
}
static PyObject* get_compiled_spill_stack_size(
PyObject* /* self */,
PyObject* func) {
if (jit_ctx == NULL) {
return PyLong_FromLong(0);
}
long size = _PyJITContext_GetSpillStackSize(jit_ctx, func);
PyObject* res = PyLong_FromLong(size);
return res;
}
static PyObject* jit_frame_mode(PyObject* /* self */, PyObject*) {
return PyLong_FromLong(jit_config.frame_mode);
}
static PyObject* get_supported_opcodes(PyObject* /* self */, PyObject*) {
auto set = Ref<>::steal(PySet_New(nullptr));
if (set == nullptr) {
return nullptr;
}
for (auto op : hir::kSupportedOpcodes) {
auto op_obj = Ref<>::steal(PyLong_FromLong(op));
if (op_obj == nullptr) {
return nullptr;
}
if (PySet_Add(set, op_obj) < 0) {
return nullptr;
}
}
return set.release();
}
static PyObject* jit_force_normal_frame(PyObject*, PyObject* func_obj) {
if (!PyFunction_Check(func_obj)) {
PyErr_SetString(PyExc_TypeError, "Input must be a function");
return NULL;
}
PyFunctionObject* func = reinterpret_cast<PyFunctionObject*>(func_obj);
reinterpret_cast<PyCodeObject*>(func->func_code)->co_flags |= CO_NORMAL_FRAME;
Py_INCREF(func_obj);
return func_obj;
}
extern "C" {
PyObject* _PyJIT_GetAndClearCodeInterpCost(void) {
if (!g_capture_interp_cost) {
Py_RETURN_NONE;
}
PyObject* dict = PyDict_New();
if (dict == NULL) {
return NULL;
}
for (const auto& entry : g_code_interp_cost) {
PyDict_SetItemString(
dict, entry.first.c_str(), PyLong_FromLong(entry.second));
}
g_code_interp_cost.clear();
return dict;
}
}
static PyMethodDef jit_methods[] = {
{"disable",
(PyCFunction)(void*)disable_jit,
METH_FASTCALL,
"Disable the jit."},
{"disassemble", disassemble, METH_O, "Disassemble JIT compiled functions"},
{"is_jit_compiled",
is_jit_compiled,
METH_O,
"Check if a function is jit compiled."},
{"force_compile",
force_compile,
METH_O,
"Force a function to be JIT compiled if it hasn't yet"},
{"jit_frame_mode",
jit_frame_mode,
METH_NOARGS,
"Get JIT frame mode (0 = normal frames, 1 = no frames, 2 = shadow frames"},
{"get_jit_list", get_jit_list, METH_NOARGS, "Get the JIT-list"},
{"print_hir",
print_hir,
METH_O,
"Print the HIR for a jitted function to stdout."},
{"get_supported_opcodes",
get_supported_opcodes,
METH_NOARGS,
"Return a set of all supported opcodes, as ints."},
{"get_compiled_functions",
get_compiled_functions,
METH_NOARGS,
"Return a list of functions that are currently JIT-compiled."},
{"get_compilation_time",
get_compilation_time,
METH_NOARGS,
"Return the total time used for JIT compiling functions in milliseconds."},
{"get_function_compilation_time",
get_function_compilation_time,
METH_O,
"Return the time used for JIT compiling a given function in "
"milliseconds."},
{"get_and_clear_runtime_stats",
get_and_clear_runtime_stats,
METH_NOARGS,
"Returns information about the runtime behavior of JIT-compiled code."},
{"clear_runtime_stats",
clear_runtime_stats,
METH_NOARGS,
"Clears runtime stats about JIT-compiled code without returning a value."},
{"get_compiled_size",
get_compiled_size,
METH_O,
"Return code size in bytes for a JIT-compiled function."},
{"get_compiled_stack_size",
get_compiled_stack_size,
METH_O,
"Return stack size in bytes for a JIT-compiled function."},
{"get_compiled_spill_stack_size",
get_compiled_spill_stack_size,
METH_O,
"Return stack size in bytes used for register spills for a JIT-compiled "
"function."},
{"jit_force_normal_frame",
jit_force_normal_frame,
METH_O,
"Decorator forcing a function to always use normal frame mode when JIT."},
{"test_multithreaded_compile",
test_multithreaded_compile,
METH_NOARGS,
"Force multi-threaded recompile of still existing JIT functions for test"},
{"is_test_multithreaded_compile_enabled",
is_test_multithreaded_compile_enabled,
METH_NOARGS,
"Return True if test_multithreaded_compile mode is enabled"},
{NULL, NULL, 0, NULL}};
static PyModuleDef jit_module = {
PyModuleDef_HEAD_INIT,
.m_name = "cinderjit",
.m_doc = NULL,
.m_size = -1,
.m_methods = jit_methods,
.m_slots = nullptr,
.m_traverse = nullptr,
.m_clear = nullptr,
.m_free = nullptr};
static int onJitListImpl(
BorrowedRef<PyCodeObject> code,
BorrowedRef<> module,
BorrowedRef<> qualname) {
bool is_static = code->co_flags & CO_STATICALLY_COMPILED;
if (g_jit_list == nullptr ||
(is_static && jit_config.compile_all_static_functions)) {
// There's no jit list or the function is static.
return 1;
}
return g_jit_list->lookup(module, qualname);
}
int _PyJIT_OnJitList(PyFunctionObject* func) {
return onJitListImpl(func->func_code, func->func_module, func->func_qualname);
}
// Is env var set to a value other than "0" or ""?
int _is_env_truthy(const char* name) {
const char* val = Py_GETENV(name);
if (val == NULL || val[0] == '\0' || !strncmp(val, "0", 1)) {
return 0;
}
return 1;
}
int _is_flag_set(const char* xoption, const char* envname) {
if (PyJIT_IsXOptionSet(xoption) || _is_env_truthy(envname)) {
return 1;
}
return 0;
}
// If the given X option is set and is a string, return it. If not, check the
// given environment variable for a nonempty value and return it if
// found. Otherwise, return nullptr.
const char* flag_string(const char* xoption, const char* envname) {
PyObject* pyobj = nullptr;
if (PyJIT_GetXOption(xoption, &pyobj) == 0 && pyobj != nullptr &&
PyUnicode_Check(pyobj)) {
return PyUnicode_AsUTF8(pyobj);
}
auto envval = Py_GETENV(envname);
if (envval != nullptr && envval[0] != '\0') {
return envval;
}
return nullptr;
}
long flag_long(const char* xoption, const char* envname, long _default) {
PyObject* pyobj = nullptr;
if (PyJIT_GetXOption(xoption, &pyobj) == 0 && pyobj != nullptr &&
PyUnicode_Check(pyobj)) {
auto val = Ref<PyObject>::steal(PyLong_FromUnicodeObject(pyobj, 10));
if (val != nullptr) {
return PyLong_AsLong(val);
}
JIT_LOG("Invalid value for %s: %s", xoption, PyUnicode_AsUTF8(pyobj));
}
const char* envval = Py_GETENV(envname);
if (envval != nullptr && envval[0] != '\0') {
try {
return std::stol(envval);
} catch (std::exception const&) {
JIT_LOG("Invalid value for %s: %s", envname, envval);
}
}
return _default;
}
int _PyJIT_Initialize() {
if (jit_config.init_state == JIT_INITIALIZED) {
return 0;
}
int use_jit = 0;
if (_is_flag_set("jit", "PYTHONJIT")) {
use_jit = 1;
}
// Redirect logging to a file if configured.
const char* log_filename = flag_string("jit-log-file", "PYTHONJITLOGFILE");
if (log_filename != nullptr) {
const char* kPidMarker = "{pid}";
std::string pid_filename = log_filename;
auto marker_pos = pid_filename.find(kPidMarker);
if (marker_pos != std::string::npos) {
pid_filename.replace(
marker_pos, std::strlen(kPidMarker), fmt::format("{}", getpid()));
}
FILE* file = fopen(pid_filename.c_str(), "w");
if (file == NULL) {
JIT_LOG(
"Couldn't open log file %s (%s), logging to stderr",
pid_filename,
strerror(errno));
} else {
g_log_file = file;
}
}
if (_is_flag_set("jit-debug", "PYTHONJITDEBUG")) {
JIT_DLOG("Enabling JIT debug and extra logging.");
g_debug = 1;
g_debug_verbose = 1;
}
if (_is_flag_set("jit-debug-refcount", "PYTHONJITDEBUGREFCOUNT")) {
JIT_DLOG("Enabling JIT refcount insertion debug mode.");
g_debug_refcount = 1;
}
if (_is_flag_set("jit-dump-hir", "PYTHONJITDUMPHIR")) {
JIT_DLOG("Enabling JIT dump-hir mode.");
g_dump_hir = 1;
}
if (_is_flag_set("jit-dump-hir-passes", "PYTHONJITDUMPHIRPASSES")) {
JIT_DLOG("Enabling JIT dump-hir-passes mode.");
g_dump_hir_passes = 1;
}
if (_is_flag_set("jit-dump-final-hir", "PYTHONJITDUMPFINALHIR")) {
JIT_DLOG("Enabling JIT dump-final-hir mode.");
g_dump_final_hir = 1;
}
if (_is_flag_set("jit-dump-lir", "PYTHONJITDUMPLIR")) {
JIT_DLOG("Enable JIT dump-lir mode with origin data.");
g_dump_lir = 1;
}
if (_is_flag_set("jit-dump-lir-no-origin", "PYTHONJITDUMPLIRNOORIGIN")) {
JIT_DLOG("Enable JIT dump-lir mode without origin data.");
g_dump_lir = 1;
g_dump_lir_no_origin = 1;
}
if (_is_flag_set("jit-dump-c-helper", "PYTHONJITDUMPCHELPER")) {
JIT_DLOG("Enable JIT dump-c-helper mode.");
g_dump_c_helper = 1;
}
if (_is_flag_set("jit-disas-funcs", "PYTHONJITDISASFUNCS")) {
JIT_DLOG("Enabling JIT disas-funcs mode.");
g_disas_funcs = 1;
}
if (_is_flag_set("jit-gdb-support", "PYTHONJITGDBSUPPORT")) {
JIT_DLOG("Enable GDB support and JIT debug mode.");
g_debug = 1;
g_gdb_support = 1;
}
if (_is_flag_set("jit-gdb-stubs-support", "PYTHONJITGDBSUPPORT")) {
JIT_DLOG("Enable GDB support for stubs.");
g_gdb_stubs_support = 1;
}
if (_is_flag_set("jit-gdb-write-elf", "PYTHONJITGDBWRITEELF")) {
JIT_DLOG("Enable GDB support with ELF output, and JIT debug.");
g_debug = 1;
g_gdb_support = 1;
g_gdb_write_elf_objects = 1;
}
if (_is_flag_set("jit-dump-stats", "PYTHONJITDUMPSTATS")) {
JIT_DLOG("Dumping JIT runtime stats at shutdown.");
g_dump_stats = 1;
}
if (_is_flag_set(
"jit-enable-jit-list-wildcards", "PYTHONJITENABLEJITLISTWILDCARDS")) {
JIT_LOG("Enabling wildcards in JIT list");
jit_config.allow_jit_list_wildcards = 1;
}
if (_is_flag_set("jit-all-static-functions", "PYTHONJITALLSTATICFUNCTIONS")) {
JIT_DLOG("JIT-compiling all static functions");
jit_config.compile_all_static_functions = 1;
}
std::unique_ptr<JITList> jit_list;
const char* jl_fn = flag_string("jit-list-file", "PYTHONJITLISTFILE");
if (jl_fn != NULL) {
use_jit = 1;
if (jit_config.allow_jit_list_wildcards) {
jit_list = jit::WildcardJITList::create();
} else {
jit_list = jit::JITList::create();
}
if (jit_list == nullptr) {
JIT_LOG("Failed to allocate JIT list");
return -1;
}
if (!jit_list->parseFile(jl_fn)) {
JIT_LOG("Could not parse jit-list, disabling JIT.");
return 0;
}
}
if (_is_flag_set("jit-capture-interp-cost", "PYTHONJITCAPTUREINTERPCOST")) {
if (use_jit) {
use_jit = 0;
JIT_LOG("Keeping JIT disabled to capture interpreter cost.");
}
g_capture_interp_cost = 1;
// Hack to help mitigate the cost of tracing during normal production. See
// ceval.c where the cost counting happens for more details.
_PyRuntime.ceval.tracing_possible++;
}
if (use_jit) {
JIT_DLOG("Enabling JIT.");
} else {
return 0;
}
if (_PyJITContext_Init() == -1) {
JIT_LOG("failed initializing jit context");
return -1;
}
jit_ctx = _PyJITContext_New(std::make_unique<jit::Compiler>());
if (jit_ctx == NULL) {
JIT_LOG("failed creating global jit context");
return -1;
}
PyObject* mod = PyModule_Create(&jit_module);
if (mod == NULL) {
return -1;
}
PyObject* modname = PyUnicode_InternFromString("cinderjit");
if (modname == NULL) {
return -1;
}
PyObject* modules = PyImport_GetModuleDict();
int st = _PyImport_FixupExtensionObject(mod, modname, modname, modules);
Py_DECREF(modname);
if (st == -1) {
return -1;
}
#define INTERN_STR(s) \
s_str_##s = PyUnicode_InternFromString(#s); \
if (s_str_##s == nullptr) { \
return -1; \
}
INTERNED_STRINGS(INTERN_STR)
#undef INTERN_STR
jit_config.init_state = JIT_INITIALIZED;
jit_config.is_enabled = 1;
g_jit_list = jit_list.release();
if (_is_flag_set("jit-no-frame", "PYTHONJITNOFRAME")) {
jit_config.frame_mode = NO_FRAME;
}
if (_is_flag_set("jit-shadow-frame", "PYTHONJITSHADOWFRAME")) {
jit_config.frame_mode = SHADOW_FRAME;
_PyThreadState_GetFrame =
reinterpret_cast<PyThreadFrameGetter>(materializeShadowCallStack);
}
jit_config.are_type_slots_enabled = !PyJIT_IsXOptionSet("jit-no-type-slots");
jit_config.batch_compile_workers =
flag_long("jit-batch-compile-workers", "PYTHONJITBATCHCOMPILEWORKERS", 0);
if (_is_flag_set(
"jit-test-multithreaded-compile",
"PYTHONJITTESTMULTITHREADEDCOMPILE")) {
jit_config.test_multithreaded_compile = 1;
}
total_compliation_time = 0.0;
return 0;
}
static std::string key_for_py_code_object(PyCodeObject* code) {
Py_ssize_t name_len;
PyObject* py_name = code->co_qualname ? code->co_qualname : code->co_name;
const char* name = PyUnicode_AsUTF8AndSize(py_name, &name_len);
Py_ssize_t fn_len;
const char* fn = PyUnicode_AsUTF8AndSize(code->co_filename, &fn_len);
return fmt::format(
"{}@{}:{}",
std::string{name, static_cast<std::string::size_type>(name_len)},
std::string{fn, static_cast<std::string::size_type>(fn_len)},
code->co_firstlineno);
}
static std::unordered_map<PyCodeObject*, std::string> g_code_key_cache_;
void _PyJIT_InvalidateCodeKey(PyCodeObject* code) {
if (!g_capture_interp_cost) {
return;
}
g_code_key_cache_.erase(code);
}
void _PyJIT_BumpCodeInterpCost(PyCodeObject* code, long cost) {
std::string key;
auto key_cache_entry = g_code_key_cache_.find(code);
if (key_cache_entry == g_code_key_cache_.end()) {
key = key_for_py_code_object(reinterpret_cast<PyCodeObject*>(code));
g_code_key_cache_[code] = key;
} else {
key = key_cache_entry->second;
}
auto entry = g_code_interp_cost.find(key);
if (entry == g_code_interp_cost.end()) {
entry = g_code_interp_cost.emplace(key, 0).first;
}
entry->second += cost;
}
int _PyJIT_IsEnabled() {
return (jit_config.init_state == JIT_INITIALIZED) && jit_config.is_enabled;
}
void _PyJIT_AfterFork_Child() {
perf::afterForkChild();
}
int _PyJIT_AreTypeSlotsEnabled() {
return (jit_config.init_state == JIT_INITIALIZED) &&
jit_config.are_type_slots_enabled;
}
int _PyJIT_Enable() {
if (jit_config.init_state != JIT_INITIALIZED) {
return 0;
}
jit_config.is_enabled = 1;
return 0;
}
int _PyJIT_EnableTypeSlots() {
if (!_PyJIT_IsEnabled()) {
return 0;
}
jit_config.are_type_slots_enabled = 1;
return 1;
}
void _PyJIT_Disable() {
jit_config.is_enabled = 0;
jit_config.are_type_slots_enabled = 0;
}
_PyJIT_Result _PyJIT_SpecializeType(
PyTypeObject* type,
_PyJIT_TypeSlots* slots) {
return _PyJITContext_SpecializeType(jit_ctx, type, slots);
}
_PyJIT_Result _PyJIT_CompileFunction(PyFunctionObject* func) {
// Serialize here as we might have been called re-entrantly.
ThreadedCompileSerialize guard;
if (jit_ctx == nullptr) {
return PYJIT_NOT_INITIALIZED;
}
if (!_PyJIT_OnJitList(func)) {
return PYJIT_RESULT_CANNOT_SPECIALIZE;