Coverage Report

Created: 2026-07-14 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/optimizer.c
Line
Count
Source
1
#include "Python.h"
2
3
#ifdef _Py_TIER2
4
5
#include "opcode.h"
6
#include "pycore_interp.h"
7
#include "pycore_backoff.h"
8
#include "pycore_bitutils.h"        // _Py_popcount32()
9
#include "pycore_ceval.h"       // _Py_set_eval_breaker_bit
10
#include "pycore_code.h"            // _Py_GetBaseCodeUnit
11
#include "pycore_interpframe.h"
12
#include "pycore_object.h"          // _PyObject_GC_UNTRACK()
13
#include "pycore_opcode_metadata.h" // _PyOpcode_OpName[]
14
#include "pycore_opcode_utils.h"  // MAX_REAL_OPCODE
15
#include "pycore_optimizer.h"     // _Py_uop_analyze_and_optimize()
16
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
17
#include "pycore_tuple.h"         // _PyTuple_FromArraySteal
18
#include "pycore_unicodeobject.h" // _PyUnicode_FromASCII
19
#include "pycore_uop_ids.h"
20
#include "pycore_jit.h"
21
#include <stdbool.h>
22
#include <stdint.h>
23
#include <stddef.h>
24
25
#define NEED_OPCODE_METADATA
26
#include "pycore_uop_metadata.h" // Uop tables
27
#undef NEED_OPCODE_METADATA
28
29
#define MAX_EXECUTORS_SIZE 256
30
31
// Trace too short, no progress:
32
// _START_EXECUTOR
33
// _MAKE_WARM
34
// _CHECK_VALIDITY
35
// _SET_IP
36
// is 4-5 instructions.
37
#define CODE_SIZE_NO_PROGRESS 5
38
// We start with _START_EXECUTOR, _MAKE_WARM
39
#define CODE_SIZE_EMPTY 2
40
41
#define _PyExecutorObject_CAST(op)  ((_PyExecutorObject *)(op))
42
43
#ifndef Py_GIL_DISABLED
44
static bool
45
has_space_for_executor(PyCodeObject *code, _Py_CODEUNIT *instr)
46
{
47
    if (code == (PyCodeObject *)&_Py_InitCleanup) {
48
        return false;
49
    }
50
    if (instr->op.code == ENTER_EXECUTOR) {
51
        return true;
52
    }
53
    if (code->co_executors == NULL) {
54
        return true;
55
    }
56
    return code->co_executors->size < MAX_EXECUTORS_SIZE;
57
}
58
59
static int32_t
60
get_index_for_executor(PyCodeObject *code, _Py_CODEUNIT *instr)
61
{
62
    if (instr->op.code == ENTER_EXECUTOR) {
63
        return instr->op.arg;
64
    }
65
    _PyExecutorArray *old = code->co_executors;
66
    int size = 0;
67
    int capacity = 0;
68
    if (old != NULL) {
69
        size = old->size;
70
        capacity = old->capacity;
71
        assert(size < MAX_EXECUTORS_SIZE);
72
    }
73
    assert(size <= capacity);
74
    if (size == capacity) {
75
        /* Array is full. Grow array */
76
        int new_capacity = capacity ? capacity * 2 : 4;
77
        _PyExecutorArray *new = PyMem_Realloc(
78
            old,
79
            offsetof(_PyExecutorArray, executors) +
80
            new_capacity * sizeof(_PyExecutorObject *));
81
        if (new == NULL) {
82
            return -1;
83
        }
84
        new->capacity = new_capacity;
85
        new->size = size;
86
        code->co_executors = new;
87
    }
88
    assert(size < code->co_executors->capacity);
89
    return size;
90
}
91
92
static void
93
insert_executor(PyCodeObject *code, _Py_CODEUNIT *instr, int index, _PyExecutorObject *executor)
94
{
95
    Py_INCREF(executor);
96
    if (instr->op.code == ENTER_EXECUTOR) {
97
        assert(index == instr->op.arg);
98
        _Py_ExecutorDetach(code->co_executors->executors[index]);
99
    }
100
    else {
101
        assert(code->co_executors->size == index);
102
        assert(code->co_executors->capacity > index);
103
        code->co_executors->size++;
104
    }
105
    executor->vm_data.opcode = instr->op.code;
106
    executor->vm_data.oparg = instr->op.arg;
107
    executor->vm_data.code = code;
108
    executor->vm_data.index = (int)(instr - _PyCode_CODE(code));
109
    code->co_executors->executors[index] = executor;
110
    assert(index < MAX_EXECUTORS_SIZE);
111
    instr->op.code = ENTER_EXECUTOR;
112
    instr->op.arg = index;
113
}
114
#endif // Py_GIL_DISABLED
115
116
static _PyExecutorObject *
117
make_executor_from_uops(_PyThreadStateImpl *tstate, _PyUOpInstruction *buffer, int length, const _PyBloomFilter *dependencies);
118
119
static int
120
uop_optimize(_PyInterpreterFrame *frame, PyThreadState *tstate,
121
             _PyExecutorObject **exec_ptr,
122
             bool progress_needed);
123
124
/* Returns 1 if optimized, 0 if not optimized, and -1 for an error.
125
 * If optimized, *executor_ptr contains a new reference to the executor
126
 */
127
// gh-137573: inlining this function causes stack overflows
128
Py_NO_INLINE int
129
_PyOptimizer_Optimize(
130
    _PyInterpreterFrame *frame, PyThreadState *tstate)
