Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.2k
Expand file tree
/
Copy pathoptimizer_analysis.c
More file actions
Latest commit
831 lines (757 loc) · 26.4 KB
/
Copy pathoptimizer_analysis.c
File metadata and controls
831 lines (757 loc) · 26.4 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
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
#ifdef_Py_TIER2
/*
* This file contains the support code for CPython's uops optimizer.
* It also performs some simple optimizations.
* It performs a traditional data-flow analysis[1] over the trace of uops.
* Using the information gained, it chooses to emit, or skip certain instructions
* if possible.
*
* [1] For information on data-flow analysis, please see
* https://clang.llvm.org/docs/DataFlowAnalysisIntro.html
*
* */
#include"Python.h"
#include"opcode.h"
#include"pycore_dict.h"
#include"pycore_interp.h"
#include"pycore_opcode_metadata.h"
#include"pycore_opcode_utils.h"
#include"pycore_pystate.h"// _PyInterpreterState_GET()
#include"pycore_pyatomic_ft_wrappers.h"// FT_ATOMIC_*
#include"pycore_tstate.h"// _PyThreadStateImpl
#include"pycore_uop_metadata.h"
#include"pycore_long.h"
#include"pycore_interpframe.h"// _PyFrame_GetCode
#include"pycore_optimizer.h"
#include"pycore_object.h"
#include"pycore_function.h"
#include"pycore_uop_ids.h"
#include"pycore_range.h"
#include"pycore_unicodeobject.h"
#include"pycore_ceval.h"
#include"pycore_floatobject.h"
#include"pycore_setobject.h"
#include"pycore_typeobject.h"
#include<stdarg.h>
#include<stdbool.h>
#include<stdint.h>
#include<stddef.h>
#ifdefPy_DEBUG
externconstchar*_PyUOpName(intindex);
externvoid_PyUOpPrint(const_PyUOpInstruction*uop);
externvoid_PyUOpSymPrint(JitOptRefref);
staticconstchar*constDEBUG_ENV="PYTHON_OPT_DEBUG";
staticinlineintget_lltrace(void) {
char*uop_debug=Py_GETENV(DEBUG_ENV);
intlltrace=0;
if (uop_debug!=NULL&&*uop_debug >= '0') {
lltrace=*uop_debug-'0'; // TODO: Parse an int and all that
}
returnlltrace;
}
#defineDPRINTF(level, ...) \
if (get_lltrace() >= (level)) { printf(__VA_ARGS__); }
staticvoid
dump_abstract_stack(_Py_UOpsAbstractFrame*frame, JitOptRef*stack_pointer)
{
printf(" locals=[");
for (inti=0 ; i<frame->locals_len; i++) {
if (i>0) {
printf(", ");
}
_PyUOpSymPrint(frame->locals[i]);
}
printf("]\n");
if (stack_pointer<frame->stack) {
printf(" stack=%d\n", (int)(stack_pointer-frame->stack));
}
else {
printf(" stack=[");
for (JitOptRef*ptr=frame->stack; ptr<stack_pointer; ptr++) {
if (ptr!=frame->stack) {
printf(", ");
}
_PyUOpSymPrint(*ptr);
}
printf("]\n");
}
fflush(stdout);
}
staticvoid
dump_uop(JitOptContext*ctx, constchar*label, intindex,
const_PyUOpInstruction*instr, JitOptRef*stack_pointer)
{
if (get_lltrace() >= 3) {
printf("%4d %s: ", index, label);
_PyUOpPrint(instr);
printf("\n");
if (get_lltrace() >= 5&&ctx->frame->code!= ((PyCodeObject*)&_Py_InitCleanup)) {
dump_abstract_stack(ctx->frame, stack_pointer);
}
}
}
staticvoid
dump_uops(JitOptContext*ctx, constchar*label,
_PyUOpInstruction*start, JitOptRef*stack_pointer)
{
intcurrent_len=uop_buffer_length(&ctx->out_buffer);
intadded_count= (int)(ctx->out_buffer.next-start);
for (intj=0; j<added_count; j++) {
dump_uop(ctx, label, current_len-added_count+j, &start[j], stack_pointer);
}
}
#defineDUMP_UOP dump_uop
#defineDUMP_UOPS dump_uops
#else
#defineDPRINTF(level, ...)
#defineDUMP_UOP(ctx, label, index, instr, stack_pointer)
#defineDUMP_UOPS(ctx, label, start, stack_pointer)
#endif
staticint
get_mutations(PyObject*dict) {
assert(PyDict_CheckExact(dict));
PyDictObject*d= (PyDictObject*)dict;
uint64_ttag=FT_ATOMIC_LOAD_UINT64_RELAXED(d->_ma_watcher_tag);
return (tag >> DICT_MAX_WATCHERS) & ((1 << DICT_WATCHED_MUTATION_BITS) -1);
}
staticvoid
increment_mutations(PyObject*dict) {
assert(PyDict_CheckExact(dict));
PyDictObject*d= (PyDictObject*)dict;
FT_ATOMIC_ADD_UINT64(d->_ma_watcher_tag, 1ULL << DICT_MAX_WATCHERS);
}
/* The first two dict watcher IDs are reserved for CPython,
* so we don't need to check that they haven't been used */
#defineBUILTINS_WATCHER_ID 0
#defineGLOBALS_WATCHER_ID 1
#defineTYPE_WATCHER_ID 0
staticint
globals_watcher_callback(PyDict_WatchEventevent, PyObject*dict,
PyObject*key, PyObject*new_value)
{
RARE_EVENT_STAT_INC(watched_globals_modification);
assert(get_mutations(dict) <_Py_MAX_ALLOWED_GLOBALS_MODIFICATIONS);
_Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), dict, 1);
increment_mutations(dict);
PyDict_Unwatch(GLOBALS_WATCHER_ID, dict);
return0;
}
staticint
type_watcher_callback(PyTypeObject*type)
{
_Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), type, 1);
PyType_Unwatch(TYPE_WATCHER_ID, (PyObject*)type);
return0;
}
staticint
_setup_optimizer_watchers(void*Py_UNUSED(arg))
{
PyInterpreterState*interp=_PyInterpreterState_GET();
FT_ATOMIC_STORE_PTR_RELEASE(
interp->dict_state.watchers[GLOBALS_WATCHER_ID],
globals_watcher_callback);
interp->type_watchers[TYPE_WATCHER_ID] =type_watcher_callback;
return0;
}
staticvoid
watch_type(PyTypeObject*type, _PyBloomFilter*filter)
{
if (_Py_IsImmortal(type) && (type->tp_flags&Py_TPFLAGS_IMMUTABLETYPE)) {
return;
}
PyType_Watch(TYPE_WATCHER_ID, (PyObject*)type);
_Py_BloomFilter_Add(filter, type);
}
staticPyObject*
convert_global_to_const(_PyUOpInstruction*inst, PyObject*obj)
{
assert(inst->opcode==_LOAD_GLOBAL_MODULE||inst->opcode==_LOAD_GLOBAL_BUILTINS||inst->opcode==_LOAD_ATTR_MODULE);
assert(PyDict_CheckExact(obj));
PyDictObject*dict= (PyDictObject*)obj;
assert(dict->ma_keys->dk_kind==DICT_KEYS_UNICODE);
PyDictUnicodeEntry*entries=DK_UNICODE_ENTRIES(dict->ma_keys);
int64_tindex=inst->operand1;
assert(index <= UINT16_MAX);
if ((int)index >= dict->ma_keys->dk_nentries) {
returnNULL;
}
PyDictKeysObject*keys=dict->ma_keys;
if (keys->dk_version!=inst->operand0) {
returnNULL;
}
PyObject*res=entries[index].me_value;
if (res==NULL) {
returnNULL;
}
if (_Py_IsImmortal(res)) {
inst->opcode=_LOAD_CONST_INLINE_BORROW;
} else {
inst->opcode=_LOAD_CONST_INLINE;
}
inst->operand0= (uint64_t)res;
returnres;
}
staticbool
incorrect_keys(PyObject*obj, uint32_tversion)
{
if (!PyDict_CheckExact(obj)) {
return true;
}
PyDictObject*dict= (PyDictObject*)obj;
returndict->ma_keys->dk_version!=version;
}
#defineSTACK_LEVEL() ((int)(stack_pointer - ctx->frame->stack))
#defineSTACK_SIZE() ((int)(ctx->frame->stack_len))
staticinlineint
is_terminator_uop(const_PyUOpInstruction*uop)
{
intopcode=uop->opcode;
return (
opcode==_EXIT_TRACE||
opcode==_JUMP_TO_TOP||
opcode==_DYNAMIC_EXIT||
opcode==_DEOPT
);
}
#defineCURRENT_FRAME_IS_INIT_SHIM() (ctx->frame->code == ((PyCodeObject *)&_Py_InitCleanup))
#defineGETLOCAL(idx) ((ctx->frame->locals[idx]))
#defineREPLACE_OP(INST, OP, ARG, OPERAND) \
(INST)->opcode = OP; \
(INST)->oparg = ARG; \
(INST)->operand0 = OPERAND;
#defineADD_OP(OP, ARG, OPERAND) add_op(ctx, this_instr, (OP), (ARG), (OPERAND))
staticinlinevoid
add_op(JitOptContext*ctx, _PyUOpInstruction*this_instr,
uint16_topcode, uint16_toparg, uintptr_toperand0)
{
_PyUOpInstruction*out=ctx->out_buffer.next;
assert(out<ctx->out_buffer.end);
out->opcode= (opcode);
out->format=this_instr->format;
out->oparg= (oparg);
out->target=this_instr->target;
out->operand0= (operand0);
out->operand1=this_instr->operand1;
#ifdefPy_STATS
out->fitness=this_instr->fitness;
#endif
ctx->out_buffer.next++;
}
/* Shortened forms for convenience, used in optimizer_bytecodes.c */
#definesym_is_not_null _Py_uop_sym_is_not_null
#definesym_is_const _Py_uop_sym_is_const
#definesym_is_safe_const _Py_uop_sym_is_safe_const
#definesym_is_not_container _Py_uop_sym_is_not_container
#definesym_get_const _Py_uop_sym_get_const
#definesym_new_const_steal _Py_uop_sym_new_const_steal
#definesym_get_const_as_stackref _Py_uop_sym_get_const_as_stackref
#definesym_new_unknown _Py_uop_sym_new_unknown
#definesym_new_not_null _Py_uop_sym_new_not_null
#definesym_new_type _Py_uop_sym_new_type
#definesym_is_null _Py_uop_sym_is_null
#definesym_new_const _Py_uop_sym_new_const
#definesym_new_null _Py_uop_sym_new_null
#definesym_has_type _Py_uop_sym_has_type
#definesym_get_type _Py_uop_sym_get_type
#definesym_get_probable_type _Py_uop_sym_get_probable_type
#definesym_matches_type _Py_uop_sym_matches_type
#definesym_matches_type_version _Py_uop_sym_matches_type_version
#definesym_get_type_version _Py_uop_sym_get_type_version
#definesym_set_null(SYM) _Py_uop_sym_set_null(ctx, SYM)
#definesym_set_non_null(SYM) _Py_uop_sym_set_non_null(ctx, SYM)
#definesym_set_type(SYM, TYPE) _Py_uop_sym_set_type(ctx, SYM, TYPE)
#definesym_set_type_version(SYM, VERSION) _Py_uop_sym_set_type_version(ctx, SYM, VERSION)
#definesym_set_const(SYM, CNST) _Py_uop_sym_set_const(ctx, SYM, CNST)
#definesym_set_compact_int(SYM) _Py_uop_sym_set_compact_int(ctx, SYM)
#definesym_is_bottom _Py_uop_sym_is_bottom
#definesym_truthiness _Py_uop_sym_truthiness
#defineframe_new _Py_uop_frame_new
#defineframe_new_from_symbol _Py_uop_frame_new_from_symbol
#defineframe_pop _Py_uop_frame_pop
#definesym_new_tuple _Py_uop_sym_new_tuple
#definesym_tuple_getitem _Py_uop_sym_tuple_getitem
#definesym_tuple_length _Py_uop_sym_tuple_length
#definesym_is_immortal _Py_uop_symbol_is_immortal
#definesym_is_compact_int _Py_uop_sym_is_compact_int
#definesym_new_compact_int _Py_uop_sym_new_compact_int
#definesym_new_truthiness _Py_uop_sym_new_truthiness
#definesym_new_predicate _Py_uop_sym_new_predicate
#definesym_apply_predicate_narrowing _Py_uop_sym_apply_predicate_narrowing
#definesym_set_recorded_type(SYM, TYPE) _Py_uop_sym_set_recorded_type(ctx, SYM, TYPE)
#definesym_set_recorded_value(SYM, VAL) _Py_uop_sym_set_recorded_value(ctx, SYM, VAL)
#definesym_set_recorded_gen_func(SYM, VAL) _Py_uop_sym_set_recorded_gen_func(ctx, SYM, VAL)
#definesym_get_probable_func_code _Py_uop_sym_get_probable_func_code
#definesym_get_probable_value _Py_uop_sym_get_probable_value
#definesym_set_stack_depth(DEPTH, SP) _Py_uop_sym_set_stack_depth(ctx, DEPTH, SP)
/* Comparison oparg masks */
#defineCOMPARE_LT_MASK 2
#defineCOMPARE_GT_MASK 4
#defineCOMPARE_EQ_MASK 8
#defineJUMP_TO_LABEL(label) goto label;
staticint
check_stack_bounds(JitOptContext*ctx, JitOptRef*stack_pointer, intoffset, intopcode)
{
intstack_level= (int)(stack_pointer+ (offset) -ctx->frame->stack);
intshould_check= !CURRENT_FRAME_IS_INIT_SHIM() ||
(opcode==_RETURN_VALUE) ||
(opcode==_RETURN_GENERATOR) ||
(opcode==_YIELD_VALUE);
if (should_check&& (stack_level<0||stack_level>STACK_SIZE() +MAX_CACHED_REGISTER)) {
ctx->contradiction= true;
ctx->done= true;
return1;
}
return0;
}
#defineCHECK_STACK_BOUNDS(offset) \
if (check_stack_bounds(ctx, stack_pointer, offset, opcode)) { \
break; \
} \
staticint
optimize_to_bool(
_PyUOpInstruction*this_instr,
JitOptContext*ctx,
JitOptRefvalue,
JitOptRef*result_ptr,
uint16_tprefix, uint16_tsuffix)
{
if (sym_matches_type(value, &PyBool_Type)) {
ADD_OP(_NOP, 0, 0);
*result_ptr=value;
return1;
}
inttruthiness=sym_truthiness(ctx, value);
if (truthiness >= 0) {
PyObject*load=truthiness ? Py_True : Py_False;
if (prefix!=_NOP) {
ADD_OP(prefix, 0, 0);
}
ADD_OP(_LOAD_CONST_INLINE_BORROW, 0, (uintptr_t)load);
if (suffix!=_NOP) {
ADD_OP(suffix, 2, 0);
}
*result_ptr=sym_new_const(ctx, load);
return1;
}
return0;
}
staticvoid
optimize_dict_known_hash(
JitOptContext*ctx, _PyBloomFilter*dependencies, _PyUOpInstruction*this_instr,
PyObject*sub, uint16_topcode)
{
if (PyUnicode_CheckExact(sub) ||PyLong_CheckExact(sub) ||PyBytes_CheckExact(sub)
||PyFloat_CheckExact(sub) ||PyComplex_CheckExact(sub)) {
// PyObject_Hash can't fail on these types
ADD_OP(opcode, 0, PyObject_Hash(sub));
}
elseif (PyTuple_CheckExact(sub)) {
// only use known hash variant when hash of tuple is already computed
// since computing it can call arbitrary code
Py_hash_thash= ((PyTupleObject*)sub)->ob_hash;
if (hash!=-1) {
ADD_OP(opcode, 0, hash);
}
}
elseif (Py_TYPE(sub)->tp_hash==PyBaseObject_Type.tp_hash) {
// for user-defined objects which don't override tp_hash
Py_hash_thash=PyObject_Hash(sub);
ADD_OP(opcode, 0, hash);
watch_type(Py_TYPE(sub), dependencies);
}
}
staticvoid
eliminate_pop_guard(_PyUOpInstruction*this_instr, JitOptContext*ctx, boolexit)
{
ADD_OP(_POP_TOP, 0, 0);
if (exit) {
REPLACE_OP((this_instr+1), _EXIT_TRACE, 0, 0);
this_instr[1].target=this_instr->target;
}
}
staticJitOptRef
lookup_attr(JitOptContext*ctx, _PyBloomFilter*dependencies, _PyUOpInstruction*this_instr,
PyTypeObject*type, PyObject*name,
uint16_tprefix, uint16_tsuffix)
{
// The cached value may be dead, so we need to do the lookup again... :(
if (type&&PyType_Check(type)) {
PyObject*lookup=_PyType_Lookup(type, name);
if (lookup) {
boolimmortal=_Py_IsImmortal(lookup) || (type->tp_flags&Py_TPFLAGS_IMMUTABLETYPE);
if (prefix!=_NOP) {
ADD_OP(prefix, 0, 0);
}
ADD_OP(immortal ? _LOAD_CONST_INLINE_BORROW : _LOAD_CONST_INLINE,
0, (uintptr_t)lookup);
if (suffix!=_NOP) {
ADD_OP(suffix, 2, 0);
}
if ((type->tp_flags&Py_TPFLAGS_IMMUTABLETYPE) ==0) {
watch_type(type, dependencies);
}
returnsym_new_const(ctx, lookup);
}
}
returnsym_new_not_null(ctx);
}
staticvoid
optimize_pop_top(JitOptContext*ctx, _PyUOpInstruction*this_instr, JitOptRefvalue)
{
PyTypeObject*typ=sym_get_type(value);
if (PyJitRef_IsBorrowed(value) ||
sym_is_immortal(PyJitRef_Unwrap(value)) ||
sym_is_null(value)) {
ADD_OP(_POP_TOP_NOP, 0, 0);
}
elseif (typ==&PyLong_Type) {
ADD_OP(_POP_TOP_INT, 0, 0);
}
elseif (typ==&PyFloat_Type) {
ADD_OP(_POP_TOP_FLOAT, 0, 0);
}
elseif (typ==&PyUnicode_Type) {
ADD_OP(_POP_TOP_UNICODE, 0, 0);
}
else {
ADD_OP(_POP_TOP, 0, 0);
}
}
/* Look up name via super (normal case from supercheck where
su_obj_type = Py_TYPE(obj)). */
staticJitOptRef
lookup_super_attr(JitOptContext*ctx, _PyBloomFilter*dependencies,
_PyUOpInstruction*this_instr,
PyTypeObject*su_type, PyTypeObject*obj_type,
PyObject*name,
uint16_timmortal, uint16_tmortal, uint16_tsuffix)
{
if (su_type==NULL||obj_type==NULL) {
returnsym_new_not_null(ctx);
}
/* Normal case: obj_type must be a subtype of su_type */
if (!PyType_IsSubtype(obj_type, su_type)) {
returnsym_new_not_null(ctx);
}
PyObject*lookup=_PySuper_LookupDescr(su_type, obj_type, name);
if (lookup==NULL) {
if (PyErr_Occurred()) {
PyErr_Clear();
}
returnsym_new_not_null(ctx);
}
if ((Py_TYPE(lookup)->tp_flags&Py_TPFLAGS_METHOD_DESCRIPTOR) ==0) {
Py_DECREF(lookup);
returnsym_new_not_null(ctx);
}
intopcode=mortal;
if (_Py_IsImmortal(lookup) || (obj_type->tp_flags&Py_TPFLAGS_IMMUTABLETYPE)) {
opcode=immortal;
}
ADD_OP(_SWAP, 3, 0);
ADD_OP(_POP_TOP, 0, 0);
ADD_OP(_POP_TOP, 0, 0);
ADD_OP(opcode, 0, (uintptr_t)lookup);
if (suffix!=_NOP) {
ADD_OP(suffix, 2, 0);
}
// if obj_type is immutable, then all its superclasses are immutable
if ((obj_type->tp_flags&Py_TPFLAGS_IMMUTABLETYPE) ==0) {
watch_type(su_type, dependencies);
watch_type(obj_type, dependencies);
}
returnsym_new_const_steal(ctx, lookup);
}
static
PyCodeObject*
get_current_code_object(JitOptContext*ctx)
{
return (PyCodeObject*)ctx->frame->code;
}
staticPyObject*
get_co_name(JitOptContext*ctx, intindex)
{
returnPyTuple_GET_ITEM(get_current_code_object(ctx)->co_names, index);
}
staticint
get_test_bit_for_bools(void) {
#ifdefPy_STACKREF_DEBUG
uintptr_tfalse_bits=_Py_STACKREF_FALSE_INDEX;
uintptr_ttrue_bits=_Py_STACKREF_TRUE_INDEX;
#else
uintptr_tfalse_bits= (uintptr_t)&_Py_FalseStruct;
uintptr_ttrue_bits= (uintptr_t)&_Py_TrueStruct;
#endif
for (inti=4; i<8; i++) {
if ((true_bits ^ false_bits) & (uintptr_t)(1 << i)) {
returni;
}
}
return0;
}
staticint
test_bit_set_in_true(intbit) {
#ifdefPy_STACKREF_DEBUG
uintptr_ttrue_bits=_Py_STACKREF_TRUE_INDEX;
#else
uintptr_ttrue_bits= (uintptr_t)&_Py_TrueStruct;
#endif
assert((true_bits ^ ((uintptr_t)&_Py_FalseStruct)) & (uintptr_t)(1 << bit));
returntrue_bits& (uintptr_t)(1 << bit);
}
#ifdefPy_DEBUG
void
_Py_opt_assert_within_stack_bounds(
_Py_UOpsAbstractFrame*frame, JitOptRef*stack_pointer,
constchar*filename, intlineno
) {
if (frame->code== ((PyCodeObject*)&_Py_InitCleanup)) {
return;
}
intlevel= (int)(stack_pointer-frame->stack);
if (level<0) {
printf("Stack underflow (depth = %d) at %s:%d\n", level, filename, lineno);
fflush(stdout);
abort();
}
intsize= (int)(frame->stack_len) +MAX_CACHED_REGISTER;
if (level>size) {
printf("Stack overflow (depth = %d) at %s:%d\n", level, filename, lineno);
fflush(stdout);
abort();
}
}
#endif
#ifdefPy_DEBUG
#defineASSERT_WITHIN_STACK_BOUNDS(F, L) _Py_opt_assert_within_stack_bounds(ctx->frame, stack_pointer, (F), (L))
#else
#defineASSERT_WITHIN_STACK_BOUNDS(F, L) (void)0
#endif
/* >0 (length) for success, 0 for not ready, clears all possible errors. */
staticint
optimize_uops(
_PyThreadStateImpl*tstate,
_PyUOpInstruction*trace,
inttrace_len,
intcurr_stacklen,
_PyUOpInstruction*output,
_PyBloomFilter*dependencies
)
{
assert(!PyErr_Occurred());
assert(tstate->jit_tracer_state!=NULL);
PyFunctionObject*func=tstate->jit_tracer_state->initial_state.func;
JitOptContext*ctx=&tstate->jit_tracer_state->opt_context;
uint32_topcode=UINT16_MAX;
uop_buffer_init(&ctx->out_buffer, output, UOP_MAX_TRACE_LENGTH);
// Make sure that watchers are set up
PyInterpreterState*interp=_PyInterpreterState_GET();
_PyOnceFlag_CallOnce(&interp->dict_state.watcher_setup_once,
_setup_optimizer_watchers, NULL);
_Py_uop_abstractcontext_init(ctx, dependencies);
_Py_UOpsAbstractFrame*frame=_Py_uop_frame_new(ctx, (PyCodeObject*)func->func_code, NULL, 0);
if (frame==NULL) {
return0;
}
frame->func=func;
ctx->curr_frame_depth++;
ctx->frame=frame;
_Py_uop_sym_set_stack_depth(ctx, curr_stacklen, frame->stack_pointer);
_PyUOpInstruction*this_instr=NULL;
JitOptRef*stack_pointer=ctx->frame->stack_pointer;
for (inti=0; i<trace_len; i++) {
this_instr=&trace[i];
if (ctx->done) {
// Don't do any more optimization, but
// we still need to reach a terminator for corrctness.
*(ctx->out_buffer.next++) =*this_instr;
if (is_terminator_uop(this_instr)) {
break;
}
continue;
}
intoparg=this_instr->oparg;
opcode=this_instr->opcode;
if (!CURRENT_FRAME_IS_INIT_SHIM()) {
stack_pointer=ctx->frame->stack_pointer;
}
DUMP_UOP(ctx, "abs", (int)(this_instr-trace), this_instr, stack_pointer);
_PyUOpInstruction*out_ptr=ctx->out_buffer.next;
switch (opcode) {
#include"optimizer_cases.c.h"
default:
DPRINTF(1, "\nUnknown opcode in abstract interpreter\n");
Py_UNREACHABLE();
}
// If no ADD_OP was called during this iteration, copy the original instruction
if (ctx->out_buffer.next==out_ptr) {
*(ctx->out_buffer.next++) =*this_instr;
}
assert(ctx->frame!=NULL);
DUMP_UOPS(ctx, "out", out_ptr, stack_pointer);
if (!CURRENT_FRAME_IS_INIT_SHIM() && !ctx->done) {
DPRINTF(3, " stack_level %d\n", STACK_LEVEL());
ctx->frame->stack_pointer=stack_pointer;
assert(STACK_LEVEL() >= 0);
}
}
if (ctx->out_of_space) {
DPRINTF(3, "\n");
DPRINTF(1, "Out of space in abstract interpreter\n");
}
if (ctx->contradiction) {
// Attempted to push a "bottom" (contradiction) symbol onto the stack.
// This means that the abstract interpreter has optimized to trace
// to an unreachable estate.
// We *could* generate an _EXIT_TRACE or _FATAL_ERROR here, but hitting
// bottom usually indicates an optimizer bug, so we are probably better off
// retrying later.
DPRINTF(3, "\n");
DPRINTF(1, "Hit bottom in abstract interpreter\n");
_Py_uop_abstractcontext_fini(ctx);
OPT_STAT_INC(optimizer_contradiction);
return0;
}
/* Either reached the end or cannot optimize further, but there
* would be no benefit in retrying later */
_Py_uop_abstractcontext_fini(ctx);
// Check that the trace ends with a proper terminator
if (uop_buffer_length(&ctx->out_buffer) >0) {
assert(is_terminator_uop(uop_buffer_last(&ctx->out_buffer)));
}
returnuop_buffer_length(&ctx->out_buffer);
error:
DPRINTF(3, "\n");
DPRINTF(1, "Encountered error in abstract interpreter\n");
if (opcode <= MAX_UOP_ID) {
OPT_ERROR_IN_OPCODE(opcode);
}
_Py_uop_abstractcontext_fini(ctx);
assert(PyErr_Occurred());
PyErr_Clear();
return0;
}
constuint16_top_without_push[MAX_UOP_ID+1] = {
[_COPY] =_NOP,
[_LOAD_CONST_INLINE] =_NOP,
[_LOAD_CONST_INLINE_BORROW] =_NOP,
[_LOAD_FAST] =_NOP,
[_LOAD_FAST_BORROW] =_NOP,
[_LOAD_SMALL_INT] =_NOP,
[_PUSH_NULL] =_NOP,
};
constboolop_skip[MAX_UOP_ID+1] = {
[_NOP] = true,
[_CHECK_VALIDITY] = true,
[_CHECK_PERIODIC] = true,
[_SET_IP] = true,
};
constuint16_top_without_pop[MAX_UOP_ID+1] = {
[_POP_TOP] =_NOP,
[_POP_TOP_NOP] =_NOP,
[_POP_TOP_INT] =_NOP,
[_POP_TOP_FLOAT] =_NOP,
[_POP_TOP_UNICODE] =_NOP,
};
staticint
remove_unneeded_uops(_PyUOpInstruction*buffer, intbuffer_size)
{
/* Remove _SET_IP and _CHECK_VALIDITY where possible.
* _SET_IP is needed if the following instruction escapes or
* could error. _CHECK_VALIDITY is needed if the previous
* instruction could have escaped. */
intlast_set_ip=-1;
boolmay_have_escaped= true;
for (intpc=0; pc<buffer_size; pc++) {
intopcode=buffer[pc].opcode;
switch (opcode) {
case_START_EXECUTOR:
may_have_escaped= false;
break;
case_SET_IP:
buffer[pc].opcode=_NOP;
last_set_ip=pc;
break;
case_CHECK_VALIDITY:
if (may_have_escaped) {
may_have_escaped= false;
}
else {
buffer[pc].opcode=_NOP;
}
break;
case_EXIT_TRACE:
default:
{
// Cancel out pushes and pops, repeatedly. So:
// _LOAD_FAST + _POP_TOP + _POP_TOP + _LOAD_CONST_INLINE_BORROW + _POP_TOP
// ...becomes:
// _NOP + _NOP + _POP_TOP + _NOP + _NOP
while (op_without_pop[opcode]) {
_PyUOpInstruction*last=&buffer[pc-1];
while (op_skip[last->opcode]) {
last--;
}
if (op_without_push[last->opcode] &&op_without_pop[opcode]) {
last->opcode=op_without_push[last->opcode];
opcode=buffer[pc].opcode=op_without_pop[opcode];
if (op_without_pop[last->opcode]) {
opcode=last->opcode;
pc= (int)(last-buffer);
}
}
else {
break;
}
}
/* _PUSH_FRAME doesn't escape or error, but it
* does need the IP for the return address */
boolneeds_ip= (opcode==_PUSH_FRAME||opcode==_YIELD_VALUE||opcode==_DYNAMIC_EXIT||opcode==_EXIT_TRACE);
if (_PyUop_Flags[opcode] &HAS_ESCAPES_FLAG) {
needs_ip= true;
may_have_escaped= true;
}
if (needs_ip&&last_set_ip >= 0) {
assert(buffer[last_set_ip].opcode==_NOP);
buffer[last_set_ip].opcode=_SET_IP;
last_set_ip=-1;
}
if (opcode==_EXIT_TRACE) {
returnpc+1;
}
break;
}
case_JUMP_TO_TOP:
case_DYNAMIC_EXIT:
case_DEOPT:
returnpc+1;
}
}
Py_UNREACHABLE();
}
// 0 - failure, no error raised, just fall back to Tier 1
// -1 - failure, and raise error
// > 0 - length of optimized trace
int
_Py_uop_analyze_and_optimize(
_PyThreadStateImpl*tstate,
_PyUOpInstruction*buffer,
intlength,
intcurr_stacklen,
_PyUOpInstruction*output,
_PyBloomFilter*dependencies
)
{
OPT_STAT_INC(optimizer_attempts);
length=optimize_uops(
tstate, buffer, length, curr_stacklen, output, dependencies);
if (length==0) {
returnlength;
}
assert(length>0);
length=remove_unneeded_uops(output, length);
assert(length>0);
OPT_STAT_INC(optimizer_successes);
returnlength;
}
#endif/* _Py_TIER2 */