131
{
132
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
133
    PyInterpreterState *interp = _PyInterpreterState_GET();
134
    if (!interp->jit) {
135
        // gh-140936: It is possible that interp->jit will become false during
136
        // interpreter finalization. However, the specialized JUMP_BACKWARD_JIT
137
        // instruction may still be present. In this case, we should
138
        // return immediately without optimization.
139
        return 0;
140
    }
141
    _PyExecutorObject *prev_executor = _tstate->jit_tracer_state->initial_state.executor;
142
    if (prev_executor != NULL && !prev_executor->vm_data.valid) {
143
        // gh-143604: If we are a side exit executor and the original executor is no
144
        // longer valid, don't compile to prevent a reference leak.
145
        return 0;
146
    }
147
    assert(!interp->compiling);
148
    assert(_tstate->jit_tracer_state->initial_state.stack_depth >= 0);
149
#ifndef Py_GIL_DISABLED
150
    assert(_tstate->jit_tracer_state->initial_state.func != NULL);
151
    interp->compiling = true;
152
    // The first executor in a chain and the MAX_CHAIN_DEPTH'th executor *must*
153
    // make progress in order to avoid infinite loops or excessively-long
154
    // side-exit chains. We can only insert the executor into the bytecode if
155
    // this is true, since a deopt won't infinitely re-enter the executor:
156
    int chain_depth = _tstate->jit_tracer_state->initial_state.chain_depth;
157
    chain_depth %= MAX_CHAIN_DEPTH;
158
    bool progress_needed = chain_depth == 0;
159
    PyCodeObject *code = (PyCodeObject *)_tstate->jit_tracer_state->initial_state.code;
160
    _Py_CODEUNIT *start = _tstate->jit_tracer_state->initial_state.start_instr;
161
    if (progress_needed && !has_space_for_executor(code, start)) {
162
        interp->compiling = false;
163
        return 0;
164
    }
165
    _PyExecutorObject *executor;
166
    int err = uop_optimize(frame, tstate, &executor, progress_needed);
167
    if (err <= 0) {
168
        interp->compiling = false;
169
        return err;
170
    }
171
    assert(executor != NULL);
172
    if (progress_needed) {
173
        int index = get_index_for_executor(code, start);
174
        if (index < 0) {
175
            /* Out of memory. Don't raise and assume that the
176
             * error will show up elsewhere.
177
             *
178
             * If an optimizer has already produced an executor,
179
             * it might get confused by the executor disappearing,
180
             * but there is not much we can do about that here. */
181
            Py_DECREF(executor);
182
            interp->compiling = false;
183
            return 0;
184
        }
185
        insert_executor(code, start, index, executor);
186
    }
187
    executor->vm_data.chain_depth = chain_depth;
188
    assert(executor->vm_data.valid);
189
    _PyExitData *exit = _tstate->jit_tracer_state->initial_state.exit;
190
    if (exit != NULL && !progress_needed) {
191
        exit->executor = executor;
192
    }
193
    else {
194
        // An executor inserted into the code object now has a strong reference
195
        // to it from the code object. Thus, we don't need this reference anymore.
196
        Py_DECREF(executor);
197
    }
198
    interp->compiling = false;
199
    return 1;
200
#else
201
    return 0;
202
#endif
203
}
204
205
static _PyExecutorObject *
206
get_executor_lock_held(PyCodeObject *code, int offset)
207
{
208
    int code_len = (int)Py_SIZE(code);
209
    for (int i = 0 ; i < code_len;) {
210
        if (_PyCode_CODE(code)[i].op.code == ENTER_EXECUTOR && i*2 == offset) {
211
            int oparg = _PyCode_CODE(code)[i].op.arg;
212
            _PyExecutorObject *res = code->co_executors->executors[oparg];
213
            Py_INCREF(res);
214
            return res;
215
        }
216
        i += _PyInstruction_GetLength(code, i);
217
    }
218
    PyErr_SetString(PyExc_ValueError, "no executor at given byte offset");
219
    return NULL;
220
}
221
222
_PyExecutorObject *
223
_Py_GetExecutor(PyCodeObject *code, int offset)
224
{
225
    _PyExecutorObject *executor;
226
    Py_BEGIN_CRITICAL_SECTION(code);
227
    executor = get_executor_lock_held(code, offset);
228
    Py_END_CRITICAL_SECTION();
229
    return executor;
230
}
231
232
static PyObject *
233
is_valid(PyObject *self, PyObject *Py_UNUSED(ignored))
234
{
235
    return PyBool_FromLong(((_PyExecutorObject *)self)->vm_data.valid);
236
}
237
238
static PyObject *
239
get_opcode(PyObject *self, PyObject *Py_UNUSED(ignored))
240
{
241
    return PyLong_FromUnsignedLong(((_PyExecutorObject *)self)->vm_data.opcode);
242
}
243
244
static PyObject *
245
get_oparg(PyObject *self, PyObject *Py_UNUSED(ignored))
246
{
247
    return PyLong_FromUnsignedLong(((_PyExecutorObject *)self)->vm_data.oparg);
248
}
249
250
///////////////////// Experimental UOp Optimizer /////////////////////
251
252
static int executor_clear(PyObject *executor);
253
254
void
255
_PyExecutor_Free(_PyExecutorObject *self)
256
{
257
#ifdef _Py_JIT
258
    _PyJIT_Free(self);
259
#endif
260
    PyObject_GC_Del(self);
261
}
262
263
static void executor_invalidate(PyObject *op);
264
265
static void
266
executor_clear_exits(_PyExecutorObject *executor)
267
{
268
    _PyExecutorObject *cold = _PyExecutor_GetColdExecutor();
269
    _PyExecutorObject *cold_dynamic = _PyExecutor_GetColdDynamicExecutor();
270
    for (uint32_t i = 0; i < executor->exit_count; i++) {
271
        _PyExitData *exit = &executor->exits[i];
272
        exit->temperature = initial_unreachable_backoff_counter();
273
        _PyExecutorObject *old = executor->exits[i].executor;
274
        exit->executor = exit->is_dynamic ? cold_dynamic : cold;
275
        Py_DECREF(old);
276
    }
277
}
278
279
280
void
281
_Py_ClearExecutorDeletionList(PyInterpreterState *interp)
282
{
283
    if (interp->executor_deletion_list_head == NULL) {
284
        return;
285
    }
286
    _PyRuntimeState *runtime = &_PyRuntime;
287
    HEAD_LOCK(runtime);
288
    PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
289
    while (ts) {
290
        _PyExecutorObject *current = (_PyExecutorObject *)ts->current_executor;
291
        Py_XINCREF(current);
292
        ts = ts->next;
293
    }
294
    HEAD_UNLOCK(runtime);
295
    _PyExecutorObject *keep_list = NULL;
296
    do {
297
        _PyExecutorObject *exec = interp->executor_deletion_list_head;
298
        interp->executor_deletion_list_head = exec->vm_data.links.next;
299
        if (Py_REFCNT(exec) == 0) {
300
            _PyExecutor_Free(exec);
301
        } else {
302
            exec->vm_data.links.next = keep_list;
303
            keep_list = exec;
304
        }
305
    } while (interp->executor_deletion_list_head != NULL);
306
    interp->executor_deletion_list_head = keep_list;
307
    HEAD_LOCK(runtime);
308
    ts = PyInterpreterState_ThreadHead(interp);
309
    while (ts) {
310
        _PyExecutorObject *current = (_PyExecutorObject *)ts->current_executor;
311
        if (current != NULL) {
312
            Py_DECREF((PyObject *)current);
313
        }
314
        ts = ts->next;
315
    }
316
    HEAD_UNLOCK(runtime);
317
}
318
319
static void
320
add_to_pending_deletion_list(_PyExecutorObject *self)
321
{
322
    if (self->vm_data.pending_deletion) {
323
        return;
324
    }
325
    self->vm_data.pending_deletion = 1;
326
    PyInterpreterState *interp = PyInterpreterState_Get();
327
    self->vm_data.links.previous = NULL;
328
    self->vm_data.links.next = interp->executor_deletion_list_head;
329
    interp->executor_deletion_list_head = self;
330
}
331
332
static void
333
uop_dealloc(PyObject *op) {
334
    _PyExecutorObject *self = _PyExecutorObject_CAST(op);
335
    executor_invalidate(op);
336
    assert(self->vm_data.code == NULL);
337
    add_to_pending_deletion_list(self);
338
}
339
340
const char *
341
_PyUOpName(int index)
342
{
343
    if (index < 0 || index > MAX_UOP_REGS_ID) {
344
        return NULL;
345
    }
346
    return _PyOpcode_uop_name[index];
347
}
348
349
#ifdef Py_DEBUG
350
void
351
_PyUOpPrint(const _PyUOpInstruction *uop)
352
{
353
    const char *name = _PyUOpName(uop->opcode);
354
    if (name == NULL) {
355
        printf("<uop %d>", uop->opcode);
356
    }
357
    else {
358
        printf("%s", name);
359
    }
360
    switch(uop->format) {
361
        case UOP_FORMAT_TARGET:
362
            printf(" (%d, target=%d, operand0=%#" PRIx64 ", operand1=%#" PRIx64,
363
                uop->oparg,
364
                uop->target,
365
                (uint64_t)uop->operand0,
366
                (uint64_t)uop->operand1);
367
            break;
368
        case UOP_FORMAT_JUMP:
369
            printf(" (%d, jump_target=%d, operand0=%#" PRIx64 ", operand1=%#" PRIx64,
370
                uop->oparg,
371
                uop->jump_target,
372
                (uint64_t)uop->operand0,
373
                (uint64_t)uop->operand1);
374
            break;
375
        default:
376
            printf(" (%d, Unknown format)", uop->oparg);
377
    }
378
    if (_PyUop_Flags[_PyUop_Uncached[uop->opcode]] & HAS_ERROR_FLAG) {
379
        printf(", error_target=%d", uop->error_target);
380
    }
381
382
    printf(")");
383
}
384
#endif
385
386
static Py_ssize_t
387
uop_len(PyObject *op)
388
{
389
    _PyExecutorObject *self = _PyExecutorObject_CAST(op);
390
    return self->code_size;
391
}
392
393
static PyObject *
394
uop_item(PyObject *op, Py_ssize_t index)
395
{
396
    _PyExecutorObject *self = _PyExecutorObject_CAST(op);
397
    Py_ssize_t len = uop_len(op);
398
    if (index < 0 || index >= len) {
399
        PyErr_SetNone(PyExc_IndexError);
400
        return NULL;
401
    }
402
    int opcode = self->trace[index].opcode;
403
    int base_opcode = _PyUop_Uncached[opcode];
404
    const char *name = _PyUOpName(base_opcode);
405
    if (name == NULL) {
406
        name = "<nil>";
407
    }
408
    PyObject *oname = _PyUnicode_FromASCII(name, strlen(name));
409
    if (oname == NULL) {
410
        return NULL;
411
    }
412
    PyObject *oparg = PyLong_FromUnsignedLong(self->trace[index].oparg);
413
    if (oparg == NULL) {
414
        Py_DECREF(oname);
415
        return NULL;
416
    }
417
    PyObject *target = PyLong_FromUnsignedLong(self->trace[index].target);
418
    if (target == NULL) {
419
        Py_DECREF(oparg);
420
        Py_DECREF(oname);
421
        return NULL;
422
    }
423
    PyObject *operand = PyLong_FromUnsignedLongLong(self->trace[index].operand0);
424
    if (operand == NULL) {
425
        Py_DECREF(target);
426
        Py_DECREF(oparg);
427
        Py_DECREF(oname);
428
        return NULL;
429
    }
430
    PyObject *args[4] = { oname, oparg, target, operand };
431
    return _PyTuple_FromArraySteal(args, 4);
432
}
433
434
PySequenceMethods uop_as_sequence = {
435
    .sq_length = uop_len,
436
    .sq_item = uop_item,
437
};
438
439
static int
440
executor_traverse(PyObject *o, visitproc visit, void *arg)
441
{
442
    _PyExecutorObject *executor = _PyExecutorObject_CAST(o);
443
    for (uint32_t i = 0; i < executor->exit_count; i++) {
444
        Py_VISIT(executor->exits[i].executor);
445
    }
446
    return 0;
447
}
448
449
static PyObject *
450
get_jit_code(PyObject *self, PyObject *Py_UNUSED(ignored))
451
{
452
#ifndef _Py_JIT
453
    PyErr_SetString(PyExc_RuntimeError, "JIT support not enabled.");
454
    return NULL;
455
#else
456
    _PyExecutorObject *executor = _PyExecutorObject_CAST(self);
457
    if (executor->jit_code == NULL || executor->jit_size == 0) {
458
        Py_RETURN_NONE;
459
    }
460
    return PyBytes_FromStringAndSize(executor->jit_code, executor->jit_size);
461
#endif
462
}
463
464
static PyMethodDef uop_executor_methods[] = {
465
    { "is_valid", is_valid, METH_NOARGS, NULL },
466
    { "get_jit_code", get_jit_code, METH_NOARGS, NULL},
467
    { "get_opcode", get_opcode, METH_NOARGS, NULL },
468
    { "get_oparg", get_oparg, METH_NOARGS, NULL },
469
    { NULL, NULL },
470
};
471
472
static int
473
executor_is_gc(PyObject *o)
474
{
475
    return !_Py_IsImmortal(o);
476
}
477
478
PyTypeObject _PyUOpExecutor_Type = {
479
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
480
    .tp_name = "uop_executor",
481
    .tp_basicsize = offsetof(_PyExecutorObject, exits),
482
    .tp_itemsize = 1,
483
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC,
484
    .tp_dealloc = uop_dealloc,
485
    .tp_as_sequence = &uop_as_sequence,
486
    .tp_methods = uop_executor_methods,
487
    .tp_traverse = executor_traverse,
488
    .tp_clear = executor_clear,
489
    .tp_is_gc = executor_is_gc,
490
};
491
492
/* TO DO -- Generate these tables */
493
static const uint16_t
494
_PyUOp_Replacements[MAX_UOP_ID + 1] = {
495
    [_ITER_JUMP_RANGE] = _GUARD_NOT_EXHAUSTED_RANGE,
496
    [_ITER_JUMP_LIST] = _GUARD_NOT_EXHAUSTED_LIST,
497
    [_ITER_JUMP_TUPLE] = _GUARD_NOT_EXHAUSTED_TUPLE,
498
    [_FOR_ITER] = _FOR_ITER_TIER_TWO,
499
    [_FOR_ITER_VIRTUAL] = _FOR_ITER_VIRTUAL_TIER_TWO,
500
    [_ITER_NEXT_LIST] = _ITER_NEXT_LIST_TIER_TWO,
501
    [_CHECK_PERIODIC_AT_END] = _TIER2_RESUME_CHECK,
502
    [_LOAD_BYTECODE] = _NOP,
503
    [_SEND_VIRTUAL] = _SEND_VIRTUAL_TIER_TWO,
504
    [_SEND_ASYNC_GEN] = _SEND_ASYNC_GEN_TIER_TWO,
505
};
506
507
static const uint8_t
508
is_for_iter_test[MAX_UOP_ID + 1] = {
509
    [_GUARD_NOT_EXHAUSTED_RANGE] = 1,
510
    [_GUARD_NOT_EXHAUSTED_LIST] = 1,
511
    [_GUARD_NOT_EXHAUSTED_TUPLE] = 1,
512
    [_FOR_ITER_TIER_TWO] = 1,
513
    [_ITER_NEXT_INLINE] = 1,
514
};
515
516
static const uint16_t
517
BRANCH_TO_GUARD[4][2] = {
518
    [POP_JUMP_IF_FALSE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_TRUE_POP,
519
    [POP_JUMP_IF_FALSE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_FALSE_POP,
520
    [POP_JUMP_IF_TRUE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_FALSE_POP,
521
    [POP_JUMP_IF_TRUE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_TRUE_POP,
522
    [POP_JUMP_IF_NONE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_NOT_NONE_POP,
523
    [POP_JUMP_IF_NONE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_NONE_POP,
524
    [POP_JUMP_IF_NOT_NONE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_NONE_POP,
525
    [POP_JUMP_IF_NOT_NONE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_NOT_NONE_POP,
526
};
527
528
static const uint16_t
529
guard_ip_uop[MAX_UOP_ID + 1] = {
530
    [_PUSH_FRAME] = _GUARD_IP__PUSH_FRAME,
531
    [_RETURN_GENERATOR] = _GUARD_IP_RETURN_GENERATOR,
532
    [_RETURN_VALUE] = _GUARD_IP_RETURN_VALUE,
533
    [_YIELD_VALUE] = _GUARD_IP_YIELD_VALUE,
534
};
535
536
static const uint16_t
537
guard_code_version_uop[MAX_UOP_ID + 1] = {
538
    [_PUSH_FRAME] = _GUARD_CODE_VERSION__PUSH_FRAME,
539
    [_RETURN_GENERATOR] = _GUARD_CODE_VERSION_RETURN_GENERATOR,
540
    [_RETURN_VALUE] = _GUARD_CODE_VERSION_RETURN_VALUE,
541
    [_YIELD_VALUE] = _GUARD_CODE_VERSION_YIELD_VALUE,
542
};
543
544
static const uint16_t
545
dynamic_exit_uop[MAX_UOP_ID + 1] = {
546
    [_GUARD_IP__PUSH_FRAME] = 1,
547
    [_GUARD_IP_RETURN_GENERATOR] = 1,
548
    [_GUARD_IP_RETURN_VALUE] = 1,
549
    [_GUARD_IP_YIELD_VALUE] = 1,
550
    [_GUARD_CODE_VERSION__PUSH_FRAME] = 1,
551
    [_GUARD_CODE_VERSION_RETURN_GENERATOR] = 1,
552
    [_GUARD_CODE_VERSION_RETURN_VALUE] = 1,
553
    [_GUARD_CODE_VERSION_YIELD_VALUE] = 1,
554
};
555
556
557
558
#ifdef Py_DEBUG
559
#define DPRINTF(level, ...) \
560
    if (lltrace >= (level)) { printf(__VA_ARGS__); }
561
#else
562
#define DPRINTF(level, ...)
563
#endif
564
565
566
static inline void
567
add_to_trace(
568
    _PyJitTracerState *tracer,
569
    uint16_t opcode,
570
    uint16_t oparg,
571
    uint64_t operand,
572
    uint32_t target)
573
{
574
    _PyJitUopBuffer *trace = &tracer->code_buffer;
575
    _PyUOpInstruction *inst = trace->next;
576
    inst->opcode = opcode;
577
    inst->format = UOP_FORMAT_TARGET;
578
    inst->target = target;
579
    inst->oparg = oparg;
580
    inst->operand0 = operand;
581
#ifdef Py_STATS
582
    inst->execution_count = 0;
583
    inst->fitness = tracer->translator_state.fitness;
584
#endif
585
    trace->next++;
586
}
587
588
589
#ifdef Py_DEBUG
590
#define ADD_TO_TRACE(OPCODE, OPARG, OPERAND, TARGET) \
591
    add_to_trace(tracer, (OPCODE), (OPARG), (OPERAND), (TARGET)); \
592
    if (lltrace >= 2) { \
593
        printf("%4d ADD_TO_TRACE: ", uop_buffer_length(trace)); \
594
        _PyUOpPrint(uop_buffer_last(trace)); \
595
        printf("\n"); \
596
    }
597
#else
598
#define ADD_TO_TRACE(OPCODE, OPARG, OPERAND, TARGET) \
599
    add_to_trace(tracer, (OPCODE), (OPARG), (OPERAND), (TARGET))
600
#endif
601
602
#define INSTR_IP(INSTR, CODE) \
603
    ((uint32_t)((INSTR) - ((_Py_CODEUNIT *)(CODE)->co_code_adaptive)))
604
605
606
/* Branch penalty: 0 for a fully biased branch and FITNESS_BRANCH_BALANCED for
607
 * a balanced or fully off-trace branch. This keeps any single branch from
608
 * consuming more than one balanced-branch cost.
609
 */
610
static inline int
611
compute_branch_penalty(uint16_t history)
612
{
613
    bool branch_taken = history & 1;
614
    int taken_count = _Py_popcount32((uint32_t)history);
615
    int on_trace_count = branch_taken ? taken_count : 16 - taken_count;
616
    int off_trace = 16 - on_trace_count;
617
    int penalty = off_trace * FITNESS_BRANCH_BALANCED / 8;
618
    if (penalty > FITNESS_BRANCH_BALANCED) {
619
        penalty = FITNESS_BRANCH_BALANCED;
620
    }
621
    return penalty;
622
}
623
624
/* Compute exit quality for the current trace position.
625
 * Higher values mean better places to stop the trace. */
626
static inline int32_t
627
compute_exit_quality(_Py_CODEUNIT *target_instr, int opcode,
628
                     const _PyJitTracerState *tracer)
629
{
630
    if (target_instr == tracer->initial_state.close_loop_instr) {
631
        return EXIT_QUALITY_CLOSE_LOOP;
632
    }
633
    else if (target_instr->op.code == ENTER_EXECUTOR) {
634
        return EXIT_QUALITY_ENTER_EXECUTOR;
635
    }
636
    else if (opcode == JUMP_BACKWARD_JIT ||
637
        opcode == JUMP_BACKWARD ||
638
        opcode == JUMP_BACKWARD_NO_INTERRUPT) {
639
        return EXIT_QUALITY_BACKWARD_EDGE;
640
    }
641
    else if (_PyOpcode_Caches[_PyOpcode_Deopt[opcode]] > 0) {
642
        return EXIT_QUALITY_SPECIALIZABLE;
643
    }
644
    return EXIT_QUALITY_DEFAULT;
645
}
646
647
/* Frame penalty: (MAX_ABSTRACT_FRAME_DEPTH-1) pushes exhaust fitness. */
648
static inline int32_t
649
compute_frame_penalty(uint16_t fitness_initial)
650
{
651
    return (int32_t)fitness_initial / (MAX_ABSTRACT_FRAME_DEPTH - 1) + 1;
652
}
653
654
static int
655
is_terminator(const _PyUOpInstruction *uop)
656
{
657
    int opcode = _PyUop_Uncached[uop->opcode];
658
    return (
659
        opcode == _EXIT_TRACE ||
660
        opcode == _DEOPT ||
661
        opcode == _JUMP_TO_TOP ||
662
        opcode == _DYNAMIC_EXIT
663
    );
664
}
665
666
/* Returns 1 on success (added to trace), 0 on trace end.
667
 */
668
// gh-142543: inlining this function causes stack overflows
669
Py_NO_INLINE int
670
_PyJit_translate_single_bytecode_to_trace(
671
    PyThreadState *tstate,
672
    _PyInterpreterFrame *frame,
673
    _Py_CODEUNIT *next_instr,
674
    int stop_tracing_opcode)
675
{
676
677
#ifdef Py_DEBUG
678
    char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
679
    int lltrace = 0;
680
    if (python_lltrace != NULL && *python_lltrace >= '0') {
681
        lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
682
    }
683
#endif
684
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
685
    _PyJitTracerState *tracer = _tstate->jit_tracer_state;
686
    PyCodeObject *old_code = tracer->prev_state.instr_code;
687
    bool progress_needed = (tracer->initial_state.chain_depth % MAX_CHAIN_DEPTH) == 0;
688
    _PyJitUopBuffer *trace = &tracer->code_buffer;
689
690
    _Py_CODEUNIT *this_instr =  tracer->prev_state.instr;
691
    _Py_CODEUNIT *target_instr = this_instr;
692
    uint32_t target = 0;
693
694
    target = Py_IsNone((PyObject *)old_code)
695
        ? (uint32_t)(target_instr - _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS_PTR)
696
        : INSTR_IP(target_instr, old_code);
697
698
    // Rewind EXTENDED_ARG so that we see the whole thing.
699
    // We must point to the first EXTENDED_ARG when deopting.
700
    int oparg = tracer->prev_state.instr_oparg;
701
    int opcode = this_instr->op.code;
702
    int rewind_oparg = oparg;
703
    while (rewind_oparg > 255) {
704
        rewind_oparg >>= 8;
705
        target--;
706
    }
707
708
    if (opcode == ENTER_EXECUTOR) {
709
        _PyExecutorObject *executor = old_code->co_executors->executors[oparg & 255];
710
        opcode = executor->vm_data.opcode;
711
        oparg = (oparg & ~255) | executor->vm_data.oparg;
712
    }
713
714
    if (_PyOpcode_Caches[_PyOpcode_Deopt[opcode]] > 0) {
715
        uint16_t backoff = (this_instr + 1)->counter.value_and_backoff;
716
        // adaptive_counter_cooldown is a fresh specialization.
717
        // trigger_backoff_counter is what we set during tracing.
718
        // All tracing backoffs should be freshly specialized or untouched.
719
        // If not, that indicates a deopt during tracing, and
720
        // thus the "actual" instruction executed is not the one that is
721
        // in the instruction stream, but rather the deopt.
722
        // It's important we check for this, as some specializations might make
723
        // no progress (they can immediately deopt after specializing).
724
        // We do this to improve performance, as otherwise a compiled trace
725
        // will just deopt immediately.
726
        if (backoff != adaptive_counter_cooldown().value_and_backoff &&
727
            backoff != trigger_backoff_counter().value_and_backoff) {
728
            OPT_STAT_INC(trace_immediately_deopts);
729
            opcode = _PyOpcode_Deopt[opcode];
730
        }
731
    }
732
733
    // Strange control-flow
734
    bool has_dynamic_jump_taken = OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) &&
735
        (next_instr != this_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]]);
736
737
    /* Special case the first instruction,
738
    * so that we can guarantee forward progress */
739
    if (progress_needed && uop_buffer_length(&tracer->code_buffer) < CODE_SIZE_NO_PROGRESS) {
740
        if (OPCODE_HAS_EXIT(opcode) || OPCODE_HAS_DEOPT(opcode)) {
741
            opcode = _PyOpcode_Deopt[opcode];
742
        }
743
        assert(!OPCODE_HAS_EXIT(opcode));
744
        assert(!OPCODE_HAS_DEOPT(opcode));
745
    }
746
747
    bool needs_guard_ip = OPCODE_HAS_NEEDS_GUARD_IP(opcode);
748
    if (has_dynamic_jump_taken && !needs_guard_ip) {
749
        DPRINTF(2, "Unsupported: dynamic jump taken %s\n", _PyOpcode_OpName[opcode]);
750
        goto unsupported;
751
    }
752
753
    int is_sys_tracing = (tstate->c_tracefunc != NULL) || (tstate->c_profilefunc != NULL);
754
    if (is_sys_tracing) {
755
        goto done;
756
    }
757
758
    if (stop_tracing_opcode == _DEOPT) {
759
        // gh-143183: It's important we rewind to the last known proper target.
760
        // The current target might be garbage as stop tracing usually indicates
761
        // we are in something that we can't trace.
762
        DPRINTF(2, "Told to stop tracing\n");
763
        goto unsupported;
764
    }
765
    else if (stop_tracing_opcode != 0) {
766
        assert(stop_tracing_opcode == _EXIT_TRACE);
767
        ADD_TO_TRACE(stop_tracing_opcode, 0, 0, target);
768
        goto done;
769
    }
770
771
    DPRINTF(2, "%p %d: %s(%d) %d\n", old_code, target, _PyOpcode_OpName[opcode], oparg, needs_guard_ip);
772
773
#ifdef Py_DEBUG
774
    if (oparg > 255) {
775
        assert(_Py_GetBaseCodeUnit(old_code, target).op.code == EXTENDED_ARG);
776
    }
777
#endif
778
779
    // This happens when a recursive call happens that we can't trace. Such as Python -> C -> Python calls
780
    // If we haven't guarded the IP, then it's untraceable.
781
    if (frame != tracer->prev_state.instr_frame && !needs_guard_ip) {
782
        DPRINTF(2, "Unsupported: unguardable jump taken\n");
783
        goto unsupported;
784
    }
785
786
    if (oparg > 0xFFFF) {
787
        DPRINTF(2, "Unsupported: oparg too large\n");
788
        unsupported:
789
        {
790
            _PyUOpInstruction *curr = uop_buffer_last(trace);
791
            while (curr->opcode != _SET_IP && uop_buffer_length(trace) > 2) {
792
                trace->next--;
793
                curr = uop_buffer_last(trace);
794
            }
795
            if (curr->opcode == _SET_IP) {
796
                int32_t old_target = (int32_t)uop_get_target(curr);
797
                curr->opcode = _DEOPT;
798
                curr->format = UOP_FORMAT_TARGET;
799
                curr->target = old_target;
800
            }
801
            goto done;
802
        }
803
    }
804
805
    if (opcode == NOP) {
806
        return 1;
807
    }
808
809
    if (opcode == JUMP_FORWARD) {
810
        return 1;
811
    }
812
813
    if (opcode == EXTENDED_ARG) {
814
        return 1;
815
    }
816
817
    // Stop the trace if fitness has dropped below the exit quality threshold.
818
    _PyJitTracerTranslatorState *ts = &tracer->translator_state;
819
    int32_t eq = compute_exit_quality(target_instr, opcode, tracer);
820
    DPRINTF(3, "Fitness check: %s(%d) fitness=%d, exit_quality=%d, depth=%d\n",
821
            _PyOpcode_OpName[opcode], oparg, ts->fitness, eq, ts->frame_depth);
822
823
    if (ts->fitness < eq) {
824
        // Heuristic exit: leave operand1=0 so the side exit increments chain_depth.
825
        ADD_TO_TRACE(_EXIT_TRACE, 0, 0, target);
826
        OPT_STAT_INC(fitness_terminated_traces);
827
        DPRINTF(2, "Fitness terminated: %s(%d) fitness=%d < exit_quality=%d\n",
828
                _PyOpcode_OpName[opcode], oparg, ts->fitness, eq);
829
        goto done;
830
    }
831
832
    // Snapshot remaining space so the later fitness charge reflects all buffer
833
    // space this bytecode consumed, including reserved tail slots.
834
    int32_t remaining_before = uop_buffer_remaining_space(trace);
835
836
    // One for possible _DEOPT, one because _CHECK_VALIDITY itself might _DEOPT
837
    trace->end -= 2;
838
839
    const _PyOpcodeRecordSlotMap *record_slot_map = &_PyOpcode_RecordSlotMaps[opcode];
840
841
    assert(opcode != ENTER_EXECUTOR && opcode != EXTENDED_ARG);
842
    assert(!_PyErr_Occurred(tstate));
843
844
845
    if (OPCODE_HAS_EXIT(opcode)) {
846
        // Make space for side exit
847
        trace->end--;
848
    }
849
    if (OPCODE_HAS_ERROR(opcode)) {
850
        // Make space for error stub
851
        trace->end--;
852
    }
853
    if (OPCODE_HAS_DEOPT(opcode)) {
854
        // Make space for side exit
855
        trace->end--;
856
    }
857
858
    // _GUARD_IP leads to an exit.
859
    trace->end -= needs_guard_ip;
860
861
#if Py_DEBUG
862
    const struct opcode_macro_expansion *expansion = &_PyOpcode_macro_expansion[opcode];
863
    int space_needed = expansion->nuops + needs_guard_ip + 2 + (!OPCODE_HAS_NO_SAVE_IP(opcode));
864
    assert(uop_buffer_remaining_space(trace) > space_needed);
865
#endif
866
867
    ADD_TO_TRACE(_CHECK_VALIDITY, 0, 0, target);
868
869
    if (!OPCODE_HAS_NO_SAVE_IP(opcode)) {
870
        ADD_TO_TRACE(_SET_IP, 0, (uintptr_t)target_instr, target);
871
    }
872
873
    switch (opcode) {
874
        case POP_JUMP_IF_NONE:
875
        case POP_JUMP_IF_NOT_NONE:
876
        case POP_JUMP_IF_FALSE:
877
        case POP_JUMP_IF_TRUE:
878
        {
879
            _Py_CODEUNIT *computed_next_instr_without_modifiers = target_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]];
880
            _Py_CODEUNIT *computed_next_instr = computed_next_instr_without_modifiers + (computed_next_instr_without_modifiers->op.code == NOT_TAKEN);
881
            _Py_CODEUNIT *computed_jump_instr = computed_next_instr_without_modifiers + oparg;
882
            assert(next_instr == computed_next_instr || next_instr == computed_jump_instr);
883
            int jump_happened = target_instr[1].cache & 1;
884
            assert(jump_happened ? (next_instr == computed_jump_instr) : (next_instr == computed_next_instr));
885
            uint32_t uopcode = BRANCH_TO_GUARD[opcode - POP_JUMP_IF_FALSE][jump_happened];
886
            ADD_TO_TRACE(uopcode, 0, 0, INSTR_IP(jump_happened ? computed_next_instr : computed_jump_instr, old_code));
887
            int bp = compute_branch_penalty(target_instr[1].cache);
888
            tracer->translator_state.fitness -= bp;
889
            DPRINTF(3, "  branch penalty: -%d (history=0x%04x, taken=%d) -> fitness=%d\n",
890
                    bp, target_instr[1].cache, jump_happened,
891
                    tracer->translator_state.fitness);
892
893
            break;
894
        }
895
        case JUMP_BACKWARD_JIT:
896
            // This is possible as the JIT might have re-activated after it was disabled
897
        case JUMP_BACKWARD_NO_JIT:
898
        case JUMP_BACKWARD:
899
            ADD_TO_TRACE(_CHECK_PERIODIC, 0, 0, target);
900
            break;
901
        case JUMP_BACKWARD_NO_INTERRUPT:
902
            break;
903
904
        case RESUME:
905
        case RESUME_CHECK:
906
        case RESUME_CHECK_JIT:
907
            /* Use a special tier 2 version of RESUME_CHECK to allow traces to
908
             *  start with RESUME_CHECK */
909
            ADD_TO_TRACE(_TIER2_RESUME_CHECK, 0, 0, target);
910
            break;
911
        default:
912
        {
913
            const struct opcode_macro_expansion *expansion = &_PyOpcode_macro_expansion[opcode];
914
            // Reserve space for nuops (+ _SET_IP + _EXIT_TRACE)
915
            int nuops = expansion->nuops;
916
            if (nuops == 0) {
917
                DPRINTF(2, "Unsupported opcode %s\n", _PyOpcode_OpName[opcode]);
918
                goto unsupported;
919
            }
920
            assert(nuops > 0);
921
            uint32_t orig_oparg = oparg;  // For OPARG_TOP/BOTTOM
922
            uint32_t orig_target = target;
923
            int record_idx = 0;
924
            for (int i = 0; i < nuops; i++) {
925
                oparg = orig_oparg;
926
                target = orig_target;
927
                uint32_t uop = expansion->uops[i].uop;
928
                uint64_t operand = 0;
929
                // Add one to account for the actual opcode/oparg pair:
930
                int offset = expansion->uops[i].offset + 1;
931
                switch (expansion->uops[i].size) {
932
                    case OPARG_SIMPLE:
933
                        assert(opcode != _JUMP_BACKWARD_NO_INTERRUPT && opcode != JUMP_BACKWARD);
934
                        break;
935
                    case OPARG_CACHE_1:
936
                        operand = read_u16(&this_instr[offset].cache);
937
                        break;
938
                    case OPARG_CACHE_2:
939
                        operand = read_u32(&this_instr[offset].cache);
940
                        break;
941
                    case OPARG_CACHE_4:
942
                        operand = read_u64(&this_instr[offset].cache);
943
                        break;
944
                    case OPARG_TOP:  // First half of super-instr
945
                        assert(orig_oparg <= 255);
946
                        oparg = orig_oparg >> 4;
947
                        break;
948
                    case OPARG_BOTTOM:  // Second half of super-instr
949
                        assert(orig_oparg <= 255);
950
                        oparg = orig_oparg & 0xF;
951
                        break;
952
                    case OPARG_SAVE_RETURN_OFFSET:  // op=_SAVE_RETURN_OFFSET; oparg=return_offset
953
                        oparg = offset;
954
                        assert(uop == _SAVE_RETURN_OFFSET);
955
                        break;
956
                    case OPARG_REPLACED:
957
                        uop = _PyUOp_Replacements[uop];
958
                        assert(uop != 0);
959
                        uint32_t next_inst = target + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]];
960
                        if (uop == _TIER2_RESUME_CHECK) {
961
                            if (this_instr[-1].op.code == LOAD_SPECIAL) {
962
                                // Don't check eval breaker immediately after LOAD_SPECIAL
963
                                uop = _NOP;
964
                            }
965
                            else {
966
                                target = next_inst;
967
                            }
968
                        }
969
                        else {
970
                            int extended_arg = orig_oparg > 255;
971
                            uint32_t jump_target = next_inst + orig_oparg + extended_arg;
972
                            /* Jump must be to an "END" either END_FOR or END_SEND */
973
                            assert((
974
                                    _Py_GetBaseCodeUnit(old_code, jump_target).op.code == END_FOR &&
975
                                    _Py_GetBaseCodeUnit(old_code, jump_target+1).op.code == POP_ITER
976
                                )
977
                                ||
978
                                _Py_GetBaseCodeUnit(old_code, jump_target).op.code == END_SEND
979
                            );
980
                            if (is_for_iter_test[uop]) {
981
                                target = jump_target + 1;
982
                            }
983
                        }
984
                        break;
985
                    case OPERAND1_1:
986
                        assert(uop_buffer_last(trace)->opcode == uop);
987
                        operand = read_u16(&this_instr[offset].cache);
988
                        uop_buffer_last(trace)->operand1 = operand;
989
                        continue;
990
                    case OPERAND1_2:
991
                        assert(uop_buffer_last(trace)->opcode == uop);
992
                        operand = read_u32(&this_instr[offset].cache);
993
                        uop_buffer_last(trace)->operand1 = operand;
994
                        continue;
995
                    case OPERAND1_4:
996
                        assert(uop_buffer_last(trace)->opcode == uop);
997
                        operand = read_u64(&this_instr[offset].cache);
998
                        uop_buffer_last(trace)->operand1 = operand;
999
                        continue;
1000
                    default:
1001
                        fprintf(stderr,
1002
                                "opcode=%d, oparg=%d; nuops=%d, i=%d; size=%d, offset=%d\n",
1003
                                opcode, oparg, nuops, i,
1004
                                expansion->uops[i].size,
1005
                                expansion->uops[i].offset);
1006
                        Py_FatalError("garbled expansion");
1007
                }
1008
                if (uop == _BINARY_OP_INPLACE_ADD_UNICODE) {
1009
                    assert(i + 1 == nuops);
1010
                    _Py_CODEUNIT *next = target_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]];
1011
                    assert(next->op.code == STORE_FAST);
1012
                    operand = next->op.arg;
1013
                }
1014
                else if (uop == _PUSH_FRAME) {
1015
                    _PyJitTracerTranslatorState *ts_depth = &tracer->translator_state;
1016
                    ts_depth->frame_depth++;
1017
                    assert(ts_depth->frame_depth < MAX_ABSTRACT_FRAME_DEPTH);
1018
                    int32_t frame_penalty = compute_frame_penalty(tstate->interp->opt_config.fitness_initial);
1019
                    ts_depth->fitness -= frame_penalty;
1020
                    DPRINTF(3, "  _PUSH_FRAME: depth=%d, penalty=-%d -> fitness=%d\n",
1021
                            ts_depth->frame_depth, frame_penalty,
1022
                            ts_depth->fitness);
1023
                }
1024
                else if (uop == _RETURN_VALUE || uop == _RETURN_GENERATOR || uop == _YIELD_VALUE) {
1025
                    _PyJitTracerTranslatorState *ts_depth = &tracer->translator_state;
1026
                    int32_t frame_penalty = compute_frame_penalty(tstate->interp->opt_config.fitness_initial);
1027
                    if (ts_depth->frame_depth <= 0) {
1028
                        // Returning past the traced root is normal for guarded
1029
                        // caller continuation. Charge a small penalty so these
1030
                        // paths still terminate.
1031
                        int32_t underflow_penalty = frame_penalty / 4;
1032
                        ts_depth->fitness -= underflow_penalty;
1033
                        DPRINTF(3, "  %s: underflow penalty=-%d -> fitness=%d\n",
1034
                                _PyOpcode_uop_name[uop], underflow_penalty,
1035
                                ts_depth->fitness);
1036
                    }
1037
                    else {
1038
                        // Symmetric with push: net-zero frame impact.
1039
                        ts_depth->fitness += frame_penalty;
1040
                        ts_depth->frame_depth--;
1041
                        DPRINTF(3, "  %s: return reward=+%d, depth=%d -> fitness=%d\n",
1042
                                _PyOpcode_uop_name[uop], frame_penalty,
1043
                                ts_depth->frame_depth,
1044
                                ts_depth->fitness);
1045
                    }
1046
                }
1047
                else if (_PyUop_Flags[uop] & HAS_RECORDS_VALUE_FLAG) {
1048
                    assert(record_idx < record_slot_map->count);
1049
                    uint8_t record_slot = record_slot_map->slots[record_idx];
1050
                    assert(record_slot < tracer->prev_state.recorded_count);
1051
                    PyObject *recorded_value = tracer->prev_state.recorded_values[record_slot];
1052
                    tracer->prev_state.recorded_values[record_slot] = NULL;
1053
                    if ((record_slot_map->transform_mask & (1u << record_idx)) &&
1054
                        recorded_value != NULL) {
1055
                        recorded_value = _PyOpcode_RecordTransformValue(uop, recorded_value);
1056
                    }
1057
                    record_idx++;
1058
                    operand = (uintptr_t)recorded_value;
1059
                }
1060
                // All other instructions
1061
                ADD_TO_TRACE(uop, oparg, operand, target);
1062
            }
1063
            break;
1064
        }  // End default
1065
1066
    }  // End switch (opcode)
1067
1068
    if (needs_guard_ip) {
1069
        int last_opcode = uop_buffer_last(trace)->opcode;
1070
        uint16_t guard_ip = guard_ip_uop[last_opcode];
1071
        if (guard_ip == 0) {
1072
            DPRINTF(1, "Unknown uop needing guard ip %s\n", _PyOpcode_uop_name[last_opcode]);
1073
            Py_UNREACHABLE();
1074
        }
1075
        PyObject *code = PyStackRef_AsPyObjectBorrow(frame->f_executable);
1076
        Py_INCREF(code);
1077
        ADD_TO_TRACE(_RECORD_CODE, 0, (uintptr_t)code, 0);
1078
        ADD_TO_TRACE(guard_ip, 0, (uintptr_t)next_instr, 0);
1079
        if (PyCode_Check(code)) {
1080
            /* Record stack depth, in operand1 */
1081
            int stack_depth = (int)(frame->stackpointer - _PyFrame_Stackbase(frame));
1082
            uop_buffer_last(trace)->operand1 = stack_depth;
1083
            ADD_TO_TRACE(guard_code_version_uop[last_opcode], 0, ((PyCodeObject *)code)->co_version, 0);
1084
        }
1085
    }
1086
    // Loop back to the start
1087
    int is_first_instr = tracer->initial_state.close_loop_instr == next_instr ||
1088
        tracer->initial_state.start_instr == next_instr;
1089
    if (is_first_instr && uop_buffer_length(trace) > CODE_SIZE_NO_PROGRESS) {
1090
        if (needs_guard_ip) {
1091
            ADD_TO_TRACE(_SET_IP, 0, (uintptr_t)next_instr, 0);
1092
        }
1093
        ADD_TO_TRACE(_JUMP_TO_TOP, 0, 0, 0);
1094
        goto done;
1095
    }
1096
    // Charge fitness by trace-buffer capacity consumed for this bytecode,
1097
    // including both emitted uops and tail reservations.
1098
    {
1099
        int32_t slots_used = remaining_before - uop_buffer_remaining_space(trace);
1100
        tracer->translator_state.fitness -= slots_used;
1101
        DPRINTF(3, "  per-insn cost: -%d -> fitness=%d\n", slots_used,
1102
                tracer->translator_state.fitness);
1103
    }
1104
    DPRINTF(2, "Trace continuing (fitness=%d)\n", tracer->translator_state.fitness);
1105
    return 1;
1106
done:
1107
    DPRINTF(2, "Trace done\n");
1108
    if (!is_terminator(uop_buffer_last(trace))) {
1109
        ADD_TO_TRACE(_EXIT_TRACE, 0, 0, target);
1110
    }
1111
    return 0;
1112
}
1113
1114
// Returns 0 for do not enter tracing, 1 on enter tracing.
1115
// gh-142543: inlining this function causes stack overflows
1116
Py_NO_INLINE int
1117
_PyJit_TryInitializeTracing(
1118
    PyThreadState *tstate, _PyInterpreterFrame *frame, _Py_CODEUNIT *curr_instr,
1119
    _Py_CODEUNIT *start_instr, _Py_CODEUNIT *close_loop_instr, _PyStackRef *stack_pointer, int chain_depth,
1120
    _PyExitData *exit, int oparg, _PyExecutorObject *current_executor)
1121
{
1122
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1123
    if (_tstate->jit_tracer_state == NULL) {
1124
        _tstate->jit_tracer_state = (_PyJitTracerState *)_PyObject_VirtualAlloc(sizeof(_PyJitTracerState));
1125
        if (_tstate->jit_tracer_state == NULL) {
1126
            // Don't error, just go to next instruction.
1127
            return 0;
1128
        }
1129
        _tstate->jit_tracer_state->is_tracing = false;
1130
    }
1131
    _PyJitTracerState *tracer = _tstate->jit_tracer_state;
1132
    // A recursive trace.
1133
    if (tracer->is_tracing) {
1134
        return 0;
1135
    }
1136
    if (oparg > 0xFFFF) {
1137
        return 0;
1138
    }
1139
    PyObject *func = PyStackRef_AsPyObjectBorrow(frame->f_funcobj);
1140
    if (func == NULL || !PyFunction_Check(func)) {
1141
        return 0;
1142
    }
1143
    PyCodeObject *code = _PyFrame_GetCode(frame);
1144
#ifdef Py_DEBUG
1145
    char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
1146
    int lltrace = 0;
1147
    if (python_lltrace != NULL && *python_lltrace >= '0') {
1148
        lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
1149
    }
1150
    DPRINTF(2,
1151
        "Tracing %s (%s:%d) at byte offset %d at chain depth %d\n",
1152
        PyUnicode_AsUTF8(code->co_qualname),
1153
        PyUnicode_AsUTF8(code->co_filename),
1154
        code->co_firstlineno,
1155
        2 * INSTR_IP(close_loop_instr, code),
1156
        chain_depth);
1157
#endif
1158
    /* Set up tracing buffer*/
1159
    _PyJitUopBuffer *trace = &tracer->code_buffer;
1160
    uop_buffer_init(trace, &tracer->uop_array[0], UOP_MAX_TRACE_LENGTH);
1161
    _PyJitTracerTranslatorState *ts = &tracer->translator_state;
1162
    ts->fitness = tstate->interp->opt_config.fitness_initial;
1163
    ts->frame_depth = 0;
1164
    ADD_TO_TRACE(_START_EXECUTOR, 0, (uintptr_t)start_instr, INSTR_IP(start_instr, code));
1165
    ADD_TO_TRACE(_MAKE_WARM, 0, 0, 0);
1166
1167
    tracer->initial_state.start_instr = start_instr;
1168
    tracer->initial_state.close_loop_instr = close_loop_instr;
1169
    tracer->initial_state.code = (PyCodeObject *)Py_NewRef(code);
1170
    tracer->initial_state.func = (PyFunctionObject *)Py_NewRef(func);
1171
    tracer->initial_state.executor = (_PyExecutorObject *)Py_XNewRef(current_executor);
1172
    tracer->initial_state.exit = exit;
1173
    tracer->initial_state.stack_depth = (int)(stack_pointer - _PyFrame_Stackbase(frame));
1174
    tracer->initial_state.chain_depth = chain_depth;
1175
    tracer->prev_state.instr_code = (PyCodeObject *)Py_NewRef(_PyFrame_GetCode(frame));
1176
    tracer->prev_state.instr = curr_instr;
1177
    tracer->prev_state.instr_frame = frame;
1178
    tracer->prev_state.instr_oparg = oparg;
1179
    tracer->prev_state.instr_stacklevel = tracer->initial_state.stack_depth;
1180
    tracer->prev_state.recorded_count = 0;
1181
    for (int i = 0; i < MAX_RECORDED_VALUES; i++) {
1182
        tracer->prev_state.recorded_values[i] = NULL;
1183
    }
1184
    const _PyOpcodeRecordEntry *record_entry = &_PyOpcode_RecordEntries[curr_instr->op.code];
1185
    for (int i = 0; i < record_entry->count; i++) {
1186
        _Py_RecordFuncPtr record_func = _PyOpcode_RecordFunctions[record_entry->indices[i]];
1187
        record_func(frame, stack_pointer, oparg, &tracer->prev_state.recorded_values[i]);
1188
    }
1189
    tracer->prev_state.recorded_count = record_entry->count;
1190
    assert(curr_instr->op.code == JUMP_BACKWARD_JIT || curr_instr->op.code == RESUME_CHECK_JIT || (exit != NULL));
1191
    tracer->initial_state.jump_backward_instr = curr_instr;
1192
1193
    DPRINTF(3, "Fitness init: chain_depth=%d, fitness=%d\n",
1194
            chain_depth, ts->fitness);
1195
1196
    tracer->is_tracing = true;
1197
    return 1;
1198
}
1199
1200
Py_NO_INLINE void
1201
_PyJit_FinalizeTracing(PyThreadState *tstate, int err)
1202
{
1203
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1204
    _PyJitTracerState *tracer = _tstate->jit_tracer_state;
1205
    // Deal with backoffs
1206
    assert(tracer != NULL);
1207
    _PyExitData *exit = tracer->initial_state.exit;
1208
    if (exit == NULL) {
1209
        // We hold a strong reference to the code object, so the instruction won't be freed.
1210
        if (err <= 0) {
1211
            _Py_BackoffCounter counter = tracer->initial_state.jump_backward_instr[1].counter;
1212
            tracer->initial_state.jump_backward_instr[1].counter = restart_backoff_counter(counter);
1213
        }
1214
        else {
1215
            if (tracer->initial_state.jump_backward_instr[0].op.code == JUMP_BACKWARD_JIT) {
1216
                tracer->initial_state.jump_backward_instr[1].counter = initial_jump_backoff_counter(&tstate->interp->opt_config);
1217
            }
1218
            else {
1219
                tracer->initial_state.jump_backward_instr[1].counter = initial_resume_backoff_counter(&tstate->interp->opt_config);
1220
            }
1221
        }
1222
    }
1223
    else if (tracer->initial_state.executor->vm_data.valid) {
1224
        // Likewise, we hold a strong reference to the executor containing this exit, so the exit is guaranteed
1225
        // to be valid to access.
1226
        if (err <= 0) {
1227
            exit->temperature = restart_backoff_counter(exit->temperature);
1228
        }
1229
        else {
1230
            exit->temperature = initial_temperature_backoff_counter(&tstate->interp->opt_config);
1231
        }
1232
    }
1233
    // Clear all recorded values
1234
    _PyJitUopBuffer *buffer = &tracer->code_buffer;
1235
    for (_PyUOpInstruction *inst = buffer->start; inst < buffer->next; inst++) {
1236
        if (_PyUop_Flags[inst->opcode] & HAS_RECORDS_VALUE_FLAG) {
1237
            Py_XDECREF((PyObject *)(uintptr_t)inst->operand0);
1238
        }
1239
    }
1240
    Py_CLEAR(tracer->initial_state.code);
1241
    Py_CLEAR(tracer->initial_state.func);
1242
    Py_CLEAR(tracer->initial_state.executor);
1243
    Py_CLEAR(tracer->prev_state.instr_code);
1244
    for (int i = 0; i < MAX_RECORDED_VALUES; i++) {
1245
        Py_CLEAR(tracer->prev_state.recorded_values[i]);
1246
    }
1247
    tracer->prev_state.recorded_count = 0;
1248
    uop_buffer_init(buffer, &tracer->uop_array[0], UOP_MAX_TRACE_LENGTH);
1249
    tracer->is_tracing = false;
1250
}
1251
1252
bool
1253
_PyJit_EnterExecutorShouldStopTracing(int og_opcode)
1254
{
1255
    // Continue tracing (skip over the executor). If it's a RESUME
1256
    // trace to form longer, more optimizeable traces.
1257
    // We want to trace over RESUME traces. Otherwise, functions with lots of RESUME
1258
    // end up with many fragmented traces which perform badly.
1259
    // See for example, the richards benchmark in pyperformance.
1260
    // For consideration: We may want to consider tracing over side traces
1261
    // inserted into bytecode as well in the future.
1262
    return og_opcode == RESUME_CHECK_JIT;
1263
}
1264
1265
void
1266
_PyJit_TracerFree(_PyThreadStateImpl *_tstate)
1267
{
1268
    if (_tstate->jit_tracer_state != NULL) {
1269
        _PyObject_VirtualFree(_tstate->jit_tracer_state, sizeof(_PyJitTracerState));
1270
        _tstate->jit_tracer_state = NULL;
1271
    }
1272
}
1273
1274
#undef RESERVE
1275
#undef INSTR_IP
1276
#undef ADD_TO_TRACE
1277
#undef DPRINTF
1278
1279
#define UNSET_BIT(array, bit) (array[(bit)>>5] &= ~(1<<((bit)&31)))
1280
#define SET_BIT(array, bit) (array[(bit)>>5] |= (1<<((bit)&31)))
1281
#define BIT_IS_SET(array, bit) (array[(bit)>>5] & (1<<((bit)&31)))
1282
1283
/* Count the number of unused uops and exits
1284
*/
1285
static int
1286
count_exits(_PyUOpInstruction *buffer, int length)
1287
{
1288
    int exit_count = 0;
1289
    for (int i = 0; i < length; i++) {
1290
        uint16_t base_opcode = _PyUop_Uncached[buffer[i].opcode];
1291
        if (base_opcode == _EXIT_TRACE || base_opcode == _DYNAMIC_EXIT) {
1292
            exit_count++;
1293
        }
1294
    }
1295
    return exit_count;
1296
}
1297
1298
/* The number of cached registers at any exit (`EXIT_IF` or `DEOPT_IF`)
1299
 * This is the number of cached at entries at start, unless the uop is
1300
 * marked as `exit_depth_is_output` in which case it is the number of
1301
 * cached entries at the end */
1302
static int
1303
get_cached_entries_for_side_exit(_PyUOpInstruction *inst)
1304
{
1305
    // Maybe add another generated table for this?
1306
    int base_opcode = _PyUop_Uncached[inst->opcode];
1307
    assert(base_opcode != 0);
1308
    for (int i = 0; i <= MAX_CACHED_REGISTER; i++) {
1309
        const _PyUopTOSentry *entry = &_PyUop_Caching[base_opcode].entries[i];
1310
        if (entry->opcode == inst->opcode) {
1311
            return entry->exit;
1312
        }
1313
    }
1314
    Py_UNREACHABLE();
1315
}
1316
1317
static void make_exit(_PyUOpInstruction *inst, int opcode, int target, bool is_control_flow)
1318
{
1319
    assert(opcode > MAX_UOP_ID && opcode <= MAX_UOP_REGS_ID);
1320
    inst->opcode = opcode;
1321
    inst->oparg = 0;
1322
    inst->operand0 = 0;
1323
    inst->format = UOP_FORMAT_TARGET;
1324
    inst->target = target;
1325
    inst->operand1 = is_control_flow;
1326
#ifdef Py_STATS
1327
    inst->fitness = 0;
1328
    inst->execution_count = 0;
1329
#endif
1330
}
1331
1332
/* Convert implicit exits, errors and deopts
1333
 * into explicit ones. */
1334
static int
1335
prepare_for_execution(_PyUOpInstruction *buffer, int length)
1336
{
1337
    int32_t current_jump = -1;
1338
    int32_t current_jump_target = -1;
1339
    int32_t current_error = -1;
1340
    int32_t current_error_target = -1;
1341
    int32_t current_popped = -1;
1342
    int32_t current_exit_op = -1;
1343
    /* Leaving in NOPs slows down the interpreter and messes up the stats */
1344
    _PyUOpInstruction *copy_to = &buffer[0];
1345
    for (int i = 0; i < length; i++) {
1346
        _PyUOpInstruction *inst = &buffer[i];
1347
        if (inst->opcode != _NOP) {
1348
            if (copy_to != inst) {
1349
                *copy_to = *inst;
1350
            }
1351
            copy_to++;
1352
        }
1353
    }
1354
    length = (int)(copy_to - buffer);
1355
    int next_spare = length;
1356
    for (int i = 0; i < length; i++) {
1357
        _PyUOpInstruction *inst = &buffer[i];
1358
        int base_opcode = _PyUop_Uncached[inst->opcode];
1359
        assert(inst->opcode != _NOP);
1360
        int32_t target = (int32_t)uop_get_target(inst);
1361
        uint16_t exit_flags = _PyUop_Flags[base_opcode] & (HAS_EXIT_FLAG | HAS_DEOPT_FLAG | HAS_PERIODIC_FLAG);
1362
        if (exit_flags) {
1363
            uint16_t base_exit_op = _EXIT_TRACE;
1364
            if (exit_flags & HAS_DEOPT_FLAG) {
1365
                base_exit_op = _DEOPT;
1366
            }
1367
            else if (exit_flags & HAS_PERIODIC_FLAG) {
1368
                base_exit_op = _HANDLE_PENDING_AND_DEOPT;
1369
            }
1370
            int32_t jump_target = target;
1371
            if (dynamic_exit_uop[base_opcode]) {
1372
                base_exit_op = _DYNAMIC_EXIT;
1373
            }
1374
            int exit_depth = get_cached_entries_for_side_exit(inst);
1375
            assert(_PyUop_Caching[base_exit_op].entries[exit_depth].opcode > 0);
1376
            int16_t exit_op = _PyUop_Caching[base_exit_op].entries[exit_depth].opcode;
1377
            bool is_control_flow = (base_opcode == _GUARD_IS_FALSE_POP || base_opcode == _GUARD_IS_TRUE_POP || is_for_iter_test[base_opcode]);
1378
            if (jump_target != current_jump_target || current_exit_op != exit_op) {
1379
                make_exit(&buffer[next_spare], exit_op, jump_target, is_control_flow);
1380
                current_exit_op = exit_op;
1381
                current_jump_target = jump_target;
1382
                current_jump = next_spare;
1383
                next_spare++;
1384
            }
1385
            buffer[i].jump_target = current_jump;
1386
            buffer[i].format = UOP_FORMAT_JUMP;
1387
        }
1388
        if (_PyUop_Flags[base_opcode] & HAS_ERROR_FLAG) {
1389
            int popped = (_PyUop_Flags[base_opcode] & HAS_ERROR_NO_POP_FLAG) ?
1390
                0 : _PyUop_num_popped(base_opcode, inst->oparg);
1391
            if (target != current_error_target || popped != current_popped) {
1392
                current_popped = popped;
1393
                current_error = next_spare;
1394
                current_error_target = target;
1395
                make_exit(&buffer[next_spare], _ERROR_POP_N_r00, 0, false);
1396
                buffer[next_spare].operand0 = target;
1397
                next_spare++;
1398
            }
1399
            buffer[i].error_target = current_error;
1400
            if (buffer[i].format == UOP_FORMAT_TARGET) {
1401
                buffer[i].format = UOP_FORMAT_JUMP;
1402
                buffer[i].jump_target = 0;
1403
            }
1404
        }
1405
        if (base_opcode == _JUMP_TO_TOP) {
1406
            assert(_PyUop_Uncached[buffer[0].opcode] == _START_EXECUTOR);
1407
            buffer[i].format = UOP_FORMAT_JUMP;
1408
            buffer[i].jump_target = 1;
1409
        }
1410
    }
1411
    return next_spare;
1412
}
1413
1414
/* Executor side exits */
1415
1416
static _PyExecutorObject *
1417
allocate_executor(int exit_count, int length)
1418
{
1419
    int size = exit_count*sizeof(_PyExitData) + length*sizeof(_PyUOpInstruction);
1420
    _PyExecutorObject *res = PyObject_GC_NewVar(_PyExecutorObject, &_PyUOpExecutor_Type, size);
1421
    if (res == NULL) {
1422
        return NULL;
1423
    }
1424
    res->trace = (_PyUOpInstruction *)(res->exits + exit_count);
1425
    res->code_size = length;
1426
    res->exit_count = exit_count;
1427
    res->jit_registration = NULL;
1428
    return res;
1429
}
1430
1431
#ifdef Py_DEBUG
1432
1433
#define CHECK(PRED) \
1434
if (!(PRED)) { \
1435
    printf(#PRED " at %d\n", i); \
1436
    assert(0); \
1437
}
1438
1439
static int
1440
target_unused(int opcode)
1441
{
1442
    return (_PyUop_Flags[opcode] & (HAS_ERROR_FLAG | HAS_EXIT_FLAG | HAS_DEOPT_FLAG)) == 0;
1443
}
1444
1445
static void
1446
sanity_check(_PyExecutorObject *executor)
1447
{
1448
    for (uint32_t i = 0; i < executor->exit_count; i++) {
1449
        _PyExitData *exit = &executor->exits[i];
1450
        CHECK(exit->target < (1 << 25));
1451
    }
1452
    bool ended = false;
1453
    uint32_t i = 0;
1454
    CHECK(_PyUop_Uncached[executor->trace[0].opcode] == _START_EXECUTOR ||
1455
        _PyUop_Uncached[executor->trace[0].opcode] == _COLD_EXIT ||
1456
        _PyUop_Uncached[executor->trace[0].opcode] == _COLD_DYNAMIC_EXIT);
1457
    for (; i < executor->code_size; i++) {
1458
        const _PyUOpInstruction *inst = &executor->trace[i];
1459
        uint16_t opcode = inst->opcode;
1460
        uint16_t base_opcode = _PyUop_Uncached[opcode];
1461
        CHECK(opcode > MAX_UOP_ID);
1462
        CHECK(opcode <= MAX_UOP_REGS_ID);
1463
        CHECK(base_opcode <= MAX_UOP_ID);
1464
        CHECK(base_opcode != 0);
1465
        switch(inst->format) {
1466
            case UOP_FORMAT_TARGET:
1467
                CHECK(target_unused(base_opcode));
1468
                break;
1469
            case UOP_FORMAT_JUMP:
1470
                CHECK(inst->jump_target < executor->code_size);
1471
                break;
1472
        }
1473
        if (_PyUop_Flags[base_opcode] & HAS_ERROR_FLAG) {
1474
            CHECK(inst->format == UOP_FORMAT_JUMP);
1475
            CHECK(inst->error_target < executor->code_size);
1476
        }
1477
        if (is_terminator(inst)) {
1478
            ended = true;
1479
            i++;
1480
            break;
1481
        }
1482
    }
1483
    CHECK(ended);
1484
    for (; i < executor->code_size; i++) {
1485
        const _PyUOpInstruction *inst = &executor->trace[i];
1486
        uint16_t base_opcode = _PyUop_Uncached[inst->opcode];
1487
        CHECK(
1488
            base_opcode == _DEOPT ||
1489
            base_opcode == _HANDLE_PENDING_AND_DEOPT ||
1490
            base_opcode == _EXIT_TRACE ||
1491
            base_opcode == _ERROR_POP_N ||
1492
            base_opcode == _DYNAMIC_EXIT);
1493
    }
1494
}
1495
1496
#undef CHECK
1497
#endif
1498
1499
/* Makes an executor from a buffer of uops.
1500
 * Account for the buffer having gaps and NOPs by computing a "used"
1501
 * bit vector and only copying the used uops. Here "used" means reachable
1502
 * and not a NOP.
1503
 */
1504
static _PyExecutorObject *
1505
make_executor_from_uops(_PyThreadStateImpl *tstate, _PyUOpInstruction *buffer, int length, const _PyBloomFilter *dependencies)
1506
{
1507
    int exit_count = count_exits(buffer, length);
1508
    _PyExecutorObject *executor = allocate_executor(exit_count, length);
1509
    if (executor == NULL) {
1510
        return NULL;
1511
    }
1512
1513
    /* Initialize exits */
1514
    int chain_depth = tstate->jit_tracer_state->initial_state.chain_depth;
1515
    _PyExecutorObject *cold = _PyExecutor_GetColdExecutor();
1516
    _PyExecutorObject *cold_dynamic = _PyExecutor_GetColdDynamicExecutor();
1517
    cold->vm_data.chain_depth = chain_depth;
1518
    PyInterpreterState *interp = tstate->base.interp;
1519
    for (int i = 0; i < exit_count; i++) {
1520
        executor->exits[i].index = i;
1521
        executor->exits[i].temperature = initial_temperature_backoff_counter(&interp->opt_config);
1522
    }
1523
    int next_exit = exit_count-1;
1524
    _PyUOpInstruction *dest = (_PyUOpInstruction *)&executor->trace[length];
1525
    assert(_PyUop_Uncached[buffer[0].opcode] == _START_EXECUTOR);
1526
    buffer[0].operand0 = (uint64_t)executor;
1527
    for (int i = length-1; i >= 0; i--) {
1528
        uint16_t base_opcode = _PyUop_Uncached[buffer[i].opcode];
1529
        dest--;
1530
        *dest = buffer[i];
1531
        if (base_opcode == _EXIT_TRACE || base_opcode == _DYNAMIC_EXIT) {
1532
            _PyExitData *exit = &executor->exits[next_exit];
1533
            exit->target = buffer[i].target;
1534
            dest->operand0 = (uint64_t)exit;
1535
            exit->executor = base_opcode == _EXIT_TRACE ? cold : cold_dynamic;
1536
            exit->is_dynamic = (char)(base_opcode == _DYNAMIC_EXIT);
1537
            exit->is_control_flow = (char)buffer[i].operand1;
1538
            next_exit--;
1539
        }
1540
    }
1541
    assert(next_exit == -1);
1542
    assert(dest == executor->trace);
1543
    assert(_PyUop_Uncached[dest->opcode] == _START_EXECUTOR);
1544
    // Note: we MUST track it here before any Py_DECREF(executor) or
1545
    // linking of executor. Otherwise, the GC tries to untrack a
1546
    // still untracked object during dealloc.
1547
    _PyObject_GC_TRACK(executor);
1548
    if (_Py_ExecutorInit(executor, dependencies) < 0) {
1549
        Py_DECREF(executor);
1550
        return NULL;
1551
    }
1552
#ifdef Py_DEBUG
1553
    char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
1554
    int lltrace = 0;
1555
    if (python_lltrace != NULL && *python_lltrace >= '0') {
1556
        lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
1557
    }
1558
    if (lltrace >= 2) {
1559
        printf("Optimized trace (length %d):\n", length);
1560
        for (int i = 0; i < length; i++) {
1561
            printf("%4d OPTIMIZED: ", i);
1562
            _PyUOpPrint(&executor->trace[i]);
1563
            printf("\n");
1564
        }
1565
    }
1566
    sanity_check(executor);
1567
#endif
1568
#ifdef _Py_JIT
1569
    executor->jit_code = NULL;
1570
    executor->jit_size = 0;
1571
    // This is initialized to false so we can prevent the executor
1572
    // from being immediately detected as cold and invalidated.
1573
    executor->vm_data.cold = false;
1574
    if (_PyJIT_Compile(executor, executor->trace, length)) {
1575
        Py_DECREF(executor);
1576
        return NULL;
1577
    }
1578
#endif
1579
    return executor;
1580
}
1581
1582
#ifdef Py_STATS
1583
/* Returns the effective trace length.
1584
 * Ignores NOPs and trailing exit and error handling.*/
1585
int effective_trace_length(_PyUOpInstruction *buffer, int length)
1586
{
1587
    int nop_count = 0;
1588
    for (int i = 0; i < length; i++) {
1589
        int opcode = buffer[i].opcode;
1590
        if (opcode == _NOP) {
1591
            nop_count++;
1592
        }
1593
        if (is_terminator(&buffer[i])) {
1594
            return i+1-nop_count;
1595
        }
1596
    }
1597
    Py_FatalError("No terminating instruction");
1598
    Py_UNREACHABLE();
1599
}
1600
#endif
1601
1602
1603
static int
1604
stack_allocate(_PyUOpInstruction *buffer, _PyUOpInstruction *output, int length)
1605
{
1606
    assert(buffer[0].opcode == _START_EXECUTOR);
1607
    /* The input buffer and output buffers will overlap.
1608
       Make sure that we can move instructions to the output
1609
       without overwriting the input. */
1610
    if (buffer == output) {
1611
        // This can only happen if optimizer has not been run
1612
        for (int i = 0; i < length; i++) {
1613
            buffer[i + UOP_MAX_TRACE_LENGTH] = buffer[i];
1614
        }
1615
        buffer += UOP_MAX_TRACE_LENGTH;
1616
    }
1617
    else {
1618
        assert(output + UOP_MAX_TRACE_LENGTH == buffer);
1619
    }
1620
    int depth = 0;
1621
    _PyUOpInstruction *write = output;
1622
    for (int i = 0; i < length; i++) {
1623
        int uop = buffer[i].opcode;
1624
        if (uop == _NOP) {
1625
            continue;
1626
        }
1627
        int new_depth = _PyUop_Caching[uop].best[depth];
1628
        if (new_depth != depth) {
1629
            write->opcode = _PyUop_SpillsAndReloads[depth][new_depth];
1630
            assert(write->opcode != 0);
1631
            write->format = UOP_FORMAT_TARGET;
1632
            write->oparg = 0;
1633
            write->target = 0;
1634
            write++;
1635
            depth = new_depth;
1636
        }
1637
        *write = buffer[i];
1638
        uint16_t new_opcode = _PyUop_Caching[uop].entries[depth].opcode;
1639
        assert(new_opcode != 0);
1640
        write->opcode = new_opcode;
1641
        write++;
1642
        depth = _PyUop_Caching[uop].entries[depth].output;
1643
    }
1644
    return (int)(write - output);
1645
}
1646
1647
static int
1648
uop_optimize(
1649
    _PyInterpreterFrame *frame,
1650
    PyThreadState *tstate,
1651
    _PyExecutorObject **exec_ptr,
1652
    bool progress_needed)
1653
{
1654
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1655
    assert(_tstate->jit_tracer_state != NULL);
1656
    _PyUOpInstruction *buffer = _tstate->jit_tracer_state->code_buffer.start;
1657
    OPT_STAT_INC(attempts);
1658
    bool is_noopt = !tstate->interp->opt_config.uops_optimize_enabled;
1659
    int curr_stackentries = _tstate->jit_tracer_state->initial_state.stack_depth;
1660
    int length = uop_buffer_length(&_tstate->jit_tracer_state->code_buffer);
1661
    if (length <= CODE_SIZE_NO_PROGRESS) {
1662
        return 0;
1663
    }
1664
    assert(length > 0);
1665
    assert(length < UOP_MAX_TRACE_LENGTH);
1666
    OPT_STAT_INC(traces_created);
1667
1668
    _PyBloomFilter dependencies;
1669
    _Py_BloomFilter_Init(&dependencies);
1670
    if (!is_noopt) {
1671
        _PyUOpInstruction *output = &_tstate->jit_tracer_state->uop_array[UOP_MAX_TRACE_LENGTH];
1672
        length = _Py_uop_analyze_and_optimize(
1673
            _tstate, buffer, length, curr_stackentries,
1674
            output, &dependencies);
1675
1676
        if (length <= 0) {
1677
            return length;
1678
        }
1679
        buffer = output;
1680
    }
1681
    assert(length < UOP_MAX_TRACE_LENGTH);
1682
    assert(length >= 1);
1683
    /* Fix up */
1684
    for (int pc = 0; pc < length; pc++) {
1685
        int opcode = buffer[pc].opcode;
1686
        int oparg = buffer[pc].oparg;
1687
        if (oparg < _PyUop_Replication[opcode].stop && oparg >= _PyUop_Replication[opcode].start) {
1688
            buffer[pc].opcode = opcode + oparg + 1 - _PyUop_Replication[opcode].start;
1689
            assert(strncmp(_PyOpcode_uop_name[buffer[pc].opcode], _PyOpcode_uop_name[opcode], strlen(_PyOpcode_uop_name[opcode])) == 0);
1690
        }
1691
        else if (_PyUop_Flags[opcode] & HAS_RECORDS_VALUE_FLAG) {
1692
            Py_XDECREF((PyObject *)(uintptr_t)buffer[pc].operand0);
1693
            buffer[pc].opcode = _NOP;
1694
        }
1695
        else if (is_terminator(&buffer[pc])) {
1696
            break;
1697
        }
1698
        assert(_PyOpcode_uop_name[buffer[pc].opcode]);
1699
    }
1700
    // We've cleaned up the references in the buffer, so discard the code buffer
1701
    // to avoid doing it again during tracer cleanup
1702
    _PyJitUopBuffer *code_buffer = &_tstate->jit_tracer_state->code_buffer;
1703
    code_buffer->next = code_buffer->start;
1704
1705
    OPT_HIST(effective_trace_length(buffer, length), optimized_trace_length_hist);
1706
    _PyUOpInstruction *output = &_tstate->jit_tracer_state->uop_array[0];
1707
    length = stack_allocate(buffer, output, length);
1708
    buffer = output;
1709
    length = prepare_for_execution(buffer, length);
1710
    assert(length <= UOP_MAX_TRACE_LENGTH);
1711
    _PyExecutorObject *executor = make_executor_from_uops(
1712
        _tstate, buffer, length, &dependencies);
1713
    if (executor == NULL) {
1714
        return -1;
1715
    }
1716
    assert(length <= UOP_MAX_TRACE_LENGTH);
1717
1718
    // Check executor coldness
1719
    // It's okay if this ends up going negative.
1720
    if (--tstate->interp->executor_creation_counter == 0) {
1721
        _Py_set_eval_breaker_bit(tstate, _PY_EVAL_JIT_INVALIDATE_COLD_BIT);
1722
    }
1723
1724
    *exec_ptr = executor;
1725
    return 1;
1726
}
1727
1728
1729
/*****************************************
1730
 *        Executor management
1731
 ****************************************/
1732
1733
static int
1734
link_executor(_PyExecutorObject *executor, const _PyBloomFilter *bloom)
1735
{
1736
    PyInterpreterState *interp = _PyInterpreterState_GET();
1737
    if (interp->executor_count == interp->executor_capacity) {
1738
        size_t new_cap = interp->executor_capacity ? interp->executor_capacity * 2 : 64;
1739
        _PyBloomFilter *new_blooms = PyMem_Realloc(
1740
            interp->executor_blooms, new_cap * sizeof(_PyBloomFilter));
1741
        if (new_blooms == NULL) {
1742
            return -1;
1743
        }
1744
        _PyExecutorObject **new_ptrs = PyMem_Realloc(
1745
            interp->executor_ptrs, new_cap * sizeof(_PyExecutorObject *));
1746
        if (new_ptrs == NULL) {
1747
            /* Revert blooms realloc — the old pointer may have been freed by
1748
             * a successful realloc, but new_blooms is the valid pointer. */
1749
            interp->executor_blooms = new_blooms;
1750
            return -1;
1751
        }
1752
        interp->executor_blooms = new_blooms;
1753
        interp->executor_ptrs = new_ptrs;
1754
        interp->executor_capacity = new_cap;
1755
    }
1756
    size_t idx = interp->executor_count++;
1757
    interp->executor_blooms[idx] = *bloom;
1758
    interp->executor_ptrs[idx] = executor;
1759
    executor->vm_data.bloom_array_idx = (int32_t)idx;
1760
    return 0;
1761
}
1762
1763
static void
1764
unlink_executor(_PyExecutorObject *executor)
1765
{
1766
    PyInterpreterState *interp = PyInterpreterState_Get();
1767
    int32_t idx = executor->vm_data.bloom_array_idx;
1768
    assert(idx >= 0 && (size_t)idx < interp->executor_count);
1769
    size_t last = --interp->executor_count;
1770
    if ((size_t)idx != last) {
1771
        /* Swap-remove: move the last element into the vacated slot */
1772
        interp->executor_blooms[idx] = interp->executor_blooms[last];
1773
        interp->executor_ptrs[idx] = interp->executor_ptrs[last];
1774
        interp->executor_ptrs[idx]->vm_data.bloom_array_idx = idx;
1775
    }
1776
    executor->vm_data.bloom_array_idx = -1;
1777
}
1778
1779
/* This must be called by optimizers before using the executor */
1780
int
1781
_Py_ExecutorInit(_PyExecutorObject *executor, const _PyBloomFilter *dependency_set)
1782
{
1783
    executor->vm_data.valid = true;
1784
    executor->vm_data.pending_deletion = 0;
1785
    executor->vm_data.code = NULL;
1786
    if (link_executor(executor, dependency_set) < 0) {
1787
        return -1;
1788
    }
1789
    return 0;
1790
}
1791
1792
static _PyExecutorObject *
1793
make_cold_executor(uint16_t opcode)
1794
{
1795
    _PyExecutorObject *cold = allocate_executor(0, 1);
1796
    if (cold == NULL) {
1797
        Py_FatalError("Cannot allocate core JIT code");
1798
    }
1799
    ((_PyUOpInstruction *)cold->trace)->opcode = opcode;
1800
    // This is initialized to false so we can prevent the executor
1801
    // from being immediately detected as cold and invalidated.
1802
    cold->vm_data.cold = false;
1803
#ifdef _Py_JIT
1804
    cold->jit_code = NULL;
1805
    cold->jit_size = 0;
1806
    if (_PyJIT_Compile(cold, cold->trace, 1)) {
1807
        Py_DECREF(cold);
1808
        Py_FatalError("Cannot allocate core JIT code");
1809
    }
1810
#endif
1811
    _Py_SetImmortal((PyObject *)cold);
1812
    return cold;
1813
}
1814
1815
_PyExecutorObject *
1816
_PyExecutor_GetColdExecutor(void)
1817
{
1818
    PyInterpreterState *interp = _PyInterpreterState_GET();
1819
    if (interp->cold_executor == NULL) {
1820
        return interp->cold_executor = make_cold_executor(_COLD_EXIT_r00);;
1821
    }
1822
    return interp->cold_executor;
1823
}
1824
1825
_PyExecutorObject *
1826
_PyExecutor_GetColdDynamicExecutor(void)
1827
{
1828
    PyInterpreterState *interp = _PyInterpreterState_GET();
1829
    if (interp->cold_dynamic_executor == NULL) {
1830
        interp->cold_dynamic_executor = make_cold_executor(_COLD_DYNAMIC_EXIT_r00);
1831
    }
1832
    return interp->cold_dynamic_executor;
1833
}
1834
1835
void
1836
_PyExecutor_ClearExit(_PyExitData *exit)
1837
{
1838
    if (exit == NULL) {
1839
        return;
1840
    }
1841
    _PyExecutorObject *old = exit->executor;
1842
    if (exit->is_dynamic) {
1843
        exit->executor = _PyExecutor_GetColdDynamicExecutor();
1844
    }
1845
    else {
1846
        exit->executor = _PyExecutor_GetColdExecutor();
1847
    }
1848
    Py_DECREF(old);
1849
}
1850
1851
/* Detaches the executor from the code object (if any) that
1852
 * holds a reference to it */
1853
void
1854
_Py_ExecutorDetach(_PyExecutorObject *executor)
1855
{
1856
    PyCodeObject *code = executor->vm_data.code;
1857
    if (code == NULL) {
1858
        return;
1859
    }
1860
    _Py_CODEUNIT *instruction = &_PyCode_CODE(code)[executor->vm_data.index];
1861
    assert(instruction->op.code == ENTER_EXECUTOR);
1862
    int index = instruction->op.arg;
1863
    assert(code->co_executors->executors[index] == executor);
1864
    instruction->op.code = _PyOpcode_Deopt[executor->vm_data.opcode];
1865
    instruction->op.arg = executor->vm_data.oparg;
1866
    executor->vm_data.code = NULL;
1867
    code->co_executors->executors[index] = NULL;
1868
    Py_DECREF(executor);
1869
}
1870
1871
/* Executors can be invalidated at any time,
1872
   even with a stop-the-world lock held.
1873
   Consequently it must not run arbitrary code,
1874
   including Py_DECREF with a non-executor. */
1875
static void
1876
executor_invalidate(PyObject *op)
1877
{
1878
    _PyExecutorObject *executor = _PyExecutorObject_CAST(op);
1879
    if (!executor->vm_data.valid) {
1880
        return;
1881
    }
1882
    executor->vm_data.valid = 0;
1883
    unlink_executor(executor);
1884
    executor_clear_exits(executor);
1885
    _Py_ExecutorDetach(executor);
1886
    _PyObject_GC_UNTRACK(op);
1887
}
1888
1889
static int
1890
executor_clear(PyObject *op)
1891
{
1892
    executor_invalidate(op);
1893
    return 0;
1894
}
1895
1896
void
1897
_Py_Executor_DependsOn(_PyExecutorObject *executor, void *obj)
1898
{
1899
    assert(executor->vm_data.valid);
1900
    PyInterpreterState *interp = _PyInterpreterState_GET();
1901
    int32_t idx = executor->vm_data.bloom_array_idx;
1902
    assert(idx >= 0 && (size_t)idx < interp->executor_count);
1903
    _Py_BloomFilter_Add(&interp->executor_blooms[idx], obj);
1904
}
1905
1906
/* Invalidate all executors that depend on `obj`
1907
 * May cause other executors to be invalidated as well.
1908
 * Uses contiguous bloom filter array for cache-friendly scanning.
1909
 */
1910
void
1911
_Py_Executors_InvalidateDependency(PyInterpreterState *interp, void *obj, int is_invalidation)
1912
{
1913
    _PyBloomFilter obj_filter;
1914
    _Py_BloomFilter_Init(&obj_filter);
1915
    _Py_BloomFilter_Add(&obj_filter, obj);
1916
    /* Scan contiguous bloom filter array */
1917
    PyObject *invalidate = PyList_New(0);
1918
    if (invalidate == NULL) {
1919
        goto error;
1920
    }
1921
    /* Clearing an executor can clear others, so we need to make a list of
1922
     * executors to invalidate first */
1923
    for (size_t i = 0; i < interp->executor_count; i++) {
1924
        assert(interp->executor_ptrs[i]->vm_data.valid);
1925
        if (bloom_filter_may_contain(&interp->executor_blooms[i], &obj_filter) &&
1926
            PyList_Append(invalidate, (PyObject *)interp->executor_ptrs[i]))
1927
        {
1928
            goto error;
1929
        }
1930
    }
1931
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(invalidate); i++) {
1932
        PyObject *exec = PyList_GET_ITEM(invalidate, i);
1933
        executor_invalidate(exec);
1934
        if (is_invalidation) {
1935
            OPT_STAT_INC(executors_invalidated);
1936
        }
1937
    }
1938
    Py_DECREF(invalidate);
1939
    return;
1940
error:
1941
    PyErr_Clear();
1942
    Py_XDECREF(invalidate);
1943
    // If we're truly out of memory, wiping out everything is a fine fallback:
1944
    _Py_Executors_InvalidateAll(interp, is_invalidation);
1945
}
1946
1947
/* Invalidate all executors */
1948
void
1949
_Py_Executors_InvalidateAll(PyInterpreterState *interp, int is_invalidation)
1950
{
1951
    while (interp->executor_count > 0) {
1952
        /* Invalidate from the end to avoid repeated swap-remove shifts */
1953
        _PyExecutorObject *executor = interp->executor_ptrs[interp->executor_count - 1];
1954
        assert(executor->vm_data.valid);
1955
        if (executor->vm_data.code) {
1956
            // Clear the entire code object so its co_executors array be freed:
1957
            _PyCode_Clear_Executors(executor->vm_data.code);
1958
        }
1959
        else {
1960
            executor_invalidate((PyObject *)executor);
1961
        }
1962
        if (is_invalidation) {
1963
            OPT_STAT_INC(executors_invalidated);
1964
        }
1965
    }
1966
}
1967
1968
void
1969
_Py_Executors_InvalidateCold(PyInterpreterState *interp)
1970
{
1971
    /* Scan contiguous executor array */
1972
    PyObject *invalidate = PyList_New(0);
1973
    if (invalidate == NULL) {
1974
        goto error;
1975
    }
1976
1977
    /* Clearing an executor can deallocate others, so we need to make a list of
1978
     * executors to invalidate first */
1979
    for (size_t i = 0; i < interp->executor_count; i++) {
1980
        _PyExecutorObject *exec = interp->executor_ptrs[i];
1981
        assert(exec->vm_data.valid);
1982
1983
        if (exec->vm_data.cold && PyList_Append(invalidate, (PyObject *)exec) < 0) {
1984
            goto error;
1985
        }
1986
        else {
1987
            exec->vm_data.cold = true;
1988
        }
1989
    }
1990
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(invalidate); i++) {
1991
        PyObject *exec = PyList_GET_ITEM(invalidate, i);
1992
        executor_invalidate(exec);
1993
    }
1994
    Py_DECREF(invalidate);
1995
    return;
1996
error:
1997
    PyErr_Clear();
1998
    Py_XDECREF(invalidate);
1999
    // If we're truly out of memory, wiping out everything is a fine fallback
2000
    _Py_Executors_InvalidateAll(interp, 0);
2001
}
2002
2003
#include "record_functions.c.h"
2004
2005
static int
2006
escape_angles(const char *input, Py_ssize_t size, char *buffer) {
2007
    int written = 0;
2008
    for (Py_ssize_t i = 0; i < size; i++) {
2009
        char c = input[i];
2010
        if (c == '<' || c == '>') {
2011
            buffer[written++] = '&';
2012
            buffer[written++] = c == '>' ? 'g' : 'l';
2013
            buffer[written++] = 't';
2014
            buffer[written++] = ';';
2015
        }
2016
        else {
2017
            buffer[written++] = c;
2018
        }
2019
    }
2020
    return written;
2021
}
2022
2023
static void
2024
write_str(PyObject *str, FILE *out)
2025
{
2026
    // Encode the Unicode object to the specified encoding
2027
    PyObject *encoded_obj = PyUnicode_AsEncodedString(str, "utf8", "strict");
2028
    if (encoded_obj == NULL) {
2029
        PyErr_Clear();
2030
        return;
2031
    }
2032
    const char *encoded_str = PyBytes_AsString(encoded_obj);
2033
    Py_ssize_t encoded_size = PyBytes_Size(encoded_obj);
2034
    char buffer[120];
2035
    bool truncated = false;
2036
    if (encoded_size > 24) {
2037
        encoded_size = 24;
2038
        truncated = true;
2039
    }
2040
    int size = escape_angles(encoded_str, encoded_size, buffer);
2041
    fwrite(buffer, 1, size, out);
2042
    if (truncated) {
2043
        fwrite("...", 1, 3, out);
2044
    }
2045
    Py_DECREF(encoded_obj);
2046
}
2047
2048
static int
2049
find_line_number(PyCodeObject *code, _PyExecutorObject *executor)
2050
{
2051
    int code_len = (int)Py_SIZE(code);
2052
    for (int i = 0; i < code_len; i++) {
2053
        _Py_CODEUNIT *instr = &_PyCode_CODE(code)[i];
2054
        int opcode = instr->op.code;
2055
        if (opcode == ENTER_EXECUTOR) {
2056
            _PyExecutorObject *exec = code->co_executors->executors[instr->op.arg];
2057
            if (exec == executor) {
2058
                return PyCode_Addr2Line(code, i*2);
2059
            }
2060
        }
2061
        i += _PyOpcode_Caches[_Py_GetBaseCodeUnit(code, i).op.code];
2062
    }
2063
    return -1;
2064
}
2065
2066
#define RED "#ff0000"
2067
#define WHITE "#ffffff"
2068
#define BLUE "#0000ff"
2069
#define BLACK "#000000"
2070
#define LOOP "#00c000"
2071
2072
#ifdef Py_STATS
2073
2074
static const char *COLORS[10] = {
2075
    "9",
2076
    "8",
2077
    "7",
2078
    "6",
2079
    "5",
2080
    "4",
2081
    "3",
2082
    "2",
2083
    "1",
2084
    WHITE,
2085
};
2086
const char *
2087
get_background_color(_PyUOpInstruction const *inst, uint64_t max_hotness)
2088
{
2089
    uint64_t hotness = inst->execution_count;
2090
    int index = (hotness * 10)/max_hotness;
2091
    if (index > 9) {
2092
        index = 9;
2093
    }
2094
    if (index < 0) {
2095
        index = 0;
2096
    }
2097
    return COLORS[index];
2098
}
2099
2100
const char *
2101
get_foreground_color(_PyUOpInstruction const *inst, uint64_t max_hotness)
2102
{
2103
    if(_PyUop_Uncached[inst->opcode] == _DEOPT) {
2104
        return RED;
2105
    }
2106
    uint64_t hotness = inst->execution_count;
2107
    int index = (hotness * 10)/max_hotness;
2108
    if (index > 3) {
2109
        return BLACK;
2110
    }
2111
    return WHITE;
2112
}
2113
#endif
2114
2115
static void
2116
write_row_for_uop(_PyExecutorObject *executor, uint32_t i, FILE *out)
2117
{
2118
    /* Write row for uop.
2119
        * The `port` is a marker so that outgoing edges can
2120
        * be placed correctly. If a row is marked `port=17`,
2121
        * then the outgoing edge is `{EXEC_NAME}:17 -> {TARGET}`
2122
        * https://graphviz.readthedocs.io/en/stable/manual.html#node-ports-compass
2123
        */
2124
    _PyUOpInstruction const *inst = &executor->trace[i];
2125
    const char *opname = _PyOpcode_uop_name[inst->opcode];
2126
#ifdef Py_STATS
2127
    const char *bg_color = get_background_color(inst, executor->trace[0].execution_count);
2128
    const char *color = get_foreground_color(inst, executor->trace[0].execution_count);
2129
    fprintf(out, "        <tr><td port=\"i%d\" border=\"1\" color=\"%s\" bgcolor=\"%s\" ><font color=\"%s\"> %s [%d]&nbsp;--&nbsp; %" PRIu64 "</font></td></tr>\n",
2130
        i, color, bg_color, color, opname, inst->fitness, inst->execution_count);
2131
#else
2132
    const char *color = (_PyUop_Uncached[inst->opcode] == _DEOPT) ? RED : BLACK;
2133
    fprintf(out, "        <tr><td port=\"i%d\" border=\"1\" color=\"%s\" >%s op0=%" PRIu64 "</td></tr>\n", i, color, opname, inst->operand0);
2134
#endif
2135
}
2136
2137
static bool
2138
is_stop(_PyUOpInstruction const *inst)
2139
{
2140
    uint16_t base_opcode = _PyUop_Uncached[inst->opcode];
2141
    return (base_opcode == _EXIT_TRACE || base_opcode == _DEOPT || base_opcode == _JUMP_TO_TOP);
2142
}
2143
2144
2145
/* Writes the node and outgoing edges for a single tracelet in graphviz format.
2146
 * Each tracelet is presented as a table of the uops it contains.
2147
 * If Py_STATS is enabled, execution counts are included.
2148
 *
2149
 * https://graphviz.readthedocs.io/en/stable/manual.html
2150
 * https://graphviz.org/gallery/
2151
 */
2152
static void
2153
executor_to_gv(_PyExecutorObject *executor, FILE *out)
2154
{
2155
    PyCodeObject *code = executor->vm_data.code;
2156
    fprintf(out, "executor_%p [\n", executor);
2157
    fprintf(out, "    shape = none\n");
2158
2159
    /* Write the HTML table for the uops */
2160
    fprintf(out, "    label = <<table border=\"0\" cellspacing=\"0\">\n");
2161
    fprintf(out, "        <tr><td port=\"start\" border=\"1\" ><b>Executor</b></td></tr>\n");
2162
    if (code == NULL) {
2163
        fprintf(out, "        <tr><td border=\"1\" >No code object</td></tr>\n");
2164
    }
2165
    else {
2166
        fprintf(out, "        <tr><td  border=\"1\" >");
2167
        write_str(code->co_qualname, out);
2168
        int line = find_line_number(code, executor);
2169
        fprintf(out, ": %d</td></tr>\n", line);
2170
    }
2171
    for (uint32_t i = 0; i < executor->code_size; i++) {
2172
        write_row_for_uop(executor, i, out);
2173
        if (is_stop(&executor->trace[i])) {
2174
            break;
2175
        }
2176
    }
2177
    fprintf(out, "    </table>>\n");
2178
    fprintf(out, "]\n\n");
2179
2180
    /* Write all the outgoing edges */
2181
    _PyExecutorObject *cold = _PyExecutor_GetColdExecutor();
2182
    _PyExecutorObject *cold_dynamic = _PyExecutor_GetColdDynamicExecutor();
2183
    for (uint32_t i = 0; i < executor->code_size; i++) {
2184
        _PyUOpInstruction const *inst = &executor->trace[i];
2185
        uint16_t base_opcode = _PyUop_Uncached[inst->opcode];
2186
        uint16_t flags = _PyUop_Flags[base_opcode];
2187
        _PyExitData *exit = NULL;
2188
        if (base_opcode == _JUMP_TO_TOP) {
2189
            fprintf(out, "executor_%p:i%d -> executor_%p:i%d [color = \"" LOOP "\"]\n", executor, i, executor, inst->jump_target);
2190
            break;
2191
        }
2192
        if (base_opcode == _EXIT_TRACE) {
2193
            exit = (_PyExitData *)inst->operand0;
2194
        }
2195
        else if (flags & HAS_EXIT_FLAG) {
2196
            assert(inst->format == UOP_FORMAT_JUMP);
2197
            _PyUOpInstruction const *exit_inst = &executor->trace[inst->jump_target];
2198
            uint16_t base_exit_opcode = _PyUop_Uncached[exit_inst->opcode];
2199
            (void)base_exit_opcode;
2200
            assert(base_exit_opcode == _EXIT_TRACE || base_exit_opcode == _DYNAMIC_EXIT);
2201
            exit = (_PyExitData *)exit_inst->operand0;
2202
        }
2203
        if (exit != NULL) {
2204
            if (exit->executor == cold || exit->executor == cold_dynamic) {
2205
#ifdef Py_STATS
2206
                /* Only mark as have cold exit if it has actually exited */
2207
                uint64_t diff = inst->execution_count - executor->trace[i+1].execution_count;
2208
                if (diff) {
2209
                    fprintf(out, "cold_%p%d [ label = \"%"  PRIu64  "\" shape = ellipse color=\"" BLUE "\" ]\n", executor, i, diff);
2210
                    fprintf(out, "executor_%p:i%d -> cold_%p%d\n", executor, i, executor, i);
2211
                }
2212
#endif
2213
            }
2214
            else {
2215
                fprintf(out, "executor_%p:i%d -> executor_%p:start\n", executor, i, exit->executor);
2216
            }
2217
        }
2218
        if (is_stop(inst)) {
2219
            break;
2220
        }
2221
    }
2222
}
2223
2224
/* Write the graph of all the live tracelets in graphviz format. */
2225
int
2226
_PyDumpExecutors(FILE *out)
2227
{
2228
    fprintf(out, "digraph ideal {\n\n");
2229
    fprintf(out, "    rankdir = \"LR\"\n\n");
2230
    fprintf(out, "    node [colorscheme=greys9]\n");
2231
    PyInterpreterState *interp = PyInterpreterState_Get();
2232
    for (size_t i = 0; i < interp->executor_count; i++) {
2233
        executor_to_gv(interp->executor_ptrs[i], out);
2234
    }
2235
    fprintf(out, "}\n\n");
2236
    return 0;
2237
}
2238
2239
#else
2240
2241
int
2242
_PyDumpExecutors(FILE *out)
2243
0
{
2244
0
    PyErr_SetString(PyExc_NotImplementedError, "No JIT available");
2245
0
    return -1;
2246
0
}
2247
2248
void
2249
_PyExecutor_Free(struct _PyExecutorObject *self)
2250
0
{
2251
    /* This should never be called */
2252
0
    Py_UNREACHABLE();
2253
0
}
2254
2255
#endif /* _Py_TIER2 */