Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/flowgraph.c
Line
Count
Source
1
#include "Python.h"
2
#include "opcode.h"
3
#include "pycore_c_array.h"       // _Py_CArray_EnsureCapacity
4
#include "pycore_flowgraph.h"
5
#include "pycore_compile.h"
6
#include "pycore_intrinsics.h"
7
#include "pycore_pymem.h"         // _PyMem_IsPtrFreed()
8
#include "pycore_long.h"          // _PY_IS_SMALL_INT()
9
#include "pycore_hashtable.h"     // _Py_hashtable_t
10
11
#include "pycore_opcode_utils.h"
12
#include "pycore_opcode_metadata.h" // OPCODE_HAS_ARG, etc
13
#include "pycore_pystate.h"         // _PyInterpreterState_GET()
14
#include "pycore_stackref.h"        // PyStackRef_AsPyObjectBorrow()
15
16
#include <stdbool.h>
17
18
19
#undef SUCCESS
20
#undef ERROR
21
473k
#define SUCCESS 0
22
3.84k
#define ERROR -1
23
24
#define RETURN_IF_ERROR(X)  \
25
696k
    if ((X) == -1) {        \
26
0
        return ERROR;       \
27
0
    }
28
29
152k
#define DEFAULT_BLOCK_SIZE 16
30
31
typedef _Py_SourceLocation location;
32
typedef _PyJumpTargetLabel jump_target_label;
33
34
typedef struct _PyCfgInstruction {
35
    int i_opcode;
36
    int i_oparg;
37
    _Py_SourceLocation i_loc;
38
    struct _PyCfgBasicblock *i_target; /* target block (if jump instruction) */
39
    struct _PyCfgBasicblock *i_except; /* target block when exception is raised */
40
} cfg_instr;
41
42
typedef struct _PyCfgBasicblock {
43
    /* Each basicblock in a compilation unit is linked via b_list in the
44
       reverse order that blocks are allocated.  b_list points to the
45
       previously allocated block, not to be confused with b_next, which is
46
       next by control flow. */
47
    struct _PyCfgBasicblock *b_list;
48
    /* The label of this block if it is a jump target, -1 otherwise */
49
    _PyJumpTargetLabel b_label;
50
    /* Basic block is an exception handler that preserves lasti */
51
    unsigned b_preserve_lasti : 1;
52
    /* Used by compiler passes to mark whether they have visited a basic block. */
53
    unsigned b_visited : 1;
54
    /* b_except_handler is used by the cold-detection algorithm to mark exception targets */
55
    unsigned b_except_handler : 1;
56
    /* b_cold is true if this block is not perf critical (like an exception handler) */
57
    unsigned b_cold : 1;
58
    /* b_warm is used by the cold-detection algorithm to mark blocks which are definitely not cold */
59
    unsigned b_warm : 1;
60
    /* Exception stack at start of block, used by assembler to create the exception handling table */
61
    struct _PyCfgExceptStack *b_exceptstack;
62
    /* pointer to an array of instructions, initially NULL */
63
    cfg_instr *b_instr;
64
    /* If b_next is non-NULL, it is a pointer to the next
65
       block reached by normal control flow. */
66
    struct _PyCfgBasicblock *b_next;
67
    /* number of instructions used */
68
    int b_iused;
69
    /* length of instruction array (b_instr) */
70
    int b_ialloc;
71
    /* Used by add_checks_for_loads_of_unknown_variables */
72
    uint64_t b_unsafe_locals_mask;
73
    /* Number of predecessors that a block has. */
74
    int b_predecessors;
75
    /* depth of stack upon entry of block, computed by stackdepth() */
76
    int b_startdepth;
77
} basicblock;
78
79
80
struct _PyCfgBuilder {
81
    /* The entryblock, at which control flow begins. All blocks of the
82
       CFG are reachable through the b_next links */
83
    struct _PyCfgBasicblock *g_entryblock;
84
    /* Pointer to the most recently allocated block.  By following
85
       b_list links, you can reach all allocated blocks. */
86
    struct _PyCfgBasicblock *g_block_list;
87
    /* pointer to the block currently being constructed */
88
    struct _PyCfgBasicblock *g_curblock;
89
    /* label for the next instruction to be placed */
90
    _PyJumpTargetLabel g_current_label;
91
};
92
93
typedef struct _PyCfgBuilder cfg_builder;
94
95
154k
#define SAME_LABEL(L1, L2) ((L1).id == (L2).id)
96
154k
#define IS_LABEL(L) (!SAME_LABEL((L), (NO_LABEL)))
97
98
#define LOCATION(LNO, END_LNO, COL, END_COL) \
99
    ((const _Py_SourceLocation){(LNO), (END_LNO), (COL), (END_COL)})
100
101
static inline int
102
is_block_push(cfg_instr *i)
103
684k
{
104
684k
    assert(OPCODE_HAS_ARG(i->i_opcode) || !IS_BLOCK_PUSH_OPCODE(i->i_opcode));
105
684k
    return IS_BLOCK_PUSH_OPCODE(i->i_opcode);
106
684k
}
107
108
static inline int
109
is_jump(cfg_instr *i)
110
569k
{
111
569k
    return OPCODE_HAS_JUMP(i->i_opcode);
112
569k
}
113
114
/* One arg*/
115
#define INSTR_SET_OP1(I, OP, ARG) \
116
27.1k
    do { \
117
27.1k
        assert(OPCODE_HAS_ARG(OP)); \
118
27.1k
        cfg_instr *_instr__ptr_ = (I); \
119
27.1k
        _instr__ptr_->i_opcode = (OP); \
120
27.1k
        _instr__ptr_->i_oparg = (ARG); \
121
27.1k
    } while (0);
122
123
/* No args*/
124
#define INSTR_SET_OP0(I, OP) \
125
25.2k
    do { \
126
25.2k
        assert(!OPCODE_HAS_ARG(OP)); \
127
25.2k
        cfg_instr *_instr__ptr_ = (I); \
128
25.2k
        _instr__ptr_->i_opcode = (OP); \
129
25.2k
        _instr__ptr_->i_oparg = 0; \
130
25.2k
    } while (0);
131
132
#define INSTR_SET_LOC(I, LOC) \
133
3.55k
    do { \
134
3.55k
        cfg_instr *_instr__ptr_ = (I); \
135
3.55k
        _instr__ptr_->i_loc = (LOC); \
136
3.55k
    } while (0);
137
138
/***** Blocks *****/
139
140
/* Returns the offset of the next instruction in the current block's
141
   b_instr array.  Resizes the b_instr as necessary.
142
   Returns -1 on failure.
143
*/
144
static int
145
basicblock_next_instr(basicblock *b)
146
152k
{
147
152k
    assert(b != NULL);
148
152k
    _Py_c_array_t array = {
149
152k
        .array = (void*)b->b_instr,
150
152k
        .allocated_entries = b->b_ialloc,
151
152k
        .item_size = sizeof(cfg_instr),
152
152k
        .initial_num_entries = DEFAULT_BLOCK_SIZE,
153
152k
    };
154
155
152k
    RETURN_IF_ERROR(_Py_CArray_EnsureCapacity(&array, b->b_iused + 1));
156
152k
    b->b_instr = array.array;
157
152k
    b->b_ialloc = array.allocated_entries;
158
152k
    return b->b_iused++;
159
152k
}
160
161
static cfg_instr *
162
432k
basicblock_last_instr(const basicblock *b) {
163
432k
    assert(b->b_iused >= 0);
164
432k
    if (b->b_iused > 0) {
165
392k
        assert(b->b_instr != NULL);
166
392k
        return &b->b_instr[b->b_iused - 1];
167
392k
    }
168
40.0k
    return NULL;
169
432k
}
170
171
/* Allocate a new block and return a pointer to it.
172
   Returns NULL on error.
173
*/
174
175
static basicblock *
176
cfg_builder_new_block(cfg_builder *g)
177
13.6k
{
178
13.6k
    basicblock *b = (basicblock *)PyMem_Calloc(1, sizeof(basicblock));
179
13.6k
    if (b == NULL) {
180
0
        PyErr_NoMemory();
181
0
        return NULL;
182
0
    }
183
    /* Extend the singly linked list of blocks with new block. */
184
13.6k
    b->b_list = g->g_block_list;
185
13.6k
    g->g_block_list = b;
186
13.6k
    b->b_label = NO_LABEL;
187
13.6k
    return b;
188
13.6k
}
189
190
static int
191
basicblock_addop(basicblock *b, int opcode, int oparg, location loc,
192
                 basicblock *except)
193
148k
{
194
148k
    assert(IS_WITHIN_OPCODE_RANGE(opcode));
195
148k
    assert(!IS_ASSEMBLER_OPCODE(opcode));
196
148k
    assert(OPCODE_HAS_ARG(opcode) || HAS_TARGET(opcode) || oparg == 0);
197
148k
    assert(0 <= oparg && oparg < (1 << 30));
198
199
148k
    int off = basicblock_next_instr(b);
200
148k
    if (off < 0) {
201
0
        return ERROR;
202
0
    }
203
148k
    cfg_instr *i = &b->b_instr[off];
204
148k
    i->i_opcode = opcode;
205
148k
    i->i_oparg = oparg;
206
148k
    i->i_loc = loc;
207
148k
    i->i_except = except;
208
    // memory is already zero initialized
209
148k
    assert(i->i_target == NULL);
210
211
148k
    return SUCCESS;
212
148k
}
213
214
static int
215
basicblock_add_jump(basicblock *b, int opcode, basicblock *target, location loc,
216
                    basicblock *except)
217
212
{
218
212
    cfg_instr *last = basicblock_last_instr(b);
219
212
    if (last && is_jump(last)) {
220
0
        return ERROR;
221
0
    }
222
223
212
    RETURN_IF_ERROR(
224
212
        basicblock_addop(b, opcode, target->b_label.id, loc, except));
225
212
    last = basicblock_last_instr(b);
226
212
    assert(last && last->i_opcode == opcode);
227
212
    last->i_target = target;
228
212
    return SUCCESS;
229
212
}
230
231
static inline int
232
basicblock_append_instructions(basicblock *to, basicblock *from)
233
787
{
234
2.21k
    for (int i = 0; i < from->b_iused; i++) {
235
1.43k
        int n = basicblock_next_instr(to);
236
1.43k
        if (n < 0) {
237
0
            return ERROR;
238
0
        }
239
1.43k
        to->b_instr[n] = from->b_instr[i];
240
1.43k
    }
241
787
    return SUCCESS;
242
787
}
243
244
static inline int
245
124k
basicblock_nofallthrough(const basicblock *b) {
246
124k
    cfg_instr *last = basicblock_last_instr(b);
247
124k
    return (last &&
248
115k
            (IS_SCOPE_EXIT_OPCODE(last->i_opcode) ||
249
57.6k
             IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)));
250
124k
}
251
252
#define BB_NO_FALLTHROUGH(B) (basicblock_nofallthrough(B))
253
204k
#define BB_HAS_FALLTHROUGH(B) (!basicblock_nofallthrough(B))
254
255
static basicblock *
256
copy_basicblock(cfg_builder *g, basicblock *block)
257
177
{
258
    /* Cannot copy a block if it has a fallthrough, since
259
     * a block can only have one fallthrough predecessor.
260
     */
261
177
    assert(BB_NO_FALLTHROUGH(block));
262
177
    basicblock *result = cfg_builder_new_block(g);
263
177
    if (result == NULL) {
264
0
        return NULL;
265
0
    }
266
177
    if (basicblock_append_instructions(result, block) < 0) {
267
0
        return NULL;
268
0
    }
269
177
    return result;
270
177
}
271
272
static int
273
2.32k
basicblock_insert_instruction(basicblock *block, int pos, cfg_instr *instr) {
274
2.32k
    RETURN_IF_ERROR(basicblock_next_instr(block));
275
34.9k
    for (int i = block->b_iused - 1; i > pos; i--) {
276
32.6k
        block->b_instr[i] = block->b_instr[i-1];
277
32.6k
    }
278
2.32k
    block->b_instr[pos] = *instr;
279
2.32k
    return SUCCESS;
280
2.32k
}
281
282
/* For debugging purposes only */
283
#if 0
284
static void
285
dump_instr(cfg_instr *i)
286
{
287
    const char *jump = is_jump(i) ? "jump " : "";
288
289
    char arg[128];
290
291
    *arg = '\0';
292
    if (OPCODE_HAS_ARG(i->i_opcode)) {
293
        sprintf(arg, "arg: %d ", i->i_oparg);
294
    }
295
    if (HAS_TARGET(i->i_opcode)) {
296
        sprintf(arg, "target: %p [%d] ", i->i_target, i->i_oparg);
297
    }
298
    fprintf(stderr, "line: %d, %s (%d)  %s%s\n",
299
                    i->i_loc.lineno, _PyOpcode_OpName[i->i_opcode], i->i_opcode, arg, jump);
300
}
301
302
static inline int
303
basicblock_returns(const basicblock *b) {
304
    cfg_instr *last = basicblock_last_instr(b);
305
    return last && IS_RETURN_OPCODE(last->i_opcode);
306
}
307
308
static void
309
dump_basicblock(const basicblock *b, bool highlight)
310
{
311
    const char *b_return = basicblock_returns(b) ? "return " : "";
312
    if (highlight) {
313
        fprintf(stderr, ">>> ");
314
    }
315
    fprintf(stderr, "%d: [EH=%d CLD=%d WRM=%d NO_FT=%d %p] used: %d, depth: %d, preds: %d %s\n",
316
        b->b_label.id, b->b_except_handler, b->b_cold, b->b_warm, BB_NO_FALLTHROUGH(b), b, b->b_iused,
317
        b->b_startdepth, b->b_predecessors, b_return);
318
    int depth = b->b_startdepth;
319
    if (b->b_instr) {
320
        int i;
321
        for (i = 0; i < b->b_iused; i++) {
322
            fprintf(stderr, "  [%02d] depth: %d ", i, depth);
323
            dump_instr(b->b_instr + i);
324
325
            int popped = _PyOpcode_num_popped(b->b_instr[i].i_opcode, b->b_instr[i].i_oparg);
326
            int pushed = _PyOpcode_num_pushed(b->b_instr[i].i_opcode, b->b_instr[i].i_oparg);
327
            depth += (pushed - popped);
328
        }
329
    }
330
}
331
332
void
333
_PyCfgBuilder_DumpGraph(const basicblock *entryblock, const basicblock *mark)
334
{
335
    for (const basicblock *b = entryblock; b != NULL; b = b->b_next) {
336
        dump_basicblock(b, b == mark);
337
    }
338
}
339
340
#endif
341
342
343
/***** CFG construction and modification *****/
344
345
static basicblock *
346
cfg_builder_use_next_block(cfg_builder *g, basicblock *block)
347
9.53k
{
348
9.53k
    assert(block != NULL);
349
9.53k
    g->g_curblock->b_next = block;
350
9.53k
    g->g_curblock = block;
351
9.53k
    return block;
352
9.53k
}
353
354
static inline int
355
18.1k
basicblock_exits_scope(const basicblock *b) {
356
18.1k
    cfg_instr *last = basicblock_last_instr(b);
357
18.1k
    return last && IS_SCOPE_EXIT_OPCODE(last->i_opcode);
358
18.1k
}
359
360
static inline int
361
9.94k
basicblock_has_eval_break(const basicblock *b) {
362
54.2k
    for (int i = 0; i < b->b_iused; i++) {
363
47.9k
        if (OPCODE_HAS_EVAL_BREAK(b->b_instr[i].i_opcode)) {
364
3.62k
            return true;
365
3.62k
        }
366
47.9k
    }
367
6.32k
    return false;
368
9.94k
}
369
370
static bool
371
cfg_builder_current_block_is_terminated(cfg_builder *g)
372
149k
{
373
149k
    cfg_instr *last = basicblock_last_instr(g->g_curblock);
374
149k
    if (last && IS_TERMINATOR_OPCODE(last->i_opcode)) {
375
8.40k
        return true;
376
8.40k
    }
377
141k
    if (IS_LABEL(g->g_current_label)) {
378
1.12k
        if (last || IS_LABEL(g->g_curblock->b_label)) {
379
1.12k
            return true;
380
1.12k
        }
381
0
        else {
382
            /* current block is empty, label it */
383
0
            g->g_curblock->b_label = g->g_current_label;
384
0
            g->g_current_label = NO_LABEL;
385
0
        }
386
1.12k
    }
387
140k
    return false;
388
141k
}
389
390
static int
391
cfg_builder_maybe_start_new_block(cfg_builder *g)
392
149k
{
393
149k
    if (cfg_builder_current_block_is_terminated(g)) {
394
9.53k
        basicblock *b = cfg_builder_new_block(g);
395
9.53k
        if (b == NULL) {
396
0
            return ERROR;
397
0
        }
398
9.53k
        b->b_label = g->g_current_label;
399
9.53k
        g->g_current_label = NO_LABEL;
400
9.53k
        cfg_builder_use_next_block(g, b);
401
9.53k
    }
402
149k
    return SUCCESS;
403
149k
}
404
405
#ifndef NDEBUG
406
static bool
407
cfg_builder_check(cfg_builder *g)
408
{
409
    for (basicblock *block = g->g_block_list; block != NULL; block = block->b_list) {
410
        assert(!_PyMem_IsPtrFreed(block));
411
        if (block->b_instr != NULL) {
412
            assert(block->b_ialloc > 0);
413
            assert(block->b_iused >= 0);
414
            assert(block->b_ialloc >= block->b_iused);
415
        }
416
        else {
417
            assert (block->b_iused == 0);
418
            assert (block->b_ialloc == 0);
419
        }
420
    }
421
    return true;
422
}
423
#endif
424
425
static int
426
init_cfg_builder(cfg_builder *g)
427
3.84k
{
428
3.84k
    g->g_block_list = NULL;
429
3.84k
    basicblock *block = cfg_builder_new_block(g);
430
3.84k
    if (block == NULL) {
431
0
        return ERROR;
432
0
    }
433
3.84k
    g->g_curblock = g->g_entryblock = block;
434
3.84k
    g->g_current_label = NO_LABEL;
435
3.84k
    return SUCCESS;
436
3.84k
}
437
438
cfg_builder *
439
_PyCfgBuilder_New(void)
440
3.84k
{
441
3.84k
    cfg_builder *g = PyMem_Malloc(sizeof(cfg_builder));
442
3.84k
    if (g == NULL) {
443
0
        PyErr_NoMemory();
444
0
        return NULL;
445
0
    }
446
3.84k
    memset(g, 0, sizeof(cfg_builder));
447
3.84k
    if (init_cfg_builder(g) < 0) {
448
0
        PyMem_Free(g);
449
0
        return NULL;
450
0
    }
451
3.84k
    return g;
452
3.84k
}
453
454
void
455
_PyCfgBuilder_Free(cfg_builder *g)
456
3.84k
{
457
3.84k
    if (g == NULL) {
458
0
        return;
459
0
    }
460
3.84k
    assert(cfg_builder_check(g));
461
3.84k
    basicblock *b = g->g_block_list;
462
17.5k
    while (b != NULL) {
463
13.6k
        if (b->b_instr) {
464
13.6k
            PyMem_Free((void *)b->b_instr);
465
13.6k
        }
466
13.6k
        basicblock *next = b->b_list;
467
13.6k
        PyMem_Free((void *)b);
468
13.6k
        b = next;
469
13.6k
    }
470
3.84k
    PyMem_Free(g);
471
3.84k
}
472
473
int
474
_PyCfgBuilder_CheckSize(cfg_builder *g)
475
3.84k
{
476
3.84k
    int nblocks = 0;
477
17.2k
    for (basicblock *b = g->g_block_list; b != NULL; b = b->b_list) {
478
13.3k
        nblocks++;
479
13.3k
    }
480
3.84k
    if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
481
0
        PyErr_NoMemory();
482
0
        return ERROR;
483
0
    }
484
3.84k
    return SUCCESS;
485
3.84k
}
486
487
int
488
_PyCfgBuilder_UseLabel(cfg_builder *g, jump_target_label lbl)
489
4.03k
{
490
4.03k
    g->g_current_label = lbl;
491
4.03k
    return cfg_builder_maybe_start_new_block(g);
492
4.03k
}
493
494
int
495
_PyCfgBuilder_Addop(cfg_builder *g, int opcode, int oparg, location loc)
496
145k
{
497
145k
    RETURN_IF_ERROR(cfg_builder_maybe_start_new_block(g));
498
145k
    return basicblock_addop(g->g_curblock, opcode, oparg, loc, NULL);
499
145k
}
500
501
502
static basicblock *
503
next_nonempty_block(basicblock *b)
504
13.5k
{
505
14.0k
    while (b && b->b_iused == 0) {
506
492
        b = b->b_next;
507
492
    }
508
13.5k
    return b;
509
13.5k
}
510
511
/***** debugging helpers *****/
512
513
#ifndef NDEBUG
514
static int remove_redundant_nops(cfg_builder *g);
515
516
static bool
517
no_redundant_nops(cfg_builder *g) {
518
    if (remove_redundant_nops(g) != 0) {
519
        return false;
520
    }
521
    return true;
522
}
523
524
static bool
525
no_redundant_jumps(cfg_builder *g) {
526
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
527
        cfg_instr *last = basicblock_last_instr(b);
528
        if (last != NULL) {
529
            if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
530
                basicblock *next = next_nonempty_block(b->b_next);
531
                basicblock *jump_target = next_nonempty_block(last->i_target);
532
                if (jump_target == next) {
533
                    assert(next);
534
                    if (last->i_loc.lineno == next->b_instr[0].i_loc.lineno) {
535
                        assert(0);
536
                        return false;
537
                    }
538
                }
539
            }
540
        }
541
    }
542
    return true;
543
}
544
#endif
545
546
/***** CFG preprocessing (jump targets and exceptions) *****/
547
548
static int
549
13.6k
normalize_jumps_in_block(cfg_builder *g, basicblock *b) {
550
13.6k
    cfg_instr *last = basicblock_last_instr(b);
551
13.6k
    if (last == NULL || !IS_CONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
552
10.8k
        return SUCCESS;
553
10.8k
    }
554
13.6k
    assert(!IS_ASSEMBLER_OPCODE(last->i_opcode));
555
556
2.80k
    bool is_forward = last->i_target->b_visited == 0;
557
2.80k
    if (is_forward) {
558
2.69k
        RETURN_IF_ERROR(
559
2.69k
            basicblock_addop(b, NOT_TAKEN, 0, last->i_loc, last->i_except));
560
2.69k
        return SUCCESS;
561
2.69k
    }
562
563
108
    int reversed_opcode = 0;
564
108
    switch(last->i_opcode) {
565
0
        case POP_JUMP_IF_NOT_NONE:
566
0
            reversed_opcode = POP_JUMP_IF_NONE;
567
0
            break;
568
5
        case POP_JUMP_IF_NONE:
569
5
            reversed_opcode = POP_JUMP_IF_NOT_NONE;
570
5
            break;
571
89
        case POP_JUMP_IF_FALSE:
572
89
            reversed_opcode = POP_JUMP_IF_TRUE;
573
89
            break;
574
14
        case POP_JUMP_IF_TRUE:
575
14
            reversed_opcode = POP_JUMP_IF_FALSE;
576
14
            break;
577
108
    }
578
    /* transform 'conditional jump T' to
579
     * 'reversed_jump b_next' followed by 'jump_backwards T'
580
     */
581
582
108
    basicblock *target = last->i_target;
583
108
    basicblock *backwards_jump = cfg_builder_new_block(g);
584
108
    if (backwards_jump == NULL) {
585
0
        return ERROR;
586
0
    }
587
108
    RETURN_IF_ERROR(
588
108
        basicblock_addop(backwards_jump, NOT_TAKEN, 0, last->i_loc,
589
108
                         last->i_except));
590
108
    RETURN_IF_ERROR(
591
108
        basicblock_add_jump(backwards_jump, JUMP, target, last->i_loc,
592
108
                            last->i_except));
593
108
    backwards_jump->b_startdepth = target->b_startdepth;
594
108
    last->i_opcode = reversed_opcode;
595
108
    last->i_target = b->b_next;
596
597
108
    backwards_jump->b_cold = b->b_cold;
598
108
    backwards_jump->b_next = b->b_next;
599
108
    b->b_next = backwards_jump;
600
108
    return SUCCESS;
601
108
}
602
603
604
static int
605
normalize_jumps(cfg_builder *g)
606
3.84k
{
607
3.84k
    basicblock *entryblock = g->g_entryblock;
608
17.4k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
609
13.5k
        b->b_visited = 0;
610
13.5k
    }
611
17.5k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
612
13.6k
        b->b_visited = 1;
613
13.6k
        RETURN_IF_ERROR(normalize_jumps_in_block(g, b));
614
13.6k
    }
615
3.84k
    return SUCCESS;
616
3.84k
}
617
618
static int
619
3.84k
check_cfg(cfg_builder *g) {
620
17.2k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
621
        /* Raise SystemError if jump or exit is not last instruction in the block. */
622
158k
        for (int i = 0; i < b->b_iused; i++) {
623
145k
            int opcode = b->b_instr[i].i_opcode;
624
145k
            assert(!IS_ASSEMBLER_OPCODE(opcode));
625
145k
            if (IS_TERMINATOR_OPCODE(opcode)) {
626
12.2k
                if (i != b->b_iused - 1) {
627
0
                    PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
628
0
                    return ERROR;
629
0
                }
630
12.2k
            }
631
145k
        }
632
13.3k
    }
633
3.84k
    return SUCCESS;
634
3.84k
}
635
636
static int
637
get_max_label(basicblock *entryblock)
638
14.4k
{
639
14.4k
    int lbl = -1;
640
67.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
641
52.9k
        if (b->b_label.id > lbl) {
642
14.9k
            lbl = b->b_label.id;
643
14.9k
        }
644
52.9k
    }
645
14.4k
    return lbl;
646
14.4k
}
647
648
/* Calculate the actual jump target from the target_label */
649
static int
650
translate_jump_labels_to_targets(basicblock *entryblock)
651
3.84k
{
652
3.84k
    int max_label = get_max_label(entryblock);
653
3.84k
    size_t mapsize = sizeof(basicblock *) * (max_label + 1);
654
3.84k
    basicblock **label2block = (basicblock **)PyMem_Malloc(mapsize);
655
3.84k
    if (!label2block) {
656
0
        PyErr_NoMemory();
657
0
        return ERROR;
658
0
    }
659
3.84k
    memset(label2block, 0, mapsize);
660
17.2k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
661
13.3k
        if (b->b_label.id >= 0) {
662
4.03k
            label2block[b->b_label.id] = b;
663
4.03k
        }
664
13.3k
    }
665
17.2k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
666
158k
        for (int i = 0; i < b->b_iused; i++) {
667
145k
            cfg_instr *instr = &b->b_instr[i];
668
145k
            assert(instr->i_target == NULL);
669
145k
            if (HAS_TARGET(instr->i_opcode)) {
670
5.11k
                int lbl = instr->i_oparg;
671
5.11k
                assert(lbl >= 0 && lbl <= max_label);
672
5.11k
                instr->i_target = label2block[lbl];
673
5.11k
                assert(instr->i_target != NULL);
674
5.11k
                assert(instr->i_target->b_label.id == lbl);
675
5.11k
            }
676
145k
        }
677
13.3k
    }
678
3.84k
    PyMem_Free(label2block);
679
3.84k
    return SUCCESS;
680
3.84k
}
681
682
static int
683
3.84k
mark_except_handlers(basicblock *entryblock) {
684
#ifndef NDEBUG
685
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
686
        assert(!b->b_except_handler);
687
    }
688
#endif
689
17.2k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
690
158k
        for (int i=0; i < b->b_iused; i++) {
691
145k
            cfg_instr *instr = &b->b_instr[i];
692
145k
            if (is_block_push(instr)) {
693
657
                instr->i_target->b_except_handler = 1;
694
657
            }
695
145k
        }
696
13.3k
    }
697
3.84k
    return SUCCESS;
698
3.84k
}
699
700
701
struct _PyCfgExceptStack {
702
    basicblock *handlers[CO_MAXBLOCKS+2];
703
    int depth;
704
};
705
706
707
static basicblock *
708
657
push_except_block(struct _PyCfgExceptStack *stack, cfg_instr *setup) {
709
657
    assert(is_block_push(setup));
710
657
    int opcode = setup->i_opcode;
711
657
    basicblock * target = setup->i_target;
712
657
    if (opcode == SETUP_WITH || opcode == SETUP_CLEANUP) {
713
435
        target->b_preserve_lasti = 1;
714
435
    }
715
657
    assert(stack->depth <= CO_MAXBLOCKS);
716
657
    stack->handlers[++stack->depth] = target;
717
657
    return target;
718
657
}
719
720
static basicblock *
721
616
pop_except_block(struct _PyCfgExceptStack *stack) {
722
616
    assert(stack->depth > 0);
723
616
    return stack->handlers[--stack->depth];
724
616
}
725
726
static basicblock *
727
10.7k
except_stack_top(struct _PyCfgExceptStack *stack) {
728
10.7k
    return stack->handlers[stack->depth];
729
10.7k
}
730
731
static struct _PyCfgExceptStack *
732
3.84k
make_except_stack(void) {
733
3.84k
    struct _PyCfgExceptStack *new = PyMem_Malloc(sizeof(struct _PyCfgExceptStack));
734
3.84k
    if (new == NULL) {
735
0
        PyErr_NoMemory();
736
0
        return NULL;
737
0
    }
738
3.84k
    new->depth = 0;
739
3.84k
    new->handlers[0] = NULL;
740
3.84k
    return new;
741
3.84k
}
742
743
static struct _PyCfgExceptStack *
744
3.15k
copy_except_stack(struct _PyCfgExceptStack *stack) {
745
3.15k
    struct _PyCfgExceptStack *copy = PyMem_Malloc(sizeof(struct _PyCfgExceptStack));
746
3.15k
    if (copy == NULL) {
747
0
        PyErr_NoMemory();
748
0
        return NULL;
749
0
    }
750
3.15k
    memcpy(copy, stack, sizeof(struct _PyCfgExceptStack));
751
3.15k
    return copy;
752
3.15k
}
753
754
static basicblock**
755
27.3k
make_cfg_traversal_stack(basicblock *entryblock) {
756
27.3k
    int nblocks = 0;
757
131k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
758
104k
        b->b_visited = 0;
759
104k
        nblocks++;
760
104k
    }
761
27.3k
    basicblock **stack = (basicblock **)PyMem_Malloc(sizeof(basicblock *) * nblocks);
762
27.3k
    if (!stack) {
763
0
        PyErr_NoMemory();
764
0
    }
765
27.3k
    return stack;
766
27.3k
}
767
768
/* Compute the stack effects of opcode with argument oparg.
769
770
   Some opcodes have different stack effect when jump to the target and
771
   when not jump. The 'jump' parameter specifies the case:
772
773
   * 0 -- when not jump
774
   * 1 -- when jump
775
   * -1 -- maximal
776
 */
777
typedef struct {
778
    /* The stack effect of the instruction. */
779
    int net;
780
} stack_effects;
781
782
Py_LOCAL(int)
783
get_stack_effects(int opcode, int oparg, int jump, stack_effects *effects)
784
137k
{
785
137k
    if (opcode < 0) {
786
0
        return -1;
787
0
    }
788
137k
    if ((opcode <= MAX_REAL_OPCODE) && (_PyOpcode_Deopt[opcode] != opcode)) {
789
        // Specialized instructions are not supported.
790
0
        return -1;
791
0
    }
792
137k
    int popped = _PyOpcode_num_popped(opcode, oparg);
793
137k
    int pushed = _PyOpcode_num_pushed(opcode, oparg);
794
137k
    if (popped < 0 || pushed < 0) {
795
0
        return -1;
796
0
    }
797
137k
    if (IS_BLOCK_PUSH_OPCODE(opcode) && !jump) {
798
657
        effects->net = 0;
799
657
        return 0;
800
657
    }
801
136k
    effects->net = pushed - popped;
802
136k
    return 0;
803
137k
}
804
805
Py_LOCAL_INLINE(int)
806
stackdepth_push(basicblock ***sp, basicblock *b, int depth)
807
12.6k
{
808
12.6k
    if (!(b->b_startdepth < 0 || b->b_startdepth == depth)) {
809
0
        PyErr_Format(PyExc_ValueError, "Invalid CFG, inconsistent stackdepth");
810
0
        return ERROR;
811
0
    }
812
12.6k
    if (b->b_startdepth < depth && b->b_startdepth < 100) {
813
10.7k
        assert(b->b_startdepth < 0);
814
10.7k
        b->b_startdepth = depth;
815
10.7k
        *(*sp)++ = b;
816
10.7k
    }
817
12.6k
    return SUCCESS;
818
12.6k
}
819
820
/* Find the flow path that needs the largest stack.  We assume that
821
 * cycles in the flow graph have no net effect on the stack depth.
822
 */
823
static int
824
calculate_stackdepth(cfg_builder *g)
825
3.84k
{
826
3.84k
    basicblock *entryblock = g->g_entryblock;
827
17.4k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
828
13.5k
        b->b_startdepth = INT_MIN;
829
13.5k
    }
830
3.84k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
831
3.84k
    if (!stack) {
832
0
        return ERROR;
833
0
    }
834
835
836
3.84k
    int stackdepth = -1;
837
3.84k
    int maxdepth = 0;
838
3.84k
    basicblock **sp = stack;
839
3.84k
    if (stackdepth_push(&sp, entryblock, 0) < 0) {
840
0
        goto error;
841
0
    }
842
14.6k
    while (sp != stack) {
843
10.7k
        basicblock *b = *--sp;
844
10.7k
        int depth = b->b_startdepth;
845
10.7k
        assert(depth >= 0);
846
10.7k
        basicblock *next = b->b_next;
847
137k
        for (int i = 0; i < b->b_iused; i++) {
848
132k
            cfg_instr *instr = &b->b_instr[i];
849
132k
            stack_effects effects;
850
132k
            if (get_stack_effects(instr->i_opcode, instr->i_oparg, 0, &effects) < 0) {
851
0
                PyErr_Format(PyExc_SystemError,
852
0
                             "Invalid stack effect for opcode=%d, arg=%i",
853
0
                             instr->i_opcode, instr->i_oparg);
854
0
                goto error;
855
0
            }
856
132k
            int new_depth = depth + effects.net;
857
132k
            if (new_depth < 0) {
858
0
                PyErr_Format(PyExc_ValueError,
859
0
                             "Invalid CFG, stack underflow at line %d", instr->i_loc.lineno);
860
0
                goto error;
861
0
            }
862
132k
            maxdepth = Py_MAX(maxdepth, depth);
863
132k
            if (HAS_TARGET(instr->i_opcode) && instr->i_opcode != END_ASYNC_FOR) {
864
4.38k
                if (get_stack_effects(instr->i_opcode, instr->i_oparg, 1, &effects) < 0) {
865
0
                    PyErr_Format(PyExc_SystemError,
866
0
                                 "Invalid stack effect for opcode=%d, arg=%i",
867
0
                                 instr->i_opcode, instr->i_oparg);
868
0
                    goto error;
869
0
                }
870
4.38k
                int target_depth = depth + effects.net;
871
4.38k
                assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
872
4.38k
                maxdepth = Py_MAX(maxdepth, depth);
873
4.38k
                if (stackdepth_push(&sp, instr->i_target, target_depth) < 0) {
874
0
                    goto error;
875
0
                }
876
4.38k
            }
877
132k
            depth = new_depth;
878
132k
            assert(!IS_ASSEMBLER_OPCODE(instr->i_opcode));
879
132k
            if (IS_UNCONDITIONAL_JUMP_OPCODE(instr->i_opcode) ||
880
132k
                IS_SCOPE_EXIT_OPCODE(instr->i_opcode))
881
6.36k
            {
882
                /* remaining code is dead */
883
6.36k
                next = NULL;
884
6.36k
                break;
885
6.36k
            }
886
132k
        }
887
10.7k
        if (next != NULL) {
888
4.39k
            assert(BB_HAS_FALLTHROUGH(b));
889
4.39k
            if (stackdepth_push(&sp, next, depth) < 0) {
890
0
                goto error;
891
0
            }
892
4.39k
        }
893
10.7k
    }
894
3.84k
    stackdepth = maxdepth;
895
3.84k
error:
896
3.84k
    PyMem_Free(stack);
897
3.84k
    return stackdepth;
898
3.84k
}
899
900
static int
901
3.84k
label_exception_targets(basicblock *entryblock) {
902
3.84k
    basicblock **todo_stack = make_cfg_traversal_stack(entryblock);
903
3.84k
    if (todo_stack == NULL) {
904
0
        return ERROR;
905
0
    }
906
3.84k
    struct _PyCfgExceptStack *except_stack = make_except_stack();
907
3.84k
    if (except_stack == NULL) {
908
0
        PyMem_Free(todo_stack);
909
0
        PyErr_NoMemory();
910
0
        return ERROR;
911
0
    }
912
3.84k
    except_stack->depth = 0;
913
3.84k
    todo_stack[0] = entryblock;
914
3.84k
    entryblock->b_visited = 1;
915
3.84k
    entryblock->b_exceptstack = except_stack;
916
3.84k
    basicblock **todo = &todo_stack[1];
917
3.84k
    basicblock *handler = NULL;
918
14.5k
    while (todo > todo_stack) {
919
10.7k
        todo--;
920
10.7k
        basicblock *b = todo[0];
921
10.7k
        assert(b->b_visited == 1);
922
10.7k
        except_stack = b->b_exceptstack;
923
10.7k
        assert(except_stack != NULL);
924
10.7k
        b->b_exceptstack = NULL;
925
10.7k
        handler = except_stack_top(except_stack);
926
10.7k
        int last_yield_except_depth = -1;
927
150k
        for (int i = 0; i < b->b_iused; i++) {
928
140k
            cfg_instr *instr = &b->b_instr[i];
929
140k
            if (is_block_push(instr)) {
930
657
                if (!instr->i_target->b_visited) {
931
657
                    struct _PyCfgExceptStack *copy = copy_except_stack(except_stack);
932
657
                    if (copy == NULL) {
933
0
                        goto error;
934
0
                    }
935
657
                    instr->i_target->b_exceptstack = copy;
936
657
                    todo[0] = instr->i_target;
937
657
                    instr->i_target->b_visited = 1;
938
657
                    todo++;
939
657
                }
940
657
                handler = push_except_block(except_stack, instr);
941
657
            }
942
139k
            else if (instr->i_opcode == POP_BLOCK) {
943
616
                handler = pop_except_block(except_stack);
944
616
                INSTR_SET_OP0(instr, NOP);
945
616
            }
946
138k
            else if (is_jump(instr)) {
947
4.27k
                instr->i_except = handler;
948
4.27k
                assert(i == b->b_iused -1);
949
4.27k
                if (!instr->i_target->b_visited) {
950
3.05k
                    if (BB_HAS_FALLTHROUGH(b)) {
951
2.49k
                        struct _PyCfgExceptStack *copy = copy_except_stack(except_stack);
952
2.49k
                        if (copy == NULL) {
953
0
                            goto error;
954
0
                        }
955
2.49k
                        instr->i_target->b_exceptstack = copy;
956
2.49k
                    }
957
557
                    else {
958
557
                        instr->i_target->b_exceptstack = except_stack;
959
557
                        except_stack = NULL;
960
557
                    }
961
3.05k
                    todo[0] = instr->i_target;
962
3.05k
                    instr->i_target->b_visited = 1;
963
3.05k
                    todo++;
964
3.05k
                }
965
4.27k
            }
966
134k
            else if (instr->i_opcode == YIELD_VALUE) {
967
72
                instr->i_except = handler;
968
72
                last_yield_except_depth = except_stack->depth;
969
72
            }
970
134k
            else if (instr->i_opcode == RESUME) {
971
3.94k
                instr->i_except = handler;
972
3.94k
                if (instr->i_oparg != RESUME_AT_FUNC_START && instr->i_oparg != RESUME_AT_GEN_EXPR_START) {
973
72
                    assert(last_yield_except_depth >= 0);
974
72
                    if (last_yield_except_depth == 1) {
975
58
                        instr->i_oparg |= RESUME_OPARG_DEPTH1_MASK;
976
58
                    }
977
72
                    last_yield_except_depth = -1;
978
72
                }
979
3.94k
            }
980
130k
            else if (instr->i_opcode == RETURN_GENERATOR) {
981
59
                instr->i_except = NULL;
982
59
            }
983
130k
            else {
984
130k
                instr->i_except = handler;
985
130k
            }
986
140k
        }
987
10.7k
        if (BB_HAS_FALLTHROUGH(b) && !b->b_next->b_visited) {
988
3.19k
            assert(except_stack != NULL);
989
3.19k
            b->b_next->b_exceptstack = except_stack;
990
3.19k
            todo[0] = b->b_next;
991
3.19k
            b->b_next->b_visited = 1;
992
3.19k
            todo++;
993
3.19k
        }
994
7.55k
        else if (except_stack != NULL) {
995
7.00k
           PyMem_Free(except_stack);
996
7.00k
        }
997
10.7k
    }
998
#ifdef Py_DEBUG
999
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1000
        assert(b->b_exceptstack == NULL);
1001
    }
1002
#endif
1003
3.84k
    PyMem_Free(todo_stack);
1004
3.84k
    return SUCCESS;
1005
0
error:
1006
0
    PyMem_Free(todo_stack);
1007
0
    PyMem_Free(except_stack);
1008
0
    return ERROR;
1009
3.84k
}
1010
1011
/***** CFG optimizations *****/
1012
1013
static int
1014
7.69k
remove_unreachable(basicblock *entryblock) {
1015
34.6k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1016
26.9k
        b->b_predecessors = 0;
1017
26.9k
    }
1018
7.69k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
1019
7.69k
    if (stack == NULL) {
1020
0
        return ERROR;
1021
0
    }
1022
7.69k
    basicblock **sp = stack;
1023
7.69k
    entryblock->b_predecessors = 1;
1024
7.69k
    *sp++ = entryblock;
1025
7.69k
    entryblock->b_visited = 1;
1026
28.9k
    while (sp > stack) {
1027
21.2k
        basicblock *b = *(--sp);
1028
21.2k
        if (b->b_next && BB_HAS_FALLTHROUGH(b)) {
1029
8.38k
            if (!b->b_next->b_visited) {
1030
7.04k
                assert(b->b_next->b_predecessors == 0);
1031
7.04k
                *sp++ = b->b_next;
1032
7.04k
                b->b_next->b_visited = 1;
1033
7.04k
            }
1034
8.38k
            b->b_next->b_predecessors++;
1035
8.38k
        }
1036
294k
        for (int i = 0; i < b->b_iused; i++) {
1037
272k
            basicblock *target;
1038
272k
            cfg_instr *instr = &b->b_instr[i];
1039
272k
            if (is_jump(instr) || is_block_push(instr)) {
1040
9.04k
                target = instr->i_target;
1041
9.04k
                if (!target->b_visited) {
1042
6.54k
                    *sp++ = target;
1043
6.54k
                    target->b_visited = 1;
1044
6.54k
                }
1045
9.04k
                target->b_predecessors++;
1046
9.04k
            }
1047
272k
        }
1048
21.2k
    }
1049
7.69k
    PyMem_Free(stack);
1050
1051
    /* Delete unreachable instructions */
1052
34.6k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1053
26.9k
       if (b->b_predecessors == 0) {
1054
5.65k
            b->b_iused = 0;
1055
5.65k
            b->b_except_handler = 0;
1056
5.65k
       }
1057
26.9k
    }
1058
7.69k
    return SUCCESS;
1059
7.69k
}
1060
1061
static int
1062
65.7k
basicblock_remove_redundant_nops(basicblock *bb) {
1063
    /* Remove NOPs when legal to do so. */
1064
65.7k
    int dest = 0;
1065
65.7k
    int prev_lineno = -1;
1066
677k
    for (int src = 0; src < bb->b_iused; src++) {
1067
612k
        int lineno = bb->b_instr[src].i_loc.lineno;
1068
612k
        if (bb->b_instr[src].i_opcode == NOP) {
1069
            /* Eliminate no-op if it doesn't have a line number */
1070
12.9k
            if (lineno < 0) {
1071
3.71k
                continue;
1072
3.71k
            }
1073
            /* or, if the previous instruction had the same line number. */
1074
9.20k
            if (prev_lineno == lineno) {
1075
7.50k
                continue;
1076
7.50k
            }
1077
            /* or, if the next instruction has same line number or no line number */
1078
1.70k
            if (src < bb->b_iused - 1) {
1079
1.58k
                int next_lineno = bb->b_instr[src+1].i_loc.lineno;
1080
1.58k
                if (next_lineno == lineno) {
1081
994
                    continue;
1082
994
                }
1083
595
                if (next_lineno < 0) {
1084
0
                    bb->b_instr[src+1].i_loc = bb->b_instr[src].i_loc;
1085
0
                    continue;
1086
0
                }
1087
595
            }
1088
111
            else {
1089
111
                basicblock *next = next_nonempty_block(bb->b_next);
1090
                /* or if last instruction in BB and next BB has same line number */
1091
111
                if (next) {
1092
111
                    location next_loc = NO_LOCATION;
1093
111
                    for (int next_i=0; next_i < next->b_iused; next_i++) {
1094
111
                        cfg_instr *instr = &next->b_instr[next_i];
1095
111
                        if (instr->i_opcode == NOP && instr->i_loc.lineno < 0) {
1096
                            /* Skip over NOPs without a location, they will be removed */
1097
0
                            continue;
1098
0
                        }
1099
111
                        next_loc = instr->i_loc;
1100
111
                        break;
1101
111
                    }
1102
111
                    if (lineno == next_loc.lineno) {
1103
0
                        continue;
1104
0
                    }
1105
111
                }
1106
111
            }
1107
1108
1.70k
        }
1109
599k
        if (dest != src) {
1110
46.7k
            bb->b_instr[dest] = bb->b_instr[src];
1111
46.7k
        }
1112
599k
        dest++;
1113
599k
        prev_lineno = lineno;
1114
599k
    }
1115
65.7k
    assert(dest <= bb->b_iused);
1116
65.7k
    int num_removed = bb->b_iused - dest;
1117
65.7k
    bb->b_iused = dest;
1118
65.7k
    memset(&bb->b_instr[dest], 0, sizeof(cfg_instr) * num_removed);
1119
65.7k
    return num_removed;
1120
65.7k
}
1121
1122
static int
1123
12.1k
remove_redundant_nops(cfg_builder *g) {
1124
12.1k
    int changes = 0;
1125
64.3k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
1126
52.1k
        int change = basicblock_remove_redundant_nops(b);
1127
52.1k
        RETURN_IF_ERROR(change);
1128
52.1k
        changes += change;
1129
52.1k
    }
1130
12.1k
    return changes;
1131
12.1k
}
1132
1133
static int loads_const(int opcode);
1134
1135
static int
1136
remove_redundant_nops_and_pairs(basicblock *entryblock)
1137
3.84k
{
1138
3.84k
    bool done = false;
1139
1140
7.69k
    while (! done) {
1141
3.84k
        done = true;
1142
3.84k
        cfg_instr *prev_instr = NULL;
1143
3.84k
        cfg_instr *instr = NULL;
1144
17.4k
        for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1145
13.5k
            RETURN_IF_ERROR(basicblock_remove_redundant_nops(b));
1146
13.5k
            if (IS_LABEL(b->b_label)) {
1147
                /* this block is a jump target, forget instr */
1148
4.21k
                instr = NULL;
1149
4.21k
            }
1150
145k
            for (int i = 0; i < b->b_iused; i++) {
1151
132k
                prev_instr = instr;
1152
132k
                instr = &b->b_instr[i];
1153
132k
                int prev_opcode = prev_instr ? prev_instr->i_opcode : 0;
1154
132k
                int prev_oparg = prev_instr ? prev_instr->i_oparg : 0;
1155
132k
                int opcode = instr->i_opcode;
1156
132k
                bool is_redundant_pair = false;
1157
132k
                if (opcode == POP_TOP) {
1158
3.82k
                   if (loads_const(prev_opcode)) {
1159
0
                       is_redundant_pair = true;
1160
0
                   }
1161
3.82k
                   else if (prev_opcode == COPY && prev_oparg == 1) {
1162
0
                       is_redundant_pair = true;
1163
0
                   }
1164
3.82k
                }
1165
132k
                if (is_redundant_pair) {
1166
0
                    INSTR_SET_OP0(prev_instr, NOP);
1167
0
                    INSTR_SET_OP0(instr, NOP);
1168
0
                    done = false;
1169
0
                }
1170
132k
            }
1171
13.5k
            if ((instr && is_jump(instr)) || !BB_HAS_FALLTHROUGH(b)) {
1172
9.64k
                instr = NULL;
1173
9.64k
            }
1174
13.5k
        }
1175
3.84k
    }
1176
3.84k
    return SUCCESS;
1177
3.84k
}
1178
1179
static int
1180
8.33k
remove_redundant_jumps(cfg_builder *g) {
1181
    /* If a non-empty block ends with a jump instruction, check if the next
1182
     * non-empty block reached through normal flow control is the target
1183
     * of that jump. If it is, then the jump instruction is redundant and
1184
     * can be deleted.
1185
     *
1186
     * Return the number of changes applied, or -1 on error.
1187
     */
1188
1189
8.33k
    int changes = 0;
1190
46.8k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
1191
38.5k
        cfg_instr *last = basicblock_last_instr(b);
1192
38.5k
        if (last == NULL) {
1193
7.00k
            continue;
1194
7.00k
        }
1195
38.5k
        assert(!IS_ASSEMBLER_OPCODE(last->i_opcode));
1196
31.5k
        if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
1197
2.86k
            basicblock* jump_target = next_nonempty_block(last->i_target);
1198
2.86k
            if (jump_target == NULL) {
1199
0
                PyErr_SetString(PyExc_SystemError, "jump with NULL target");
1200
0
                return ERROR;
1201
0
            }
1202
2.86k
            basicblock *next = next_nonempty_block(b->b_next);
1203
2.86k
            if (jump_target == next) {
1204
128
                changes++;
1205
128
                INSTR_SET_OP0(last, NOP);
1206
128
            }
1207
2.86k
        }
1208
31.5k
    }
1209
1210
8.33k
    return changes;
1211
8.33k
}
1212
1213
static inline bool
1214
11.8k
basicblock_has_no_lineno(basicblock *b) {
1215
14.9k
    for (int i = 0; i < b->b_iused; i++) {
1216
13.5k
        if (b->b_instr[i].i_loc.lineno >= 0) {
1217
10.5k
            return false;
1218
10.5k
        }
1219
13.5k
    }
1220
1.32k
    return true;
1221
11.8k
}
1222
1223
/* Maximum size of basic block that should be copied in optimizer */
1224
652
#define MAX_COPY_SIZE 4
1225
1226
/* If this block ends with an unconditional jump to a small exit block or
1227
 * a block that has no line numbers (and no fallthrough), then
1228
 * remove the jump and extend this block with the target.
1229
 * Returns 1 if extended, 0 if no change, and -1 on error.
1230
 */
1231
static int
1232
17.5k
basicblock_inline_small_or_no_lineno_blocks(basicblock *bb) {
1233
17.5k
    cfg_instr *last = basicblock_last_instr(bb);
1234
17.5k
    if (last == NULL) {
1235
0
        return 0;
1236
0
    }
1237
17.5k
    if (!IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
1238
15.5k
        return 0;
1239
15.5k
    }
1240
1.99k
    basicblock *target = last->i_target;
1241
1.99k
    bool small_exit_block = (basicblock_exits_scope(target) &&
1242
652
                             target->b_iused <= MAX_COPY_SIZE);
1243
1.99k
    bool no_lineno_no_fallthrough = (basicblock_has_no_lineno(target) &&
1244
540
                                     !BB_HAS_FALLTHROUGH(target));
1245
1.99k
    if (small_exit_block || no_lineno_no_fallthrough) {
1246
610
        assert(is_jump(last));
1247
610
        int removed_jump_opcode = last->i_opcode;
1248
610
        INSTR_SET_OP0(last, NOP);
1249
610
        RETURN_IF_ERROR(basicblock_append_instructions(bb, target));
1250
610
        if (no_lineno_no_fallthrough) {
1251
540
            last = basicblock_last_instr(bb);
1252
540
            if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode) &&
1253
144
                removed_jump_opcode == JUMP)
1254
19
            {
1255
                /* Make sure we don't lose eval breaker checks */
1256
19
                last->i_opcode = JUMP;
1257
19
            }
1258
540
        }
1259
610
        target->b_predecessors--;
1260
610
        return 1;
1261
610
    }
1262
1.38k
    return 0;
1263
1.99k
}
1264
1265
static int
1266
3.84k
inline_small_or_no_lineno_blocks(basicblock *entryblock) {
1267
3.84k
    bool changes;
1268
4.12k
    do {
1269
4.12k
        changes = false;
1270
21.6k
        for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1271
17.5k
            int res = basicblock_inline_small_or_no_lineno_blocks(b);
1272
17.5k
            RETURN_IF_ERROR(res);
1273
17.5k
            if (res) {
1274
610
                changes = true;
1275
610
            }
1276
17.5k
        }
1277
4.12k
    } while(changes); /* every change removes a jump, ensuring convergence */
1278
3.84k
    return changes;
1279
3.84k
}
1280
1281
// Attempt to eliminate jumps to jumps by updating inst to jump to
1282
// target->i_target using the provided opcode. Return whether or not the
1283
// optimization was successful.
1284
static bool
1285
jump_thread(basicblock *bb, cfg_instr *inst, cfg_instr *target, int opcode)
1286
104
{
1287
104
    assert(is_jump(inst));
1288
104
    assert(is_jump(target));
1289
104
    assert(inst == basicblock_last_instr(bb));
1290
    // bpo-45773: If inst->i_target == target->i_target, then nothing actually
1291
    // changes (and we fall into an infinite loop):
1292
104
    if (inst->i_target != target->i_target) {
1293
        /* Change inst to NOP and append a jump to target->i_target. The
1294
         * NOP will be removed later if it's not needed for the lineno.
1295
         */
1296
104
        INSTR_SET_OP0(inst, NOP);
1297
1298
104
        RETURN_IF_ERROR(
1299
104
            basicblock_add_jump(
1300
104
                bb, opcode, target->i_target, target->i_loc,
1301
104
                target->i_except));
1302
1303
104
        return true;
1304
104
    }
1305
0
    return false;
1306
104
}
1307
1308
static int
1309
loads_const(int opcode)
1310
153k
{
1311
153k
    return OPCODE_HAS_CONST(opcode)
1312
131k
        || opcode == LOAD_SMALL_INT
1313
114k
        || opcode == LOAD_COMMON_CONSTANT;
1314
153k
}
1315
1316
/* Returns new reference */
1317
static PyObject*
1318
get_const_value(int opcode, int oparg, PyObject *co_consts)
1319
55.3k
{
1320
55.3k
    PyObject *constant = NULL;
1321
55.3k
    assert(loads_const(opcode));
1322
55.3k
    if (opcode == LOAD_CONST) {
1323
53.1k
        assert(PyList_Check(co_consts));
1324
53.1k
        Py_ssize_t n = PyList_GET_SIZE(co_consts);
1325
53.1k
        if (oparg < 0 || oparg >= n) {
1326
0
            PyErr_Format(PyExc_ValueError,
1327
0
                         "LOAD_CONST index %d is out of range for consts (len=%zd)",
1328
0
                         oparg, n);
1329
0
            return NULL;
1330
0
        }
1331
53.1k
        constant = PyList_GET_ITEM(co_consts, oparg);
1332
53.1k
    }
1333
55.3k
    if (opcode == LOAD_SMALL_INT) {
1334
1.84k
        return PyLong_FromLong(oparg);
1335
1.84k
    }
1336
53.4k
    if (opcode == LOAD_COMMON_CONSTANT) {
1337
352
        assert(oparg < NUM_COMMON_CONSTANTS);
1338
352
        return PyStackRef_AsPyObjectBorrow(
1339
352
            _PyInterpreterState_GET()->common_consts[oparg]);
1340
352
    }
1341
1342
53.1k
    if (constant == NULL) {
1343
0
        PyErr_SetString(PyExc_SystemError,
1344
0
                        "Internal error: failed to get value of a constant");
1345
0
        return NULL;
1346
0
    }
1347
53.1k
    return Py_NewRef(constant);
1348
53.1k
}
1349
1350
// Steals a reference to newconst.
1351
static int
1352
add_const(PyObject *newconst, PyObject *consts, PyObject *const_cache,
1353
          _Py_hashtable_t *consts_index)
1354
2.02k
{
1355
2.02k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &newconst) < 0) {
1356
0
        Py_DECREF(newconst);
1357
0
        return -1;
1358
0
    }
1359
1360
2.02k
    _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(consts_index, (void *)newconst);
1361
2.02k
    if (entry != NULL) {
1362
1.41k
        Py_DECREF(newconst);
1363
1.41k
        return (int)(uintptr_t)entry->value;
1364
1.41k
    }
1365
1366
603
    Py_ssize_t index = PyList_GET_SIZE(consts);
1367
603
    if ((size_t)index >= (size_t)INT_MAX - 1) {
1368
0
        PyErr_SetString(PyExc_OverflowError, "too many constants");
1369
0
        Py_DECREF(newconst);
1370
0
        return -1;
1371
0
    }
1372
603
    if (PyList_Append(consts, newconst)) {
1373
0
        Py_DECREF(newconst);
1374
0
        return -1;
1375
0
    }
1376
1377
603
    if (_Py_hashtable_set(consts_index, (void *)newconst, (void *)(uintptr_t)index) < 0) {
1378
0
        PyList_SetSlice(consts, index, index + 1, NULL);
1379
0
        Py_DECREF(newconst);
1380
0
        PyErr_NoMemory();
1381
0
        return -1;
1382
0
    }
1383
1384
603
    Py_DECREF(newconst);
1385
603
    return (int)index;
1386
603
}
1387
1388
/*
1389
  Traverse the instructions of the basic block backwards from index "start", skipping over NOPs.
1390
  Try to collect "size" number of consecutive instructions that load constants into the array "instrs".
1391
  Caller must make sure that length of "instrs" is sufficient to fit in at least "size" instructions.
1392
1393
  Return boolean indicating whether "size" such instructions were found.
1394
*/
1395
static bool
1396
get_const_loading_instrs(basicblock *bb, int start, cfg_instr **instrs, int size)
1397
4.63k
{
1398
4.63k
    assert(start < bb->b_iused);
1399
4.63k
    assert(size >= 0);
1400
4.63k
    assert(size <= _PY_STACK_USE_GUIDELINE);
1401
1402
8.72k
    for (; start >= 0 && size > 0; start--) {
1403
6.26k
        cfg_instr *instr = &bb->b_instr[start];
1404
6.26k
        if (instr->i_opcode == NOP) {
1405
104
            continue;
1406
104
        }
1407
6.15k
        if (!loads_const(instr->i_opcode)) {
1408
2.16k
            return false;
1409
2.16k
        }
1410
3.98k
        instrs[--size] = instr;
1411
3.98k
    }
1412
1413
2.46k
    return size == 0;
1414
4.63k
}
1415
1416
/*
1417
  Change every instruction in "instrs" NOP and set its location to NO_LOCATION.
1418
  Caller must make sure "instrs" has at least "size" elements.
1419
*/
1420
static void
1421
nop_out(cfg_instr **instrs, int size)
1422
2.58k
{
1423
6.12k
    for (int i = 0; i < size; i++) {
1424
3.53k
        cfg_instr *instr = instrs[i];
1425
3.53k
        assert(instr->i_opcode != NOP);
1426
3.53k
        INSTR_SET_OP0(instr, NOP);
1427
3.53k
        INSTR_SET_LOC(instr, NO_LOCATION);
1428
3.53k
    }
1429
2.58k
}
1430
1431
/* Does not steal reference to "newconst".
1432
   Return 1 if changed instruction to LOAD_SMALL_INT.
1433
   Return 0 if could not change instruction to LOAD_SMALL_INT.
1434
   Return -1 on error.
1435
*/
1436
static int
1437
maybe_instr_make_load_smallint(cfg_instr *instr, PyObject *newconst,
1438
                               PyObject *consts, PyObject *const_cache)
1439
35.4k
{
1440
35.4k
    if (PyLong_CheckExact(newconst)) {
1441
19.4k
        int overflow;
1442
19.4k
        long val = PyLong_AsLongAndOverflow(newconst, &overflow);
1443
19.4k
        if (val == -1 && PyErr_Occurred()) {
1444
0
            return -1;
1445
0
        }
1446
19.4k
        if (!overflow && _PY_IS_SMALL_INT(val) && 0 <= val && val <= 255) {
1447
14.4k
            assert(_Py_IsImmortal(newconst));
1448
14.4k
            INSTR_SET_OP1(instr, LOAD_SMALL_INT, (int)val);
1449
14.4k
            return 1;
1450
14.4k
        }
1451
19.4k
    }
1452
21.0k
    return 0;
1453
35.4k
}
1454
1455
/* Does not steal reference to "newconst".
1456
   Return 1 if changed instruction to LOAD_COMMON_CONSTANT.
1457
   Return 0 if could not change instruction to LOAD_COMMON_CONSTANT.
1458
   Return -1 on error.
1459
*/
1460
static int
1461
maybe_instr_make_load_common_const(cfg_instr *instr, PyObject *newconst)
1462
20.8k
{
1463
20.8k
    int oparg;
1464
20.8k
    if (newconst == Py_None) {
1465
3.48k
        oparg = CONSTANT_NONE;
1466
3.48k
    }
1467
17.3k
    else if (newconst == Py_True) {
1468
256
        oparg = CONSTANT_TRUE;
1469
256
    }
1470
17.0k
    else if (newconst == Py_False) {
1471
407
        oparg = CONSTANT_FALSE;
1472
407
    }
1473
16.6k
    else if (PyUnicode_CheckExact(newconst)
1474
6.33k
             && PyUnicode_GET_LENGTH(newconst) == 0) {
1475
63
        oparg = CONSTANT_EMPTY_STR;
1476
63
    }
1477
16.6k
    else if (PyTuple_CheckExact(newconst)
1478
2.06k
             && PyTuple_GET_SIZE(newconst) == 0) {
1479
579
        oparg = CONSTANT_EMPTY_TUPLE;
1480
579
    }
1481
16.0k
    else if (PyLong_CheckExact(newconst)) {
1482
5.02k
        int overflow;
1483
5.02k
        long val = PyLong_AsLongAndOverflow(newconst, &overflow);
1484
5.02k
        if (val == -1 && PyErr_Occurred()) {
1485
0
            return -1;
1486
0
        }
1487
5.02k
        if (overflow || val != -1) {
1488
4.58k
            return 0;
1489
4.58k
        }
1490
441
        oparg = CONSTANT_MINUS_ONE;
1491
441
    }
1492
10.9k
    else {
1493
10.9k
        return 0;
1494
10.9k
    }
1495
20.8k
    assert(_Py_IsImmortal(newconst));
1496
5.22k
    INSTR_SET_OP1(instr, LOAD_COMMON_CONSTANT, oparg);
1497
5.22k
    return 1;
1498
20.8k
}
1499
1500
/* Steals reference to "newconst" */
1501
static int
1502
instr_make_load_const(cfg_instr *instr, PyObject *newconst,
1503
                      PyObject *consts, PyObject *const_cache,
1504
                      _Py_hashtable_t *consts_index)
1505
2.32k
{
1506
2.32k
    int res = maybe_instr_make_load_smallint(instr, newconst, consts, const_cache);
1507
2.32k
    if (res < 0) {
1508
0
        Py_DECREF(newconst);
1509
0
        return ERROR;
1510
0
    }
1511
2.32k
    if (res > 0) {
1512
3
        return SUCCESS;
1513
3
    }
1514
2.32k
    res = maybe_instr_make_load_common_const(instr, newconst);
1515
2.32k
    if (res < 0) {
1516
0
        Py_DECREF(newconst);
1517
0
        return ERROR;
1518
0
    }
1519
2.32k
    if (res > 0) {
1520
450
        return SUCCESS;
1521
450
    }
1522
1.87k
    int oparg = add_const(newconst, consts, const_cache, consts_index);
1523
1.87k
    RETURN_IF_ERROR(oparg);
1524
1.87k
    INSTR_SET_OP1(instr, LOAD_CONST, oparg);
1525
1.87k
    return SUCCESS;
1526
1.87k
}
1527
1528
/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
1529
   with    LOAD_CONST (c1, c2, ... cn).
1530
   The consts table must still be in list form so that the
1531
   new constant (c1, c2, ... cn) can be appended.
1532
   Called with codestr pointing to the first LOAD_CONST.
1533
*/
1534
static int
1535
fold_tuple_of_constants(basicblock *bb, int i, PyObject *consts,
1536
                        PyObject *const_cache, _Py_hashtable_t *consts_index)
1537
1.75k
{
1538
    /* Pre-conditions */
1539
1.75k
    assert(PyDict_CheckExact(const_cache));
1540
1.75k
    assert(PyList_CheckExact(consts));
1541
1542
1.75k
    cfg_instr *instr = &bb->b_instr[i];
1543
1.75k
    assert(instr->i_opcode == BUILD_TUPLE);
1544
1545
1.75k
    int seq_size = instr->i_oparg;
1546
1.75k
    if (seq_size > _PY_STACK_USE_GUIDELINE) {
1547
0
        return SUCCESS;
1548
0
    }
1549
1550
1.75k
    cfg_instr *const_instrs[_PY_STACK_USE_GUIDELINE];
1551
1.75k
    if (!get_const_loading_instrs(bb, i-1, const_instrs, seq_size)) {
1552
        /* not a const sequence */
1553
1.17k
        return SUCCESS;
1554
1.17k
    }
1555
1556
580
    PyObject *const_tuple = PyTuple_New((Py_ssize_t)seq_size);
1557
580
    if (const_tuple == NULL) {
1558
0
        return ERROR;
1559
0
    }
1560
1561
1.28k
    for (int i = 0; i < seq_size; i++) {
1562
708
        cfg_instr *inst = const_instrs[i];
1563
708
        assert(loads_const(inst->i_opcode));
1564
708
        PyObject *element = get_const_value(inst->i_opcode, inst->i_oparg, consts);
1565
708
        if (element == NULL) {
1566
0
            Py_DECREF(const_tuple);
1567
0
            return ERROR;
1568
0
        }
1569
708
        PyTuple_SET_ITEM(const_tuple, i, element);
1570
708
    }
1571
1572
580
    nop_out(const_instrs, seq_size);
1573
580
    return instr_make_load_const(instr, const_tuple, consts, const_cache, consts_index);
1574
580
}
1575
1576
/* Replace:
1577
    BUILD_LIST/BUILD_SET 0
1578
    LOAD_CONST c1
1579
    LIST_APPEND/SET_ADD 1
1580
    LOAD_CONST c2
1581
    LIST_APPEND/SET_ADD 1
1582
    ...
1583
    LOAD_CONST cN
1584
    LIST_APPEND/SET_ADD 1
1585
    [CALL_INTRINSIC_1 INTRINSIC_LIST_TO_TUPLE]   <-- optional
1586
   with:
1587
    LOAD_CONST (c1, c2, ... cN)
1588
   The instruction at `i` is either the LIST_TO_TUPLE intrinsic (so the
1589
   immediately preceding non-NOP instruction is expected to be a
1590
   LIST_APPEND, and only the BUILD_LIST/LIST_APPEND form is considered),
1591
   or the trailing LIST_APPEND or SET_ADD itself, in which case the
1592
   matching BUILD_LIST/BUILD_SET start is selected from its opcode, and
1593
   for sets the result is wrapped in a frozenset.
1594
*/
1595
static int
1596
fold_constant_seq_into_load_const(basicblock *bb, int i,
1597
                                  PyObject *consts, PyObject *const_cache,
1598
                                  _Py_hashtable_t *consts_index)
1599
41
{
1600
41
    assert(PyDict_CheckExact(const_cache));
1601
41
    assert(PyList_CheckExact(consts));
1602
41
    assert(i >= 0);
1603
41
    assert(i < bb->b_iused);
1604
1605
41
    cfg_instr *target = &bb->b_instr[i];
1606
41
    assert(target->i_opcode == LIST_APPEND || target->i_opcode == SET_ADD ||
1607
41
           (target->i_opcode == CALL_INTRINSIC_1 &&
1608
41
            target->i_oparg == INTRINSIC_LIST_TO_TUPLE));
1609
41
    bool expected_append = target->i_opcode == CALL_INTRINSIC_1;
1610
41
    int append_op = expected_append ? LIST_APPEND : target->i_opcode;
1611
41
    assert(append_op == LIST_APPEND || append_op == SET_ADD);
1612
41
    int build_op = append_op == LIST_APPEND ? BUILD_LIST : BUILD_SET;
1613
41
    int consts_found = 0;
1614
    /* Walking backward from `i`, we expect LIST_APPEND/SET_ADD and
1615
       LOAD_CONST to alternate. If `i` is the trailing LIST_TO_TUPLE
1616
       intrinsic, the next instruction back is an APPEND. If `i` is the
1617
       trailing APPEND itself, the next instruction back is a LOAD_CONST. */
1618
41
    bool expect_append = expected_append;
1619
1620
5.67k
    for (int pos = i - 1; pos >= 0; pos--) {
1621
5.67k
        cfg_instr *instr = &bb->b_instr[pos];
1622
5.67k
        int opcode = instr->i_opcode;
1623
5.67k
        int oparg = instr->i_oparg;
1624
1625
5.67k
        if (opcode == NOP) {
1626
1.66k
            continue;
1627
1.66k
        }
1628
1629
4.01k
        if (opcode == build_op && oparg == 0) {
1630
2
            if (!expect_append) {
1631
                /* Not a sequence start. */
1632
0
                return SUCCESS;
1633
0
            }
1634
1635
            /* Sequence start, we are done. */
1636
2
            PyObject *newconst = PyTuple_New((Py_ssize_t)consts_found);
1637
2
            if (newconst == NULL) {
1638
0
                return ERROR;
1639
0
            }
1640
1641
2
            int newpos_start = expected_append ? i - 1 : i;
1642
128
            for (int newpos = newpos_start; newpos >= pos; newpos--) {
1643
126
                instr = &bb->b_instr[newpos];
1644
126
                if (instr->i_opcode == NOP) {
1645
0
                    continue;
1646
0
                }
1647
126
                if (loads_const(instr->i_opcode)) {
1648
62
                    PyObject *constant = get_const_value(instr->i_opcode, instr->i_oparg, consts);
1649
62
                    if (constant == NULL) {
1650
0
                        Py_DECREF(newconst);
1651
0
                        return ERROR;
1652
0
                    }
1653
62
                    assert(consts_found > 0);
1654
62
                    PyTuple_SET_ITEM(newconst, --consts_found, constant);
1655
62
                }
1656
126
                nop_out(&instr, 1);
1657
126
            }
1658
2
            assert(consts_found == 0);
1659
1660
2
            if (build_op == BUILD_SET) {
1661
2
                PyObject *frozen = PyFrozenSet_New(newconst);
1662
2
                Py_DECREF(newconst);
1663
2
                if (frozen == NULL) {
1664
0
                    return ERROR;
1665
0
                }
1666
2
                newconst = frozen;
1667
2
            }
1668
2
            return instr_make_load_const(target, newconst, consts, const_cache, consts_index);
1669
2
        }
1670
1671
4.01k
        if (expect_append) {
1672
2.02k
            if (opcode != append_op || oparg != 1) {
1673
37
                return SUCCESS;
1674
37
            }
1675
2.02k
        }
1676
1.98k
        else {
1677
1.98k
            if (!loads_const(opcode)) {
1678
2
                return SUCCESS;
1679
2
            }
1680
1.98k
            consts_found++;
1681
1.98k
        }
1682
1683
3.97k
        expect_append = !expect_append;
1684
3.97k
    }
1685
1686
    /* Did not find sequence start. */
1687
0
    return SUCCESS;
1688
41
}
1689
1690
632
#define MIN_CONST_SEQUENCE_SIZE 3
1691
/*
1692
Optimize lists and sets for:
1693
    1. "for" loop, comprehension or "in"/"not in" tests:
1694
           Change literal list or set of constants into constant
1695
           tuple or frozenset respectively. Change list of
1696
           non-constants into tuple.
1697
    2. Constant literal lists/set with length >= MIN_CONST_SEQUENCE_SIZE:
1698
           Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cN, BUILD_LIST N
1699
           with BUILD_LIST 0, LOAD_CONST (c1, c2, ... cN), LIST_EXTEND 1,
1700
           or BUILD_SET & SET_UPDATE respectively.
1701
*/
1702
static int
1703
optimize_lists_and_sets(basicblock *bb, int i, int nextop,
1704
                        PyObject *consts, PyObject *const_cache,
1705
                        _Py_hashtable_t *consts_index)
1706
316
{
1707
316
    assert(PyDict_CheckExact(const_cache));
1708
316
    assert(PyList_CheckExact(consts));
1709
1710
316
    cfg_instr *instr = &bb->b_instr[i];
1711
316
    assert(instr->i_opcode == BUILD_LIST || instr->i_opcode == BUILD_SET);
1712
1713
316
    bool contains_or_iter = nextop == GET_ITER || nextop == CONTAINS_OP;
1714
316
    int seq_size = instr->i_oparg;
1715
316
    if (seq_size > _PY_STACK_USE_GUIDELINE ||
1716
316
        (seq_size < MIN_CONST_SEQUENCE_SIZE && !contains_or_iter))
1717
179
    {
1718
179
        return SUCCESS;
1719
179
    }
1720
1721
137
    cfg_instr *const_instrs[_PY_STACK_USE_GUIDELINE];
1722
137
    if (!get_const_loading_instrs(bb, i-1, const_instrs, seq_size)) {  /* not a const sequence */
1723
4
        if (contains_or_iter && instr->i_opcode == BUILD_LIST) {
1724
            /* iterate over a tuple instead of list */
1725
0
            INSTR_SET_OP1(instr, BUILD_TUPLE, instr->i_oparg);
1726
0
        }
1727
4
        return SUCCESS;
1728
4
    }
1729
1730
133
    PyObject *const_result = PyTuple_New((Py_ssize_t)seq_size);
1731
133
    if (const_result == NULL) {
1732
0
        return ERROR;
1733
0
    }
1734
1735
1.06k
    for (int i = 0; i < seq_size; i++) {
1736
928
        cfg_instr *inst = const_instrs[i];
1737
928
        assert(loads_const(inst->i_opcode));
1738
928
        PyObject *element = get_const_value(inst->i_opcode, inst->i_oparg, consts);
1739
928
        if (element == NULL) {
1740
0
            Py_DECREF(const_result);
1741
0
            return ERROR;
1742
0
        }
1743
928
        PyTuple_SET_ITEM(const_result, i, element);
1744
928
    }
1745
1746
133
    if (instr->i_opcode == BUILD_SET) {
1747
122
        PyObject *frozenset = PyFrozenSet_New(const_result);
1748
122
        if (frozenset == NULL) {
1749
0
            Py_DECREF(const_result);
1750
0
            return ERROR;
1751
0
        }
1752
122
        Py_SETREF(const_result, frozenset);
1753
122
    }
1754
1755
133
    int index = add_const(const_result, consts, const_cache, consts_index);
1756
133
    RETURN_IF_ERROR(index);
1757
133
    nop_out(const_instrs, seq_size);
1758
1759
133
    if (contains_or_iter) {
1760
116
        INSTR_SET_OP1(instr, LOAD_CONST, index);
1761
116
    }
1762
17
    else {
1763
17
        assert(i >= 2);
1764
17
        assert(instr->i_opcode == BUILD_LIST || instr->i_opcode == BUILD_SET);
1765
1766
17
        INSTR_SET_LOC(&bb->b_instr[i-2], instr->i_loc);
1767
1768
17
        INSTR_SET_OP1(&bb->b_instr[i-2], instr->i_opcode, 0);
1769
17
        INSTR_SET_OP1(&bb->b_instr[i-1], LOAD_CONST, index);
1770
17
        INSTR_SET_OP1(&bb->b_instr[i], instr->i_opcode == BUILD_LIST ? LIST_EXTEND : SET_UPDATE, 1);
1771
17
    }
1772
133
    return SUCCESS;
1773
133
}
1774
1775
/* Check whether the total number of items in the (possibly nested) collection obj exceeds
1776
 * limit. Return a negative number if it does, and a non-negative number otherwise.
1777
 * Used to avoid creating constants which are slow to hash.
1778
 */
1779
static Py_ssize_t
1780
const_folding_check_complexity(PyObject *obj, Py_ssize_t limit)
1781
0
{
1782
0
    if (PyTuple_Check(obj)) {
1783
0
        Py_ssize_t i;
1784
0
        limit -= PyTuple_GET_SIZE(obj);
1785
0
        for (i = 0; limit >= 0 && i < PyTuple_GET_SIZE(obj); i++) {
1786
0
            limit = const_folding_check_complexity(PyTuple_GET_ITEM(obj, i), limit);
1787
0
            if (limit < 0) {
1788
0
                return limit;
1789
0
            }
1790
0
        }
1791
0
    }
1792
0
    return limit;
1793
0
}
1794
1795
63
#define MAX_INT_SIZE           128  /* bits */
1796
0
#define MAX_COLLECTION_SIZE    256  /* items */
1797
2
#define MAX_STR_SIZE          4096  /* characters */
1798
0
#define MAX_TOTAL_ITEMS       1024  /* including nested collections */
1799
1800
static PyObject *
1801
const_folding_safe_multiply(PyObject *v, PyObject *w)
1802
6
{
1803
6
    if (PyLong_Check(v) && PyLong_Check(w) &&
1804
2
        !_PyLong_IsZero((PyLongObject *)v) && !_PyLong_IsZero((PyLongObject *)w)
1805
6
    ) {
1806
2
        int64_t vbits = _PyLong_NumBits(v);
1807
2
        int64_t wbits = _PyLong_NumBits(w);
1808
2
        assert(vbits >= 0);
1809
2
        assert(wbits >= 0);
1810
2
        if (vbits + wbits > MAX_INT_SIZE) {
1811
0
            return NULL;
1812
0
        }
1813
2
    }
1814
4
    else if (PyLong_Check(v) && PyTuple_Check(w)) {
1815
0
        Py_ssize_t size = PyTuple_GET_SIZE(w);
1816
0
        if (size) {
1817
0
            long n = PyLong_AsLong(v);
1818
0
            if (n < 0 || n > MAX_COLLECTION_SIZE / size) {
1819
0
                return NULL;
1820
0
            }
1821
0
            if (n && const_folding_check_complexity(w, MAX_TOTAL_ITEMS / n) < 0) {
1822
0
                return NULL;
1823
0
            }
1824
0
        }
1825
0
    }
1826
4
    else if (PyLong_Check(v) && (PyUnicode_Check(w) || PyBytes_Check(w))) {
1827
2
        Py_ssize_t size = PyUnicode_Check(w) ? PyUnicode_GET_LENGTH(w) :
1828
2
                                               PyBytes_GET_SIZE(w);
1829
2
        if (size) {
1830
2
            long n = PyLong_AsLong(v);
1831
2
            if (n < 0 || n > MAX_STR_SIZE / size) {
1832
0
                return NULL;
1833
0
            }
1834
2
        }
1835
2
    }
1836
2
    else if (PyLong_Check(w) &&
1837
2
             (PyTuple_Check(v) || PyUnicode_Check(v) || PyBytes_Check(v)))
1838
2
    {
1839
2
        return const_folding_safe_multiply(w, v);
1840
2
    }
1841
1842
4
    return PyNumber_Multiply(v, w);
1843
6
}
1844
1845
static PyObject *
1846
const_folding_safe_power(PyObject *v, PyObject *w)
1847
1
{
1848
1
    if (PyLong_Check(v) && PyLong_Check(w) &&
1849
1
        !_PyLong_IsZero((PyLongObject *)v) && _PyLong_IsPositive((PyLongObject *)w)
1850
1
    ) {
1851
1
        int64_t vbits = _PyLong_NumBits(v);
1852
1
        size_t wbits = PyLong_AsSize_t(w);
1853
1
        assert(vbits >= 0);
1854
1
        if (wbits == (size_t)-1) {
1855
0
            return NULL;
1856
0
        }
1857
1
        if ((uint64_t)vbits > MAX_INT_SIZE / wbits) {
1858
0
            return NULL;
1859
0
        }
1860
1
    }
1861
1862
1
    return PyNumber_Power(v, w, Py_None);
1863
1
}
1864
1865
static PyObject *
1866
const_folding_safe_lshift(PyObject *v, PyObject *w)
1867
20
{
1868
20
    if (PyLong_Check(v) && PyLong_Check(w) &&
1869
20
        !_PyLong_IsZero((PyLongObject *)v) && !_PyLong_IsZero((PyLongObject *)w)
1870
20
    ) {
1871
20
        int64_t vbits = _PyLong_NumBits(v);
1872
20
        size_t wbits = PyLong_AsSize_t(w);
1873
20
        assert(vbits >= 0);
1874
20
        if (wbits == (size_t)-1) {
1875
0
            return NULL;
1876
0
        }
1877
20
        if (wbits > MAX_INT_SIZE || (uint64_t)vbits > MAX_INT_SIZE - wbits) {
1878
0
            return NULL;
1879
0
        }
1880
20
    }
1881
1882
20
    return PyNumber_Lshift(v, w);
1883
20
}
1884
1885
static PyObject *
1886
const_folding_safe_mod(PyObject *v, PyObject *w)
1887
0
{
1888
0
    if (PyUnicode_Check(v) || PyBytes_Check(v)) {
1889
0
        return NULL;
1890
0
    }
1891
1892
0
    return PyNumber_Remainder(v, w);
1893
0
}
1894
1895
static PyObject *
1896
eval_const_binop(PyObject *left, int op, PyObject *right)
1897
29
{
1898
29
    assert(left != NULL && right != NULL);
1899
29
    assert(op >= 0 && op <= NB_OPARG_LAST);
1900
1901
29
    PyObject *result = NULL;
1902
29
    switch (op) {
1903
0
        case NB_ADD:
1904
0
            result = PyNumber_Add(left, right);
1905
0
            break;
1906
1
        case NB_SUBTRACT:
1907
1
            result = PyNumber_Subtract(left, right);
1908
1
            break;
1909
4
        case NB_MULTIPLY:
1910
4
            result = const_folding_safe_multiply(left, right);
1911
4
            break;
1912
0
        case NB_TRUE_DIVIDE:
1913
0
            result = PyNumber_TrueDivide(left, right);
1914
0
            break;
1915
0
        case NB_FLOOR_DIVIDE:
1916
0
            result = PyNumber_FloorDivide(left, right);
1917
0
            break;
1918
0
        case NB_REMAINDER:
1919
0
            result = const_folding_safe_mod(left, right);
1920
0
            break;
1921
1
        case NB_POWER:
1922
1
            result = const_folding_safe_power(left, right);
1923
1
            break;
1924
20
        case NB_LSHIFT:
1925
20
            result = const_folding_safe_lshift(left, right);
1926
20
            break;
1927
0
        case NB_RSHIFT:
1928
0
            result = PyNumber_Rshift(left, right);
1929
0
            break;
1930
0
        case NB_OR:
1931
0
            result = PyNumber_Or(left, right);
1932
0
            break;
1933
0
        case NB_XOR:
1934
0
            result = PyNumber_Xor(left, right);
1935
0
            break;
1936
0
        case NB_AND:
1937
0
            result = PyNumber_And(left, right);
1938
0
            break;
1939
3
        case NB_SUBSCR:
1940
3
            result = PyObject_GetItem(left, right);
1941
3
            break;
1942
0
        case NB_MATRIX_MULTIPLY:
1943
            // No builtin constants implement matrix multiplication
1944
0
            break;
1945
0
        default:
1946
0
            Py_UNREACHABLE();
1947
29
    }
1948
29
    return result;
1949
29
}
1950
1951
static int
1952
fold_const_binop(basicblock *bb, int i, PyObject *consts,
1953
                 PyObject *const_cache, _Py_hashtable_t *consts_index)
1954
1.02k
{
1955
1.04k
    #define BINOP_OPERAND_COUNT 2
1956
1.02k
    assert(PyDict_CheckExact(const_cache));
1957
1.02k
    assert(PyList_CheckExact(consts));
1958
1959
1.02k
    cfg_instr *binop = &bb->b_instr[i];
1960
1.02k
    assert(binop->i_opcode == BINARY_OP);
1961
1962
1.02k
    cfg_instr *operands_instrs[BINOP_OPERAND_COUNT];
1963
1.02k
    if (!get_const_loading_instrs(bb, i-1, operands_instrs, BINOP_OPERAND_COUNT)) {
1964
        /* not a const sequence */
1965
991
        return SUCCESS;
1966
991
    }
1967
1968
29
    cfg_instr *lhs_instr = operands_instrs[0];
1969
29
    assert(loads_const(lhs_instr->i_opcode));
1970
29
    PyObject *lhs = get_const_value(lhs_instr->i_opcode, lhs_instr->i_oparg, consts);
1971
29
    if (lhs == NULL) {
1972
0
        return ERROR;
1973
0
    }
1974
1975
29
    cfg_instr *rhs_instr = operands_instrs[1];
1976
29
    assert(loads_const(rhs_instr->i_opcode));
1977
29
    PyObject *rhs = get_const_value(rhs_instr->i_opcode, rhs_instr->i_oparg, consts);
1978
29
    if (rhs == NULL) {
1979
0
        Py_DECREF(lhs);
1980
0
        return ERROR;
1981
0
    }
1982
1983
29
    PyObject *newconst = eval_const_binop(lhs, binop->i_oparg, rhs);
1984
29
    Py_DECREF(lhs);
1985
29
    Py_DECREF(rhs);
1986
29
    if (newconst == NULL) {
1987
0
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
1988
0
            return ERROR;
1989
0
        }
1990
0
        PyErr_Clear();
1991
0
        return SUCCESS;
1992
0
    }
1993
1994
29
    nop_out(operands_instrs, BINOP_OPERAND_COUNT);
1995
29
    return instr_make_load_const(binop, newconst, consts, const_cache, consts_index);
1996
29
}
1997
1998
static PyObject *
1999
eval_const_unaryop(PyObject *operand, int opcode, int oparg)
2000
1.71k
{
2001
1.71k
    assert(operand != NULL);
2002
1.71k
    assert(
2003
1.71k
        opcode == UNARY_NEGATIVE ||
2004
1.71k
        opcode == UNARY_INVERT ||
2005
1.71k
        opcode == UNARY_NOT ||
2006
1.71k
        (opcode == CALL_INTRINSIC_1 && oparg == INTRINSIC_UNARY_POSITIVE)
2007
1.71k
    );
2008
1.71k
    PyObject *result;
2009
1.71k
    switch (opcode) {
2010
1.71k
        case UNARY_NEGATIVE:
2011
1.71k
            result = PyNumber_Negative(operand);
2012
1.71k
            break;
2013
0
        case UNARY_INVERT:
2014
            // XXX: This should be removed once the ~bool depreciation expires.
2015
0
            if (PyBool_Check(operand)) {
2016
0
                return NULL;
2017
0
            }
2018
0
            result = PyNumber_Invert(operand);
2019
0
            break;
2020
0
        case UNARY_NOT: {
2021
0
            int r = PyObject_IsTrue(operand);
2022
0
            if (r < 0) {
2023
0
                return NULL;
2024
0
            }
2025
0
            result = PyBool_FromLong(!r);
2026
0
            break;
2027
0
        }
2028
0
        case CALL_INTRINSIC_1:
2029
0
            if (oparg != INTRINSIC_UNARY_POSITIVE) {
2030
0
                Py_UNREACHABLE();
2031
0
            }
2032
0
            result = PyNumber_Positive(operand);
2033
0
            break;
2034
0
        default:
2035
0
            Py_UNREACHABLE();
2036
1.71k
    }
2037
1.71k
    return result;
2038
1.71k
}
2039
2040
static int
2041
fold_const_unaryop(basicblock *bb, int i, PyObject *consts,
2042
                   PyObject *const_cache, _Py_hashtable_t *consts_index)
2043
1.72k
{
2044
3.44k
    #define UNARYOP_OPERAND_COUNT 1
2045
1.72k
    assert(PyDict_CheckExact(const_cache));
2046
1.72k
    assert(PyList_CheckExact(consts));
2047
1.72k
    cfg_instr *unaryop = &bb->b_instr[i];
2048
2049
1.72k
    cfg_instr *operand_instr;
2050
1.72k
    if (!get_const_loading_instrs(bb, i-1, &operand_instr, UNARYOP_OPERAND_COUNT)) {
2051
        /* not a const */
2052
9
        return SUCCESS;
2053
9
    }
2054
2055
1.72k
    assert(loads_const(operand_instr->i_opcode));
2056
1.71k
    PyObject *operand = get_const_value(
2057
1.71k
        operand_instr->i_opcode,
2058
1.71k
        operand_instr->i_oparg,
2059
1.71k
        consts
2060
1.71k
    );
2061
1.71k
    if (operand == NULL) {
2062
0
        return ERROR;
2063
0
    }
2064
2065
1.71k
    PyObject *newconst = eval_const_unaryop(operand, unaryop->i_opcode, unaryop->i_oparg);
2066
1.71k
    Py_DECREF(operand);
2067
1.71k
    if (newconst == NULL) {
2068
0
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
2069
0
            return ERROR;
2070
0
        }
2071
0
        PyErr_Clear();
2072
0
        return SUCCESS;
2073
0
    }
2074
2075
1.71k
    if (unaryop->i_opcode == UNARY_NOT) {
2076
0
        assert(PyBool_Check(newconst));
2077
0
    }
2078
1.71k
    nop_out(&operand_instr, UNARYOP_OPERAND_COUNT);
2079
1.71k
    return instr_make_load_const(unaryop, newconst, consts, const_cache, consts_index);
2080
1.71k
}
2081
2082
1.09k
#define VISITED (-1)
2083
2084
// Replace an arbitrary run of SWAPs and NOPs with an optimal one that has the
2085
// same effect.
2086
static int
2087
swaptimize(basicblock *block, int *ix)
2088
311
{
2089
    // NOTE: "./python -m test test_patma" serves as a good, quick stress test
2090
    // for this function. Make sure to blow away cached *.pyc files first!
2091
311
    assert(*ix < block->b_iused);
2092
311
    cfg_instr *instructions = &block->b_instr[*ix];
2093
    // Find the length of the current sequence of SWAPs and NOPs, and record the
2094
    // maximum depth of the stack manipulations:
2095
311
    assert(instructions[0].i_opcode == SWAP);
2096
311
    int depth = instructions[0].i_oparg;
2097
311
    int len = 0;
2098
311
    int more = false;
2099
311
    int limit = block->b_iused - *ix;
2100
409
    while (++len < limit) {
2101
409
        int opcode = instructions[len].i_opcode;
2102
409
        if (opcode == SWAP) {
2103
84
            depth = Py_MAX(depth, instructions[len].i_oparg);
2104
84
            more = true;
2105
84
        }
2106
325
        else if (opcode != NOP) {
2107
311
            break;
2108
311
        }
2109
409
    }
2110
    // It's already optimal if there's only one SWAP:
2111
311
    if (!more) {
2112
227
        return SUCCESS;
2113
227
    }
2114
    // Create an array with elements {0, 1, 2, ..., depth - 1}:
2115
84
    int *stack = PyMem_Malloc(depth * sizeof(int));
2116
84
    if (stack == NULL) {
2117
0
        PyErr_NoMemory();
2118
0
        return ERROR;
2119
0
    }
2120
336
    for (int i = 0; i < depth; i++) {
2121
252
        stack[i] = i;
2122
252
    }
2123
    // Simulate the combined effect of these instructions by "running" them on
2124
    // our "stack":
2125
252
    for (int i = 0; i < len; i++) {
2126
168
        if (instructions[i].i_opcode == SWAP) {
2127
168
            int oparg = instructions[i].i_oparg;
2128
168
            int top = stack[0];
2129
            // SWAPs are 1-indexed:
2130
168
            stack[0] = stack[oparg - 1];
2131
168
            stack[oparg - 1] = top;
2132
168
        }
2133
168
    }
2134
    // Now we can begin! Our approach here is based on a solution to a closely
2135
    // related problem (https://cs.stackexchange.com/a/13938). It's easiest to
2136
    // think of this algorithm as determining the steps needed to efficiently
2137
    // "un-shuffle" our stack. By performing the moves in *reverse* order,
2138
    // though, we can efficiently *shuffle* it! For this reason, we will be
2139
    // replacing instructions starting from the *end* of the run. Since the
2140
    // solution is optimal, we don't need to worry about running out of space:
2141
84
    int current = len - 1;
2142
336
    for (int i = 0; i < depth; i++) {
2143
        // Skip items that have already been visited, or just happen to be in
2144
        // the correct location:
2145
252
        if (stack[i] == VISITED || stack[i] == i) {
2146
168
            continue;
2147
168
        }
2148
        // Okay, we've found an item that hasn't been visited. It forms a cycle
2149
        // with other items; traversing the cycle and swapping each item with
2150
        // the next will put them all in the correct place. The weird
2151
        // loop-and-a-half is necessary to insert 0 into every cycle, since we
2152
        // can only swap from that position:
2153
84
        int j = i;
2154
336
        while (true) {
2155
            // Skip the actual swap if our item is zero, since swapping the top
2156
            // item with itself is pointless:
2157
336
            if (j) {
2158
168
                assert(0 <= current);
2159
                // SWAPs are 1-indexed:
2160
168
                instructions[current].i_opcode = SWAP;
2161
168
                instructions[current--].i_oparg = j + 1;
2162
168
            }
2163
336
            if (stack[j] == VISITED) {
2164
                // Completed the cycle:
2165
84
                assert(j == i);
2166
84
                break;
2167
84
            }
2168
252
            int next_j = stack[j];
2169
252
            stack[j] = VISITED;
2170
252
            j = next_j;
2171
252
        }
2172
84
    }
2173
    // NOP out any unused instructions:
2174
84
    while (0 <= current) {
2175
0
        INSTR_SET_OP0(&instructions[current--], NOP);
2176
0
    }
2177
84
    PyMem_Free(stack);
2178
84
    *ix += len - 1;
2179
84
    return SUCCESS;
2180
84
}
2181
2182
2183
// This list is pretty small, since it's only okay to reorder opcodes that:
2184
// - can't affect control flow (like jumping or raising exceptions)
2185
// - can't invoke arbitrary code (besides finalizers)
2186
// - only touch the TOS (and pop it when finished)
2187
#define SWAPPABLE(opcode) \
2188
455
    ((opcode) == STORE_FAST || \
2189
455
     (opcode) == STORE_FAST_MAYBE_NULL || \
2190
455
     (opcode) == POP_TOP)
2191
2192
#define STORES_TO(instr) \
2193
65
    (((instr).i_opcode == STORE_FAST || \
2194
65
      (instr).i_opcode == STORE_FAST_MAYBE_NULL) \
2195
65
     ? (instr).i_oparg : -1)
2196
2197
static int
2198
next_swappable_instruction(basicblock *block, int i, int lineno)
2199
447
{
2200
461
    while (++i < block->b_iused) {
2201
456
        cfg_instr *instruction = &block->b_instr[i];
2202
456
        if (0 <= lineno && instruction->i_loc.lineno != lineno) {
2203
            // Optimizing across this instruction could cause user-visible
2204
            // changes in the names bound between line tracing events!
2205
0
            return -1;
2206
0
        }
2207
456
        if (instruction->i_opcode == NOP) {
2208
14
            continue;
2209
14
        }
2210
442
        if (SWAPPABLE(instruction->i_opcode)) {
2211
167
            return i;
2212
167
        }
2213
275
        return -1;
2214
442
    }
2215
5
    return -1;
2216
447
}
2217
2218
// Attempt to apply SWAPs statically by swapping *instructions* rather than
2219
// stack items. For example, we can replace SWAP(2), POP_TOP, STORE_FAST(42)
2220
// with the more efficient NOP, STORE_FAST(42), POP_TOP.
2221
static void
2222
apply_static_swaps(basicblock *block, int i)
2223
311
{
2224
    // SWAPs are to our left, and potential swaperands are to our right:
2225
355
    for (; 0 <= i; i--) {
2226
337
        assert(i < block->b_iused);
2227
337
        cfg_instr *swap = &block->b_instr[i];
2228
337
        if (swap->i_opcode != SWAP) {
2229
26
            if (swap->i_opcode == NOP || SWAPPABLE(swap->i_opcode)) {
2230
                // Nope, but we know how to handle these. Keep looking:
2231
13
                continue;
2232
13
            }
2233
            // We can't reason about what this instruction does. Bail:
2234
13
            return;
2235
26
        }
2236
311
        int j = next_swappable_instruction(block, i, -1);
2237
311
        if (j < 0) {
2238
190
            return;
2239
190
        }
2240
121
        int k = j;
2241
121
        int lineno = block->b_instr[j].i_loc.lineno;
2242
167
        for (int count = swap->i_oparg - 1; 0 < count; count--) {
2243
136
            k = next_swappable_instruction(block, k, lineno);
2244
136
            if (k < 0) {
2245
90
                return;
2246
90
            }
2247
136
        }
2248
        // The reordering is not safe if the two instructions to be swapped
2249
        // store to the same location, or if any intervening instruction stores
2250
        // to the same location as either of them.
2251
31
        int store_j = STORES_TO(block->b_instr[j]);
2252
31
        int store_k = STORES_TO(block->b_instr[k]);
2253
31
        if (store_j >= 0 || store_k >= 0) {
2254
31
            if (store_j == store_k) {
2255
0
                return;
2256
0
            }
2257
34
            for (int idx = j + 1; idx < k; idx++) {
2258
3
                int store_idx = STORES_TO(block->b_instr[idx]);
2259
3
                if (store_idx >= 0 && (store_idx == store_j || store_idx == store_k)) {
2260
0
                    return;
2261
0
                }
2262
3
            }
2263
31
        }
2264
2265
        // Success!
2266
31
        INSTR_SET_OP0(swap, NOP);
2267
31
        cfg_instr temp = block->b_instr[j];
2268
31
        block->b_instr[j] = block->b_instr[k];
2269
31
        block->b_instr[k] = temp;
2270
31
    }
2271
311
}
2272
2273
static int
2274
basicblock_optimize_load_const(PyObject *const_cache, basicblock *bb,
2275
                               PyObject *consts, _Py_hashtable_t *consts_index)
2276
13.5k
{
2277
13.5k
    assert(PyDict_CheckExact(const_cache));
2278
13.5k
    assert(PyList_CheckExact(consts));
2279
13.5k
    int opcode = 0;
2280
13.5k
    int oparg = 0;
2281
154k
    for (int i = 0; i < bb->b_iused; i++) {
2282
141k
        cfg_instr *inst = &bb->b_instr[i];
2283
141k
        if (inst->i_opcode == LOAD_CONST) {
2284
33.1k
            PyObject *constant = get_const_value(inst->i_opcode, inst->i_oparg, consts);
2285
33.1k
            if (constant == NULL) {
2286
0
                return ERROR;
2287
0
            }
2288
33.1k
            int res = maybe_instr_make_load_smallint(inst, constant, consts, const_cache);
2289
33.1k
            Py_DECREF(constant);
2290
33.1k
            if (res < 0) {
2291
0
                return ERROR;
2292
0
            }
2293
33.1k
        }
2294
141k
        bool is_copy_of_load_const = (opcode == LOAD_CONST &&
2295
18.6k
                                      inst->i_opcode == COPY &&
2296
3
                                      inst->i_oparg == 1);
2297
141k
        if (! is_copy_of_load_const) {
2298
141k
            opcode = inst->i_opcode;
2299
141k
            oparg = inst->i_oparg;
2300
141k
        }
2301
141k
        assert(!IS_ASSEMBLER_OPCODE(opcode));
2302
141k
        if (!loads_const(opcode)) {
2303
107k
            continue;
2304
107k
        }
2305
33.2k
        int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
2306
33.2k
        switch(nextop) {
2307
11
            case POP_JUMP_IF_FALSE:
2308
11
            case POP_JUMP_IF_TRUE:
2309
11
            case JUMP_IF_FALSE:
2310
11
            case JUMP_IF_TRUE:
2311
11
            {
2312
                /* Remove LOAD_CONST const; conditional jump */
2313
11
                PyObject* cnt = get_const_value(opcode, oparg, consts);
2314
11
                if (cnt == NULL) {
2315
0
                    return ERROR;
2316
0
                }
2317
11
                int is_true = PyObject_IsTrue(cnt);
2318
11
                Py_DECREF(cnt);
2319
11
                if (is_true == -1) {
2320
0
                    return ERROR;
2321
0
                }
2322
11
                if (PyCompile_OpcodeStackEffect(nextop, 0) == -1) {
2323
                    /* POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE */
2324
11
                    INSTR_SET_OP0(inst, NOP);
2325
11
                }
2326
11
                int jump_if_true = (nextop == POP_JUMP_IF_TRUE || nextop == JUMP_IF_TRUE);
2327
11
                if (is_true == jump_if_true) {
2328
0
                    bb->b_instr[i+1].i_opcode = JUMP;
2329
0
                }
2330
11
                else {
2331
11
                    INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2332
11
                }
2333
11
                break;
2334
11
            }
2335
211
            case IS_OP:
2336
211
            {
2337
                // Fold to POP_JUMP_IF_NONE:
2338
                // - LOAD_CONST(None) IS_OP(0) POP_JUMP_IF_TRUE
2339
                // - LOAD_CONST(None) IS_OP(1) POP_JUMP_IF_FALSE
2340
                // - LOAD_CONST(None) IS_OP(0) TO_BOOL POP_JUMP_IF_TRUE
2341
                // - LOAD_CONST(None) IS_OP(1) TO_BOOL POP_JUMP_IF_FALSE
2342
                // Fold to POP_JUMP_IF_NOT_NONE:
2343
                // - LOAD_CONST(None) IS_OP(0) POP_JUMP_IF_FALSE
2344
                // - LOAD_CONST(None) IS_OP(1) POP_JUMP_IF_TRUE
2345
                // - LOAD_CONST(None) IS_OP(0) TO_BOOL POP_JUMP_IF_FALSE
2346
                // - LOAD_CONST(None) IS_OP(1) TO_BOOL POP_JUMP_IF_TRUE
2347
211
                PyObject *cnt = get_const_value(opcode, oparg, consts);
2348
211
                if (cnt == NULL) {
2349
0
                    return ERROR;
2350
0
                }
2351
211
                if (!Py_IsNone(cnt)) {
2352
18
                    Py_DECREF(cnt);
2353
18
                    break;
2354
18
                }
2355
193
                if (bb->b_iused <= i + 2) {
2356
0
                    break;
2357
0
                }
2358
193
                cfg_instr *is_instr = &bb->b_instr[i + 1];
2359
193
                cfg_instr *jump_instr = &bb->b_instr[i + 2];
2360
                // Get rid of TO_BOOL regardless:
2361
193
                if (jump_instr->i_opcode == TO_BOOL) {
2362
191
                    INSTR_SET_OP0(jump_instr, NOP);
2363
191
                    if (bb->b_iused <= i + 3) {
2364
0
                        break;
2365
0
                    }
2366
191
                    jump_instr = &bb->b_instr[i + 3];
2367
191
                }
2368
193
                bool invert = is_instr->i_oparg;
2369
193
                if (jump_instr->i_opcode == POP_JUMP_IF_FALSE) {
2370
184
                    invert = !invert;
2371
184
                }
2372
9
                else if (jump_instr->i_opcode != POP_JUMP_IF_TRUE) {
2373
2
                    break;
2374
2
                }
2375
191
                INSTR_SET_OP0(inst, NOP);
2376
191
                INSTR_SET_OP0(is_instr, NOP);
2377
191
                jump_instr->i_opcode = invert ? POP_JUMP_IF_NOT_NONE
2378
191
                                              : POP_JUMP_IF_NONE;
2379
191
                break;
2380
193
            }
2381
11
            case TO_BOOL:
2382
11
            {
2383
11
                PyObject *cnt = get_const_value(opcode, oparg, consts);
2384
11
                if (cnt == NULL) {
2385
0
                    return ERROR;
2386
0
                }
2387
11
                int is_true = PyObject_IsTrue(cnt);
2388
11
                Py_DECREF(cnt);
2389
11
                if (is_true == -1) {
2390
0
                    return ERROR;
2391
0
                }
2392
11
                cnt = PyBool_FromLong(is_true);
2393
11
                int index = add_const(cnt, consts, const_cache, consts_index);
2394
11
                if (index < 0) {
2395
0
                    return ERROR;
2396
0
                }
2397
11
                INSTR_SET_OP0(inst, NOP);
2398
11
                INSTR_SET_OP1(&bb->b_instr[i + 1], LOAD_CONST, index);
2399
11
                break;
2400
11
            }
2401
33.2k
        }
2402
33.2k
        if (inst->i_opcode == LOAD_CONST) {
2403
18.4k
            PyObject *constant = get_const_value(inst->i_opcode, inst->i_oparg, consts);
2404
18.4k
            if (constant == NULL) {
2405
0
                return ERROR;
2406
0
            }
2407
18.4k
            int res = maybe_instr_make_load_common_const(inst, constant);
2408
18.4k
            Py_DECREF(constant);
2409
18.4k
            if (res < 0) {
2410
0
                return ERROR;
2411
0
            }
2412
18.4k
        }
2413
33.2k
    }
2414
13.5k
    return SUCCESS;
2415
13.5k
}
2416
2417
static int
2418
optimize_load_const(PyObject *const_cache, cfg_builder *g, PyObject *consts,
2419
3.84k
                    _Py_hashtable_t *consts_index) {
2420
17.4k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
2421
13.5k
        RETURN_IF_ERROR(basicblock_optimize_load_const(const_cache, b, consts, consts_index));
2422
13.5k
    }
2423
3.84k
    return SUCCESS;
2424
3.84k
}
2425
2426
static int
2427
optimize_basic_block(PyObject *const_cache, basicblock *bb, PyObject *consts,
2428
                     _Py_hashtable_t *consts_index)
2429
13.5k
{
2430
13.5k
    assert(PyDict_CheckExact(const_cache));
2431
13.5k
    assert(PyList_CheckExact(consts));
2432
13.5k
    cfg_instr nop;
2433
13.5k
    INSTR_SET_OP0(&nop, NOP);
2434
154k
    for (int i = 0; i < bb->b_iused; i++) {
2435
141k
        cfg_instr *inst = &bb->b_instr[i];
2436
141k
        cfg_instr *target;
2437
141k
        int opcode = inst->i_opcode;
2438
141k
        int oparg = inst->i_oparg;
2439
141k
        if (HAS_TARGET(opcode)) {
2440
4.70k
            assert(inst->i_target->b_iused > 0);
2441
4.70k
            target = &inst->i_target->b_instr[0];
2442
4.70k
            assert(!IS_ASSEMBLER_OPCODE(target->i_opcode));
2443
4.70k
        }
2444
136k
        else {
2445
136k
            target = &nop;
2446
136k
        }
2447
141k
        int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
2448
141k
        assert(!IS_ASSEMBLER_OPCODE(opcode));
2449
141k
        switch (opcode) {
2450
            /* Try to fold tuples of constants.
2451
               Skip over BUILD_TUPLE(1) UNPACK_SEQUENCE(1).
2452
               Replace BUILD_TUPLE(2) UNPACK_SEQUENCE(2) with SWAP(2).
2453
               Replace BUILD_TUPLE(3) UNPACK_SEQUENCE(3) with SWAP(3). */
2454
1.76k
            case BUILD_TUPLE:
2455
1.76k
                if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
2456
15
                    switch(oparg) {
2457
0
                        case 1:
2458
0
                            INSTR_SET_OP0(inst, NOP);
2459
0
                            INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2460
0
                            continue;
2461
15
                        case 2:
2462
15
                        case 3:
2463
15
                            INSTR_SET_OP0(inst, NOP);
2464
15
                            bb->b_instr[i+1].i_opcode = SWAP;
2465
15
                            continue;
2466
15
                    }
2467
15
                }
2468
1.75k
                RETURN_IF_ERROR(fold_tuple_of_constants(bb, i, consts, const_cache, consts_index));
2469
1.75k
                break;
2470
184
            case BUILD_LIST:
2471
316
            case BUILD_SET:
2472
316
                RETURN_IF_ERROR(optimize_lists_and_sets(bb, i, nextop, consts, const_cache, consts_index));
2473
316
                break;
2474
88
            case POP_JUMP_IF_NOT_NONE:
2475
196
            case POP_JUMP_IF_NONE:
2476
196
                switch (target->i_opcode) {
2477
5
                    case JUMP:
2478
5
                        i -= jump_thread(bb, inst, target, inst->i_opcode);
2479
196
                }
2480
196
                break;
2481
1.72k
            case POP_JUMP_IF_FALSE:
2482
1.72k
                switch (target->i_opcode) {
2483
87
                    case JUMP:
2484
87
                        i -= jump_thread(bb, inst, target, POP_JUMP_IF_FALSE);
2485
1.72k
                }
2486
1.72k
                break;
2487
1.72k
            case POP_JUMP_IF_TRUE:
2488
465
                switch (target->i_opcode) {
2489
12
                    case JUMP:
2490
12
                        i -= jump_thread(bb, inst, target, POP_JUMP_IF_TRUE);
2491
465
                }
2492
465
                break;
2493
502
            case JUMP_IF_FALSE:
2494
502
                switch (target->i_opcode) {
2495
0
                    case JUMP:
2496
0
                    case JUMP_IF_FALSE:
2497
0
                        i -= jump_thread(bb, inst, target, JUMP_IF_FALSE);
2498
0
                        continue;
2499
2
                    case JUMP_IF_TRUE:
2500
                        // No need to check for loops here, a block's b_next
2501
                        // cannot point to itself.
2502
2
                        assert(inst->i_target != inst->i_target->b_next);
2503
2
                        inst->i_target = inst->i_target->b_next;
2504
2
                        i--;
2505
2
                        continue;
2506
502
                }
2507
500
                break;
2508
500
            case JUMP_IF_TRUE:
2509
23
                switch (target->i_opcode) {
2510
0
                    case JUMP:
2511
0
                    case JUMP_IF_TRUE:
2512
0
                        i -= jump_thread(bb, inst, target, JUMP_IF_TRUE);
2513
0
                        continue;
2514
0
                    case JUMP_IF_FALSE:
2515
                        // No need to check for loops here, a block's b_next
2516
                        // cannot point to itself.
2517
0
                        assert(inst->i_target != inst->i_target->b_next);
2518
0
                        inst->i_target = inst->i_target->b_next;
2519
0
                        i--;
2520
0
                        continue;
2521
23
                }
2522
23
                break;
2523
459
            case JUMP:
2524
883
            case JUMP_NO_INTERRUPT:
2525
883
                switch (target->i_opcode) {
2526
0
                    case JUMP:
2527
0
                        i -= jump_thread(bb, inst, target, JUMP);
2528
0
                        continue;
2529
0
                    case JUMP_NO_INTERRUPT:
2530
0
                        i -= jump_thread(bb, inst, target, opcode);
2531
0
                        continue;
2532
883
                }
2533
883
                break;
2534
883
            case FOR_ITER:
2535
246
                if (target->i_opcode == JUMP) {
2536
                    /* This will not work now because the jump (at target) could
2537
                     * be forward or backward and FOR_ITER only jumps forward. We
2538
                     * can re-enable this if ever we implement a backward version
2539
                     * of FOR_ITER.
2540
                     */
2541
                    /*
2542
                    i -= jump_thread(bb, inst, target, FOR_ITER);
2543
                    */
2544
0
                }
2545
246
                break;
2546
2.58k
            case STORE_FAST:
2547
2.58k
                if (opcode == nextop &&
2548
149
                    oparg == bb->b_instr[i+1].i_oparg &&
2549
0
                    bb->b_instr[i].i_loc.lineno == bb->b_instr[i+1].i_loc.lineno) {
2550
0
                    bb->b_instr[i].i_opcode = POP_TOP;
2551
0
                    bb->b_instr[i].i_oparg = 0;
2552
0
                }
2553
2.58k
                break;
2554
395
            case SWAP:
2555
395
                if (oparg == 1) {
2556
0
                    INSTR_SET_OP0(inst, NOP);
2557
0
                }
2558
395
                break;
2559
4.96k
            case LOAD_GLOBAL:
2560
4.96k
                if (nextop == PUSH_NULL && (oparg & 1) == 0) {
2561
1.80k
                    INSTR_SET_OP1(inst, LOAD_GLOBAL, oparg | 1);
2562
1.80k
                    INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2563
1.80k
                }
2564
4.96k
                break;
2565
1.51k
            case COMPARE_OP:
2566
1.51k
                if (nextop == TO_BOOL) {
2567
434
                    INSTR_SET_OP0(inst, NOP);
2568
434
                    INSTR_SET_OP1(&bb->b_instr[i + 1], COMPARE_OP, oparg | 16);
2569
434
                    continue;
2570
434
                }
2571
1.07k
                break;
2572
1.07k
            case CONTAINS_OP:
2573
1.23k
            case IS_OP:
2574
1.23k
                if (nextop == TO_BOOL) {
2575
608
                    INSTR_SET_OP0(inst, NOP);
2576
608
                    INSTR_SET_OP1(&bb->b_instr[i + 1], opcode, oparg);
2577
608
                    continue;
2578
608
                }
2579
628
                if (nextop == UNARY_NOT) {
2580
0
                    INSTR_SET_OP0(inst, NOP);
2581
0
                    int inverted = oparg ^ 1;
2582
0
                    assert(inverted == 0 || inverted == 1);
2583
0
                    INSTR_SET_OP1(&bb->b_instr[i + 1], opcode, inverted);
2584
0
                    continue;
2585
0
                }
2586
628
                break;
2587
858
            case TO_BOOL:
2588
858
                if (nextop == TO_BOOL) {
2589
0
                    INSTR_SET_OP0(inst, NOP);
2590
0
                    continue;
2591
0
                }
2592
858
                break;
2593
858
            case UNARY_NOT:
2594
6
                if (nextop == TO_BOOL) {
2595
0
                    INSTR_SET_OP0(inst, NOP);
2596
0
                    INSTR_SET_OP0(&bb->b_instr[i + 1], UNARY_NOT);
2597
0
                    continue;
2598
0
                }
2599
6
                if (nextop == UNARY_NOT) {
2600
0
                    INSTR_SET_OP0(inst, NOP);
2601
0
                    INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2602
0
                    continue;
2603
0
                }
2604
6
                _Py_FALLTHROUGH;
2605
6
            case UNARY_INVERT:
2606
1.72k
            case UNARY_NEGATIVE:
2607
1.72k
                RETURN_IF_ERROR(fold_const_unaryop(bb, i, consts, const_cache, consts_index));
2608
1.72k
                break;
2609
104
            case CALL_INTRINSIC_1:
2610
104
                if (oparg == INTRINSIC_LIST_TO_TUPLE) {
2611
39
                    RETURN_IF_ERROR(fold_constant_seq_into_load_const(bb, i, consts, const_cache, consts_index));
2612
39
                    if (inst->i_opcode == CALL_INTRINSIC_1 && nextop == GET_ITER) {
2613
0
                        INSTR_SET_OP0(inst, NOP);
2614
0
                    }
2615
39
                }
2616
65
                else if (oparg == INTRINSIC_UNARY_POSITIVE) {
2617
0
                    RETURN_IF_ERROR(fold_const_unaryop(bb, i, consts, const_cache, consts_index));
2618
0
                }
2619
104
                break;
2620
2.12k
            case LIST_APPEND:
2621
2.18k
            case SET_ADD:
2622
2.18k
                if (oparg == 1 && (nextop == GET_ITER || nextop == CONTAINS_OP)) {
2623
2
                    RETURN_IF_ERROR(fold_constant_seq_into_load_const(
2624
2
                        bb, i, consts, const_cache, consts_index));
2625
2
                }
2626
2.18k
                break;
2627
2.18k
            case BINARY_OP:
2628
1.02k
                RETURN_IF_ERROR(fold_const_binop(bb, i, consts, const_cache, consts_index));
2629
1.02k
                break;
2630
141k
        }
2631
141k
    }
2632
2633
154k
    for (int i = 0; i < bb->b_iused; i++) {
2634
141k
        cfg_instr *inst = &bb->b_instr[i];
2635
141k
        if (inst->i_opcode == SWAP) {
2636
311
            if (swaptimize(bb, &i) < 0) {
2637
0
                goto error;
2638
0
            }
2639
311
            apply_static_swaps(bb, i);
2640
311
        }
2641
141k
    }
2642
13.5k
    return SUCCESS;
2643
0
error:
2644
0
    return ERROR;
2645
13.5k
}
2646
2647
static int resolve_line_numbers(cfg_builder *g, int firstlineno);
2648
2649
static int
2650
remove_redundant_nops_and_jumps(cfg_builder *g)
2651
7.94k
{
2652
7.94k
    int removed_nops, removed_jumps;
2653
8.33k
    do {
2654
        /* Convergence is guaranteed because the number of
2655
         * redundant jumps and nops only decreases.
2656
         */
2657
8.33k
        removed_nops = remove_redundant_nops(g);
2658
8.33k
        RETURN_IF_ERROR(removed_nops);
2659
8.33k
        removed_jumps = remove_redundant_jumps(g);
2660
8.33k
        RETURN_IF_ERROR(removed_jumps);
2661
8.33k
    } while(removed_nops + removed_jumps > 0);
2662
7.94k
    return SUCCESS;
2663
7.94k
}
2664
2665
/* Perform optimizations on a control flow graph.
2666
   The consts object should still be in list form to allow new constants
2667
   to be appended.
2668
2669
   Code trasnformations that reduce code size initially fill the gaps with
2670
   NOPs.  Later those NOPs are removed.
2671
*/
2672
static int
2673
optimize_cfg(cfg_builder *g, PyObject *consts, PyObject *const_cache,
2674
             _Py_hashtable_t *consts_index, int firstlineno)
2675
3.84k
{
2676
3.84k
    assert(PyDict_CheckExact(const_cache));
2677
3.84k
    RETURN_IF_ERROR(check_cfg(g));
2678
3.84k
    RETURN_IF_ERROR(inline_small_or_no_lineno_blocks(g->g_entryblock));
2679
3.84k
    RETURN_IF_ERROR(remove_unreachable(g->g_entryblock));
2680
3.84k
    RETURN_IF_ERROR(resolve_line_numbers(g, firstlineno));
2681
3.84k
    RETURN_IF_ERROR(optimize_load_const(const_cache, g, consts, consts_index));
2682
17.4k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
2683
13.5k
        RETURN_IF_ERROR(optimize_basic_block(const_cache, b, consts, consts_index));
2684
13.5k
    }
2685
3.84k
    RETURN_IF_ERROR(remove_redundant_nops_and_pairs(g->g_entryblock));
2686
3.84k
    RETURN_IF_ERROR(remove_unreachable(g->g_entryblock));
2687
3.84k
    RETURN_IF_ERROR(remove_redundant_nops_and_jumps(g));
2688
3.84k
    assert(no_redundant_jumps(g));
2689
3.84k
    return SUCCESS;
2690
3.84k
}
2691
2692
static void
2693
make_super_instruction(cfg_instr *inst1, cfg_instr *inst2, int super_op)
2694
2.78k
{
2695
2.78k
    int32_t line1 = inst1->i_loc.lineno;
2696
2.78k
    int32_t line2 = inst2->i_loc.lineno;
2697
    /* Skip if instructions are on different lines */
2698
2.78k
    if (line1 >= 0 && line2 >= 0 && line1 != line2) {
2699
111
        return;
2700
111
    }
2701
2.67k
    if (inst1->i_oparg >= 16 || inst2->i_oparg >= 16) {
2702
96
        return;
2703
96
    }
2704
2.57k
    INSTR_SET_OP1(inst1, super_op, (inst1->i_oparg << 4) | inst2->i_oparg);
2705
2.57k
    INSTR_SET_OP0(inst2, NOP);
2706
2.57k
}
2707
2708
static int
2709
insert_superinstructions(cfg_builder *g)
2710
3.84k
{
2711
17.5k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
2712
2713
150k
        for (int i = 0; i < b->b_iused; i++) {
2714
136k
            cfg_instr *inst = &b->b_instr[i];
2715
136k
            int nextop = i+1 < b->b_iused ? b->b_instr[i+1].i_opcode : 0;
2716
136k
            switch(inst->i_opcode) {
2717
579
                case LOAD_FAST:
2718
579
                    if (nextop == LOAD_FAST) {
2719
55
                        make_super_instruction(inst, &b->b_instr[i + 1], LOAD_FAST_LOAD_FAST);
2720
55
                    }
2721
579
                    break;
2722
13.8k
                case LOAD_FAST_BORROW:
2723
13.8k
                    if (nextop == LOAD_FAST_BORROW) {
2724
2.50k
                        make_super_instruction(inst, &b->b_instr[i + 1],
2725
2.50k
                                               LOAD_FAST_BORROW_LOAD_FAST_BORROW);
2726
2.50k
                    }
2727
13.8k
                    break;
2728
2.51k
                case STORE_FAST:
2729
2.51k
                    switch (nextop) {
2730
70
                        case LOAD_FAST:
2731
70
                            make_super_instruction(inst, &b->b_instr[i + 1], STORE_FAST_LOAD_FAST);
2732
70
                            break;
2733
152
                        case STORE_FAST:
2734
152
                            make_super_instruction(inst, &b->b_instr[i + 1], STORE_FAST_STORE_FAST);
2735
152
                            break;
2736
2.51k
                    }
2737
2.51k
                    break;
2738
136k
            }
2739
136k
        }
2740
13.6k
    }
2741
3.84k
    RETURN_IF_ERROR(remove_redundant_nops(g));
2742
3.84k
    assert(no_redundant_nops(g));
2743
3.84k
    return SUCCESS;
2744
3.84k
}
2745
2746
#define NOT_LOCAL -1
2747
2.46k
#define DUMMY_INSTR -1
2748
2749
typedef struct {
2750
    // Index of instruction that produced the reference or DUMMY_INSTR.
2751
    int instr;
2752
2753
    // The local to which the reference refers or NOT_LOCAL.
2754
    int local;
2755
} ref;
2756
2757
typedef struct {
2758
    ref *refs;
2759
    Py_ssize_t size;
2760
    Py_ssize_t capacity;
2761
} ref_stack;
2762
2763
static int
2764
ref_stack_push(ref_stack *stack, ref r)
2765
104k
{
2766
104k
    if (stack->size == stack->capacity) {
2767
3.84k
        Py_ssize_t new_cap = Py_MAX(32, stack->capacity * 2);
2768
3.84k
        ref *refs = PyMem_Realloc(stack->refs, sizeof(*stack->refs) * new_cap);
2769
3.84k
        if (refs == NULL) {
2770
0
            PyErr_NoMemory();
2771
0
            return -1;
2772
0
        }
2773
3.84k
        stack->refs = refs;
2774
3.84k
        stack->capacity = new_cap;
2775
3.84k
    }
2776
104k
    stack->refs[stack->size] = r;
2777
104k
    stack->size++;
2778
104k
    return 0;
2779
104k
}
2780
2781
static ref
2782
ref_stack_pop(ref_stack *stack)
2783
95.3k
{
2784
95.3k
    assert(stack->size > 0);
2785
95.3k
    stack->size--;
2786
95.3k
    ref r = stack->refs[stack->size];
2787
95.3k
    return r;
2788
95.3k
}
2789
2790
static void
2791
ref_stack_swap_top(ref_stack *stack, Py_ssize_t off)
2792
284
{
2793
284
    Py_ssize_t idx = stack->size - off;
2794
284
    assert(idx >= 0 && idx < stack->size);
2795
284
    ref tmp = stack->refs[idx];
2796
284
    stack->refs[idx] = stack->refs[stack->size - 1];
2797
284
    stack->refs[stack->size - 1] = tmp;
2798
284
}
2799
2800
static ref
2801
ref_stack_at(ref_stack *stack, Py_ssize_t idx)
2802
11.9k
{
2803
11.9k
    assert(idx >= 0 && idx < stack->size);
2804
11.9k
    return stack->refs[idx];
2805
11.9k
}
2806
2807
static void
2808
ref_stack_clear(ref_stack *stack)
2809
9.58k
{
2810
9.58k
    stack->size = 0;
2811
9.58k
}
2812
2813
static void
2814
ref_stack_fini(ref_stack *stack)
2815
3.84k
{
2816
3.84k
    if (stack->refs != NULL) {
2817
3.84k
        PyMem_Free(stack->refs);
2818
3.84k
    }
2819
3.84k
    stack->refs = NULL;
2820
3.84k
    stack->capacity = 0;
2821
3.84k
    stack->size = 0;
2822
3.84k
}
2823
2824
typedef enum {
2825
    // The loaded reference is still on the stack when the local is killed
2826
    SUPPORT_KILLED  = 1,
2827
    // The loaded reference is stored into a local
2828
    STORED_AS_LOCAL = 2,
2829
    // The loaded reference is still on the stack at the end of the basic block
2830
    REF_UNCONSUMED  = 4,
2831
} LoadFastInstrFlag;
2832
2833
static void
2834
kill_local(uint8_t *instr_flags, ref_stack *refs, int local)
2835
2.50k
{
2836
4.11k
    for (Py_ssize_t i = 0; i < refs->size; i++) {
2837
1.61k
        ref r = ref_stack_at(refs, i);
2838
1.61k
        if (r.local == local) {
2839
4
            assert(r.instr >= 0);
2840
4
            instr_flags[r.instr] |= SUPPORT_KILLED;
2841
4
        }
2842
1.61k
    }
2843
2.50k
}
2844
2845
static void
2846
store_local(uint8_t *instr_flags, ref_stack *refs, int local, ref r)
2847
2.46k
{
2848
2.46k
    kill_local(instr_flags, refs, local);
2849
2.46k
    if (r.instr != DUMMY_INSTR) {
2850
2.20k
        instr_flags[r.instr] |= STORED_AS_LOCAL;
2851
2.20k
    }
2852
2.46k
}
2853
2854
static void
2855
load_fast_push_block(basicblock ***sp, basicblock *target,
2856
                     Py_ssize_t start_depth)
2857
7.47k
{
2858
7.47k
    assert(target->b_startdepth >= 0 && target->b_startdepth == start_depth);
2859
7.47k
    if (!target->b_visited) {
2860
5.73k
        target->b_visited = 1;
2861
5.73k
        *(*sp)++ = target;
2862
5.73k
    }
2863
7.47k
}
2864
2865
/*
2866
 * Strength reduce LOAD_FAST{_LOAD_FAST} instructions into faster variants that
2867
 * load borrowed references onto the operand stack.
2868
 *
2869
 * This is only safe when we can prove that the reference in the frame outlives
2870
 * the borrowed reference produced by the instruction. We make this tractable
2871
 * by enforcing the following lifetimes:
2872
 *
2873
 * 1. Borrowed references loaded onto the operand stack live until the end of
2874
 *    the instruction that consumes them from the stack. Any borrowed
2875
 *    references that would escape into the heap (e.g. into frame objects or
2876
 *    generators) are converted into new, strong references.
2877
 *
2878
 * 2. Locals live until they are either killed by an instruction
2879
 *    (e.g. STORE_FAST) or the frame is unwound. Any local that is overwritten
2880
 *    via `f_locals` is added to a tuple owned by the frame object.
2881
 *
2882
 * To simplify the problem of detecting which supporting references in the
2883
 * frame are killed by instructions that overwrite locals, we only allow
2884
 * borrowed references to be stored as a local in the frame if they were passed
2885
 * as an argument. {RETURN,YIELD}_VALUE convert borrowed references into new,
2886
 * strong references.
2887
 *
2888
 * Using the above, we can optimize any LOAD_FAST{_LOAD_FAST} instructions
2889
 * that meet the following criteria:
2890
 *
2891
 * 1. The produced reference must be consumed from the stack before the
2892
 *    supporting reference in the frame is killed.
2893
 *
2894
 * 2. The produced reference cannot be stored as a local.
2895
 *
2896
 * We use abstract interpretation to identify instructions that meet these
2897
 * criteria. For each basic block, we simulate the effect the bytecode has on a
2898
 * stack of abstract references and note any instructions that violate the
2899
 * criteria above. Once we've processed all the instructions in a block, any
2900
 * non-violating LOAD_FAST{_LOAD_FAST} can be optimized.
2901
 */
2902
static int
2903
optimize_load_fast(cfg_builder *g)
2904
3.84k
{
2905
3.84k
    int status;
2906
3.84k
    ref_stack refs = {0};
2907
3.84k
    int max_instrs = 0;
2908
3.84k
    basicblock *entryblock = g->g_entryblock;
2909
17.5k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
2910
13.6k
        max_instrs = Py_MAX(max_instrs, b->b_iused);
2911
13.6k
    }
2912
3.84k
    size_t instr_flags_size = max_instrs * sizeof(uint8_t);
2913
3.84k
    uint8_t *instr_flags = PyMem_Malloc(instr_flags_size);
2914
3.84k
    if (instr_flags == NULL) {
2915
0
        PyErr_NoMemory();
2916
0
        return ERROR;
2917
0
    }
2918
3.84k
    basicblock **blocks = make_cfg_traversal_stack(entryblock);
2919
3.84k
    if (blocks == NULL) {
2920
0
        status = ERROR;
2921
0
        goto done;
2922
0
    }
2923
3.84k
    basicblock **sp = blocks;
2924
3.84k
    *sp = entryblock;
2925
3.84k
    sp++;
2926
3.84k
    entryblock->b_startdepth = 0;
2927
3.84k
    entryblock->b_visited = 1;
2928
2929
3.84k
    #define PUSH_REF(instr, local)                \
2930
104k
        do {                                      \
2931
104k
            if (ref_stack_push(&refs, (ref){(instr), (local)}) < 0) { \
2932
0
                status = ERROR;                   \
2933
0
                goto done;                        \
2934
0
            }                                     \
2935
104k
        } while(0)
2936
2937
13.4k
    while (sp != blocks) {
2938
9.58k
        basicblock *block = *--sp;
2939
9.58k
        assert(block->b_startdepth > -1);
2940
2941
        // Reset per-block state.
2942
9.58k
        memset(instr_flags, 0, block->b_iused * sizeof(*instr_flags));
2943
2944
        // Reset the stack of refs. We don't track references on the stack
2945
        // across basic blocks, but the bytecode will expect their
2946
        // presence. Add dummy references as necessary.
2947
9.58k
        ref_stack_clear(&refs);
2948
14.9k
        for (int i = 0; i < block->b_startdepth; i++) {
2949
5.33k
            PUSH_REF(DUMMY_INSTR, NOT_LOCAL);
2950
5.33k
        }
2951
2952
140k
        for (int i = 0; i < block->b_iused; i++) {
2953
130k
            cfg_instr *instr = &block->b_instr[i];
2954
130k
            int opcode = instr->i_opcode;
2955
130k
            int oparg = instr->i_oparg;
2956
130k
            assert(opcode != EXTENDED_ARG);
2957
130k
            switch (opcode) {
2958
                // Opcodes that load and store locals
2959
0
                case DELETE_FAST: {
2960
0
                    kill_local(instr_flags, &refs, oparg);
2961
0
                    break;
2962
0
                }
2963
2964
16.4k
                case LOAD_FAST: {
2965
16.4k
                    PUSH_REF(i, oparg);
2966
16.4k
                    break;
2967
16.4k
                }
2968
2969
16.4k
                case LOAD_FAST_AND_CLEAR: {
2970
35
                    kill_local(instr_flags, &refs, oparg);
2971
35
                    PUSH_REF(i, oparg);
2972
35
                    break;
2973
35
                }
2974
2975
35
                case LOAD_FAST_LOAD_FAST: {
2976
0
                    PUSH_REF(i, oparg >> 4);
2977
0
                    PUSH_REF(i, oparg & 15);
2978
0
                    break;
2979
0
                }
2980
2981
2.46k
                case STORE_FAST: {
2982
2.46k
                    ref r = ref_stack_pop(&refs);
2983
2.46k
                    store_local(instr_flags, &refs, oparg, r);
2984
2.46k
                    break;
2985
0
                }
2986
2987
0
                case STORE_FAST_LOAD_FAST: {
2988
                    // STORE_FAST
2989
0
                    ref r = ref_stack_pop(&refs);
2990
0
                    store_local(instr_flags, &refs, oparg >> 4, r);
2991
                    // LOAD_FAST
2992
0
                    PUSH_REF(i, oparg & 15);
2993
0
                    break;
2994
0
                }
2995
2996
0
                case STORE_FAST_STORE_FAST: {
2997
                    // STORE_FAST
2998
0
                    ref r = ref_stack_pop(&refs);
2999
0
                    store_local(instr_flags, &refs, oparg >> 4, r);
3000
                    // STORE_FAST
3001
0
                    r = ref_stack_pop(&refs);
3002
0
                    store_local(instr_flags, &refs, oparg & 15, r);
3003
0
                    break;
3004
0
                }
3005
3006
                // Opcodes that shuffle values on the stack
3007
691
                case COPY: {
3008
691
                    assert(oparg > 0);
3009
691
                    Py_ssize_t idx = refs.size - oparg;
3010
691
                    ref r = ref_stack_at(&refs, idx);
3011
691
                    PUSH_REF(r.instr, r.local);
3012
691
                    break;
3013
691
                }
3014
3015
691
                case SWAP: {
3016
284
                    assert(oparg >= 2);
3017
284
                    ref_stack_swap_top(&refs, oparg);
3018
284
                    break;
3019
691
                }
3020
3021
                // We treat opcodes that do not consume all of their inputs on
3022
                // a case by case basis, as we have no generic way of knowing
3023
                // how many inputs should be left on the stack.
3024
3025
                // Opcodes that consume no inputs
3026
1.10k
                case FORMAT_SIMPLE:
3027
1.10k
                case GET_ANEXT:
3028
1.35k
                case GET_ITER:
3029
1.35k
                case GET_LEN:
3030
2.04k
                case IMPORT_FROM:
3031
2.04k
                case MATCH_KEYS:
3032
2.04k
                case MATCH_MAPPING:
3033
2.04k
                case MATCH_SEQUENCE:
3034
2.04k
                case WITH_EXCEPT_START: {
3035
2.04k
                    int num_popped = _PyOpcode_num_popped(opcode, oparg);
3036
2.04k
                    int num_pushed = _PyOpcode_num_pushed(opcode, oparg);
3037
2.04k
                    int net_pushed = num_pushed - num_popped;
3038
2.04k
                    assert(net_pushed >= 0);
3039
2.98k
                    for (int j = 0; j < net_pushed; j++) {
3040
941
                        PUSH_REF(i, NOT_LOCAL);
3041
941
                    }
3042
2.04k
                    break;
3043
2.04k
                }
3044
3045
                // Opcodes that consume some inputs and push no new values
3046
2.04k
                case DICT_MERGE:
3047
396
                case DICT_UPDATE:
3048
2.51k
                case LIST_APPEND:
3049
2.56k
                case LIST_EXTEND:
3050
8.96k
                case MAP_ADD:
3051
8.96k
                case RERAISE:
3052
8.96k
                case SET_ADD:
3053
8.96k
                case SET_UPDATE: {
3054
8.96k
                    int num_popped = _PyOpcode_num_popped(opcode, oparg);
3055
8.96k
                    int num_pushed = _PyOpcode_num_pushed(opcode, oparg);
3056
8.96k
                    int net_popped = num_popped - num_pushed;
3057
8.96k
                    assert(net_popped > 0);
3058
24.3k
                    for (int i = 0; i < net_popped; i++) {
3059
15.3k
                        ref_stack_pop(&refs);
3060
15.3k
                    }
3061
8.96k
                    break;
3062
8.96k
                }
3063
3064
9
                case END_SEND: {
3065
9
                    assert(_PyOpcode_num_popped(opcode, oparg) == 3);
3066
9
                    assert(_PyOpcode_num_pushed(opcode, oparg) == 1);
3067
9
                    ref tos = ref_stack_pop(&refs);
3068
9
                    ref_stack_pop(&refs);
3069
9
                    ref_stack_pop(&refs);
3070
9
                    PUSH_REF(tos.instr, tos.local);
3071
9
                    break;
3072
9
                }
3073
3074
1.19k
                case SET_FUNCTION_ATTRIBUTE: {
3075
1.19k
                    assert(_PyOpcode_num_popped(opcode, oparg) == 2);
3076
1.19k
                    assert(_PyOpcode_num_pushed(opcode, oparg) == 1);
3077
1.19k
                    ref tos = ref_stack_pop(&refs);
3078
1.19k
                    ref_stack_pop(&refs);
3079
1.19k
                    PUSH_REF(tos.instr, tos.local);
3080
1.19k
                    break;
3081
1.19k
                }
3082
3083
                // Opcodes that consume some inputs and push new values
3084
1.19k
                case CHECK_EXC_MATCH: {
3085
0
                    ref_stack_pop(&refs);
3086
0
                    PUSH_REF(i, NOT_LOCAL);
3087
0
                    break;
3088
0
                }
3089
3090
244
                case FOR_ITER: {
3091
244
                    load_fast_push_block(&sp, instr->i_target, refs.size + 1);
3092
244
                    PUSH_REF(i, NOT_LOCAL);
3093
244
                    break;
3094
244
                }
3095
3096
8.98k
                case LOAD_ATTR:
3097
9.11k
                case LOAD_SUPER_ATTR: {
3098
9.11k
                    ref self = ref_stack_pop(&refs);
3099
9.11k
                    if (opcode == LOAD_SUPER_ATTR) {
3100
134
                        ref_stack_pop(&refs);
3101
134
                        ref_stack_pop(&refs);
3102
134
                    }
3103
9.11k
                    PUSH_REF(i, NOT_LOCAL);
3104
9.11k
                    if (oparg & 1) {
3105
                        // A method call; conservatively assume that self is pushed
3106
                        // back onto the stack
3107
2.49k
                        PUSH_REF(self.instr, self.local);
3108
2.49k
                    }
3109
9.11k
                    break;
3110
9.11k
                }
3111
3112
9.11k
                case LOAD_SPECIAL:
3113
164
                case PUSH_EXC_INFO: {
3114
164
                    ref tos = ref_stack_pop(&refs);
3115
164
                    PUSH_REF(i, NOT_LOCAL);
3116
164
                    PUSH_REF(tos.instr, tos.local);
3117
164
                    break;
3118
164
                }
3119
3120
164
                case SEND: {
3121
9
                    load_fast_push_block(&sp, instr->i_target, refs.size);
3122
9
                    ref_stack_pop(&refs);
3123
9
                    PUSH_REF(i, NOT_LOCAL);
3124
9
                    break;
3125
9
                }
3126
3127
                // Opcodes that consume all of their inputs
3128
89.2k
                default: {
3129
89.2k
                    int num_popped = _PyOpcode_num_popped(opcode, oparg);
3130
89.2k
                    int num_pushed = _PyOpcode_num_pushed(opcode, oparg);
3131
89.2k
                    if (HAS_TARGET(instr->i_opcode)) {
3132
3.16k
                        load_fast_push_block(&sp, instr->i_target, refs.size - num_popped + num_pushed);
3133
3.16k
                    }
3134
89.2k
                    if (!IS_BLOCK_PUSH_OPCODE(instr->i_opcode)) {
3135
                        // Block push opcodes only affect the stack when jumping
3136
                        // to the target.
3137
154k
                        for (int j = 0; j < num_popped; j++) {
3138
65.5k
                            ref_stack_pop(&refs);
3139
65.5k
                        }
3140
157k
                        for (int j = 0; j < num_pushed; j++) {
3141
68.0k
                            PUSH_REF(i, NOT_LOCAL);
3142
68.0k
                        }
3143
89.2k
                    }
3144
89.2k
                    break;
3145
89.2k
                }
3146
130k
            }
3147
130k
        }
3148
3149
        // Push fallthrough block
3150
9.58k
        if (BB_HAS_FALLTHROUGH(block)) {
3151
4.06k
            assert(block->b_next != NULL);
3152
4.06k
            load_fast_push_block(&sp, block->b_next, refs.size);
3153
4.06k
        }
3154
3155
        // Mark instructions that produce values that are on the stack at the
3156
        // end of the basic block
3157
19.1k
        for (Py_ssize_t i = 0; i < refs.size; i++) {
3158
9.59k
            ref r = ref_stack_at(&refs, i);
3159
9.59k
            if (r.instr != -1) {
3160
6.40k
                instr_flags[r.instr] |= REF_UNCONSUMED;
3161
6.40k
            }
3162
9.59k
        }
3163
3164
        // Optimize instructions
3165
140k
        for (int i = 0; i < block->b_iused; i++) {
3166
130k
            if (!instr_flags[i]) {
3167
122k
                cfg_instr *instr = &block->b_instr[i];
3168
122k
                switch (instr->i_opcode) {
3169
16.1k
                    case LOAD_FAST:
3170
16.1k
                        instr->i_opcode = LOAD_FAST_BORROW;
3171
16.1k
                        break;
3172
0
                    case LOAD_FAST_LOAD_FAST:
3173
0
                        instr->i_opcode = LOAD_FAST_BORROW_LOAD_FAST_BORROW;
3174
0
                        break;
3175
106k
                    default:
3176
106k
                        break;
3177
122k
                }
3178
122k
            }
3179
130k
        }
3180
9.58k
    }
3181
3182
3.84k
    #undef PUSH_REF
3183
3184
3.84k
    status = SUCCESS;
3185
3186
3.84k
done:
3187
3.84k
    ref_stack_fini(&refs);
3188
3.84k
    PyMem_Free(instr_flags);
3189
3.84k
    PyMem_Free(blocks);
3190
3.84k
    return status;
3191
3.84k
}
3192
3193
// helper functions for add_checks_for_loads_of_unknown_variables
3194
static inline void
3195
maybe_push(basicblock *b, uint64_t unsafe_mask, basicblock ***sp)
3196
31.6k
{
3197
    // Push b if the unsafe mask is giving us any new information.
3198
    // To avoid overflowing the stack, only allow each block once.
3199
    // Use b->b_visited=1 to mean that b is currently on the stack.
3200
31.6k
    uint64_t both = b->b_unsafe_locals_mask | unsafe_mask;
3201
31.6k
    if (b->b_unsafe_locals_mask != both) {
3202
4.28k
        b->b_unsafe_locals_mask = both;
3203
        // More work left to do.
3204
4.28k
        if (!b->b_visited) {
3205
            // not on the stack, so push it.
3206
4.24k
            *(*sp)++ = b;
3207
4.24k
            b->b_visited = 1;
3208
4.24k
        }
3209
4.28k
    }
3210
31.6k
}
3211
3212
static void
3213
scan_block_for_locals(basicblock *b, basicblock ***sp)
3214
15.4k
{
3215
    // bit i is set if local i is potentially uninitialized
3216
15.4k
    uint64_t unsafe_mask = b->b_unsafe_locals_mask;
3217
125k
    for (int i = 0; i < b->b_iused; i++) {
3218
110k
        cfg_instr *instr = &b->b_instr[i];
3219
110k
        assert(instr->i_opcode != EXTENDED_ARG);
3220
110k
        if (instr->i_except != NULL) {
3221
16.8k
            maybe_push(instr->i_except, unsafe_mask, sp);
3222
16.8k
        }
3223
110k
        if (instr->i_oparg >= 64) {
3224
4.72k
            continue;
3225
4.72k
        }
3226
110k
        assert(instr->i_oparg >= 0);
3227
105k
        uint64_t bit = (uint64_t)1 << instr->i_oparg;
3228
105k
        switch (instr->i_opcode) {
3229
110
            case DELETE_FAST:
3230
180
            case LOAD_FAST_AND_CLEAR:
3231
320
            case STORE_FAST_MAYBE_NULL:
3232
320
                unsafe_mask |= bit;
3233
320
                break;
3234
5.01k
            case STORE_FAST:
3235
5.01k
                unsafe_mask &= ~bit;
3236
5.01k
                break;
3237
24
            case LOAD_FAST_CHECK:
3238
                // If this doesn't raise, then the local is defined.
3239
24
                unsafe_mask &= ~bit;
3240
24
                break;
3241
22.1k
            case LOAD_FAST:
3242
22.1k
                if (unsafe_mask & bit) {
3243
24
                    instr->i_opcode = LOAD_FAST_CHECK;
3244
24
                }
3245
22.1k
                unsafe_mask &= ~bit;
3246
22.1k
                break;
3247
105k
        }
3248
105k
    }
3249
15.4k
    if (b->b_next && BB_HAS_FALLTHROUGH(b)) {
3250
6.65k
        maybe_push(b->b_next, unsafe_mask, sp);
3251
6.65k
    }
3252
15.4k
    cfg_instr *last = basicblock_last_instr(b);
3253
15.4k
    if (last && is_jump(last)) {
3254
5.88k
        assert(last->i_target != NULL);
3255
5.88k
        maybe_push(last->i_target, unsafe_mask, sp);
3256
5.88k
    }
3257
15.4k
}
3258
3259
static int
3260
fast_scan_many_locals(basicblock *entryblock, int nlocals)
3261
0
{
3262
0
    assert(nlocals > 64);
3263
0
    Py_ssize_t *states = PyMem_Calloc(nlocals - 64, sizeof(Py_ssize_t));
3264
0
    if (states == NULL) {
3265
0
        PyErr_NoMemory();
3266
0
        return ERROR;
3267
0
    }
3268
0
    Py_ssize_t blocknum = 0;
3269
    // state[i - 64] == blocknum if local i is guaranteed to
3270
    // be initialized, i.e., if it has had a previous LOAD_FAST or
3271
    // STORE_FAST within that basicblock (not followed by
3272
    // DELETE_FAST/LOAD_FAST_AND_CLEAR/STORE_FAST_MAYBE_NULL).
3273
0
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3274
0
        blocknum++;
3275
0
        for (int i = 0; i < b->b_iused; i++) {
3276
0
            cfg_instr *instr = &b->b_instr[i];
3277
0
            assert(instr->i_opcode != EXTENDED_ARG);
3278
0
            int arg = instr->i_oparg;
3279
0
            if (arg < 64) {
3280
0
                continue;
3281
0
            }
3282
0
            assert(arg >= 0);
3283
0
            switch (instr->i_opcode) {
3284
0
                case DELETE_FAST:
3285
0
                case LOAD_FAST_AND_CLEAR:
3286
0
                case STORE_FAST_MAYBE_NULL:
3287
0
                    states[arg - 64] = blocknum - 1;
3288
0
                    break;
3289
0
                case STORE_FAST:
3290
0
                    states[arg - 64] = blocknum;
3291
0
                    break;
3292
0
                case LOAD_FAST:
3293
0
                    if (states[arg - 64] != blocknum) {
3294
0
                        instr->i_opcode = LOAD_FAST_CHECK;
3295
0
                    }
3296
0
                    states[arg - 64] = blocknum;
3297
0
                    break;
3298
0
                    Py_UNREACHABLE();
3299
0
            }
3300
0
        }
3301
0
    }
3302
0
    PyMem_Free(states);
3303
0
    return SUCCESS;
3304
0
}
3305
3306
static int
3307
remove_unused_consts(basicblock *entryblock, PyObject *consts)
3308
3.84k
{
3309
3.84k
    assert(PyList_CheckExact(consts));
3310
3.84k
    Py_ssize_t nconsts = PyList_GET_SIZE(consts);
3311
3.84k
    if (nconsts == 0) {
3312
4
        return SUCCESS;  /* nothing to do */
3313
4
    }
3314
3315
3.84k
    Py_ssize_t *index_map = NULL;
3316
3.84k
    Py_ssize_t *reverse_index_map = NULL;
3317
3.84k
    int err = ERROR;
3318
3319
3.84k
    index_map = PyMem_Malloc(nconsts * sizeof(Py_ssize_t));
3320
3.84k
    if (index_map == NULL) {
3321
0
        PyErr_NoMemory();
3322
0
        goto end;
3323
0
    }
3324
23.6k
    for (Py_ssize_t i = 1; i < nconsts; i++) {
3325
19.8k
        index_map[i] = -1;
3326
19.8k
    }
3327
    // The first constant may be docstring; keep it always.
3328
3.84k
    index_map[0] = 0;
3329
3330
    /* mark used consts */
3331
17.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3332
145k
        for (int i = 0; i < b->b_iused; i++) {
3333
131k
            int opcode = b->b_instr[i].i_opcode;
3334
131k
            if (OPCODE_HAS_CONST(opcode)) {
3335
14.4k
                int index = b->b_instr[i].i_oparg;
3336
14.4k
                index_map[index] = index;
3337
14.4k
            }
3338
131k
        }
3339
13.5k
    }
3340
    /* now index_map[i] == i if consts[i] is used, -1 otherwise */
3341
    /* condense consts */
3342
3.84k
    Py_ssize_t n_used_consts = 0;
3343
27.5k
    for (Py_ssize_t i = 0; i < nconsts; i++) {
3344
23.6k
        if (index_map[i] != -1) {
3345
13.1k
            assert(index_map[i] == i);
3346
13.1k
            index_map[n_used_consts++] = index_map[i];
3347
13.1k
        }
3348
23.6k
    }
3349
3.84k
    if (n_used_consts == nconsts) {
3350
        /* nothing to do */
3351
914
        err = SUCCESS;
3352
914
        goto end;
3353
914
    }
3354
3355
    /* move all used consts to the beginning of the consts list */
3356
3.84k
    assert(n_used_consts < nconsts);
3357
15.0k
    for (Py_ssize_t i = 0; i < n_used_consts; i++) {
3358
12.1k
        Py_ssize_t old_index = index_map[i];
3359
12.1k
        assert(i <= old_index && old_index < nconsts);
3360
12.1k
        if (i != old_index) {
3361
6.21k
            PyObject *value = PyList_GET_ITEM(consts, index_map[i]);
3362
6.21k
            assert(value != NULL);
3363
6.21k
            PyList_SetItem(consts, i, Py_NewRef(value));
3364
6.21k
        }
3365
12.1k
    }
3366
3367
    /* truncate the consts list at its new size */
3368
2.92k
    if (PyList_SetSlice(consts, n_used_consts, nconsts, NULL) < 0) {
3369
0
        goto end;
3370
0
    }
3371
    /* adjust const indices in the bytecode */
3372
2.92k
    reverse_index_map = PyMem_Malloc(nconsts * sizeof(Py_ssize_t));
3373
2.92k
    if (reverse_index_map == NULL) {
3374
0
        PyErr_NoMemory();
3375
0
        goto end;
3376
0
    }
3377
25.6k
    for (Py_ssize_t i = 0; i < nconsts; i++) {
3378
22.7k
        reverse_index_map[i] = -1;
3379
22.7k
    }
3380
15.0k
    for (Py_ssize_t i = 0; i < n_used_consts; i++) {
3381
12.1k
        assert(index_map[i] != -1);
3382
12.1k
        assert(reverse_index_map[index_map[i]] == -1);
3383
12.1k
        reverse_index_map[index_map[i]] = i;
3384
12.1k
    }
3385
3386
14.2k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3387
132k
        for (int i = 0; i < b->b_iused; i++) {
3388
120k
            int opcode = b->b_instr[i].i_opcode;
3389
120k
            if (OPCODE_HAS_CONST(opcode)) {
3390
14.1k
                int index = b->b_instr[i].i_oparg;
3391
14.1k
                assert(reverse_index_map[index] >= 0);
3392
14.1k
                assert(reverse_index_map[index] < n_used_consts);
3393
14.1k
                b->b_instr[i].i_oparg = (int)reverse_index_map[index];
3394
14.1k
            }
3395
120k
        }
3396
11.3k
    }
3397
3398
2.92k
    err = SUCCESS;
3399
3.84k
end:
3400
3.84k
    PyMem_Free(index_map);
3401
3.84k
    PyMem_Free(reverse_index_map);
3402
3.84k
    return err;
3403
2.92k
}
3404
3405
3406
3407
static int
3408
add_checks_for_loads_of_uninitialized_variables(basicblock *entryblock,
3409
                                                int nlocals,
3410
                                                int nparams)
3411
3.84k
{
3412
3.84k
    if (nlocals == 0) {
3413
1.50k
        return SUCCESS;
3414
1.50k
    }
3415
2.34k
    if (nlocals > 64) {
3416
        // To avoid O(nlocals**2) compilation, locals beyond the first
3417
        // 64 are only analyzed one basicblock at a time: initialization
3418
        // info is not passed between basicblocks.
3419
0
        if (fast_scan_many_locals(entryblock, nlocals) < 0) {
3420
0
            return ERROR;
3421
0
        }
3422
0
        nlocals = 64;
3423
0
    }
3424
2.34k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
3425
2.34k
    if (stack == NULL) {
3426
0
        return ERROR;
3427
0
    }
3428
2.34k
    basicblock **sp = stack;
3429
3430
    // First origin of being uninitialized:
3431
    // The non-parameter locals in the entry block.
3432
2.34k
    uint64_t start_mask = 0;
3433
4.25k
    for (int i = nparams; i < nlocals; i++) {
3434
1.90k
        start_mask |= (uint64_t)1 << i;
3435
1.90k
    }
3436
2.34k
    maybe_push(entryblock, start_mask, &sp);
3437
3438
    // Second origin of being uninitialized:
3439
    // There could be DELETE_FAST somewhere, so
3440
    // be sure to scan each basicblock at least once.
3441
13.5k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3442
11.2k
        scan_block_for_locals(b, &sp);
3443
11.2k
    }
3444
    // Now propagate the uncertainty from the origins we found: Use
3445
    // LOAD_FAST_CHECK for any LOAD_FAST where the local could be undefined.
3446
6.58k
    while (sp > stack) {
3447
4.24k
        basicblock *b = *--sp;
3448
        // mark as no longer on stack
3449
4.24k
        b->b_visited = 0;
3450
4.24k
        scan_block_for_locals(b, &sp);
3451
4.24k
    }
3452
2.34k
    PyMem_Free(stack);
3453
2.34k
    return SUCCESS;
3454
2.34k
}
3455
3456
3457
static int
3458
2.90k
mark_warm(basicblock *entryblock) {
3459
2.90k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
3460
2.90k
    if (stack == NULL) {
3461
0
        return ERROR;
3462
0
    }
3463
2.90k
    basicblock **sp = stack;
3464
3465
2.90k
    *sp++ = entryblock;
3466
2.90k
    entryblock->b_visited = 1;
3467
11.3k
    while (sp > stack) {
3468
8.46k
        basicblock *b = *(--sp);
3469
8.46k
        assert(!b->b_except_handler);
3470
8.46k
        b->b_warm = 1;
3471
8.46k
        basicblock *next = b->b_next;
3472
8.46k
        if (next && BB_HAS_FALLTHROUGH(b) && !next->b_visited) {
3473
3.29k
            *sp++ = next;
3474
3.29k
            next->b_visited = 1;
3475
3.29k
        }
3476
92.8k
        for (int i=0; i < b->b_iused; i++) {
3477
84.4k
            cfg_instr *instr = &b->b_instr[i];
3478
84.4k
            if (is_jump(instr) && !instr->i_target->b_visited) {
3479
2.26k
                *sp++ = instr->i_target;
3480
2.26k
                instr->i_target->b_visited = 1;
3481
2.26k
            }
3482
84.4k
        }
3483
8.46k
    }
3484
2.90k
    PyMem_Free(stack);
3485
2.90k
    return SUCCESS;
3486
2.90k
}
3487
3488
static int
3489
2.90k
mark_cold(basicblock *entryblock) {
3490
15.5k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3491
12.6k
        assert(!b->b_cold && !b->b_warm);
3492
12.6k
    }
3493
2.90k
    if (mark_warm(entryblock) < 0) {
3494
0
        return ERROR;
3495
0
    }
3496
3497
2.90k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
3498
2.90k
    if (stack == NULL) {
3499
0
        return ERROR;
3500
0
    }
3501
3502
2.90k
    basicblock **sp = stack;
3503
15.5k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3504
12.6k
        if (b->b_except_handler) {
3505
657
            assert(!b->b_warm);
3506
657
            *sp++ = b;
3507
657
            b->b_visited = 1;
3508
657
        }
3509
12.6k
    }
3510
3511
4.18k
    while (sp > stack) {
3512
1.27k
        basicblock *b = *(--sp);
3513
1.27k
        b->b_cold = 1;
3514
1.27k
        basicblock *next = b->b_next;
3515
1.27k
        if (next && BB_HAS_FALLTHROUGH(b)) {
3516
329
            if (!next->b_warm && !next->b_visited) {
3517
313
                *sp++ = next;
3518
313
                next->b_visited = 1;
3519
313
            }
3520
329
        }
3521
6.92k
        for (int i = 0; i < b->b_iused; i++) {
3522
5.64k
            cfg_instr *instr = &b->b_instr[i];
3523
5.64k
            if (is_jump(instr)) {
3524
417
                assert(i == b->b_iused - 1);
3525
417
                basicblock *target = b->b_instr[i].i_target;
3526
417
                if (!target->b_warm && !target->b_visited) {
3527
308
                    *sp++ = target;
3528
308
                    target->b_visited = 1;
3529
308
                }
3530
417
            }
3531
5.64k
        }
3532
1.27k
    }
3533
2.90k
    PyMem_Free(stack);
3534
2.90k
    return SUCCESS;
3535
2.90k
}
3536
3537
3538
static int
3539
3.84k
push_cold_blocks_to_end(cfg_builder *g) {
3540
3.84k
    basicblock *entryblock = g->g_entryblock;
3541
3.84k
    if (entryblock->b_next == NULL) {
3542
        /* single basicblock, no need to reorder */
3543
945
        return SUCCESS;
3544
945
    }
3545
2.90k
    RETURN_IF_ERROR(mark_cold(entryblock));
3546
3547
2.90k
    int next_lbl = get_max_label(g->g_entryblock) + 1;
3548
3549
    /* If we have a cold block with fallthrough to a warm block, add */
3550
    /* an explicit jump instead of fallthrough */
3551
15.5k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3552
12.6k
        if (b->b_cold && BB_HAS_FALLTHROUGH(b) && b->b_next && b->b_next->b_warm) {
3553
9
            basicblock *explicit_jump = cfg_builder_new_block(g);
3554
9
            if (explicit_jump == NULL) {
3555
0
                return ERROR;
3556
0
            }
3557
9
            if (!IS_LABEL(b->b_next->b_label)) {
3558
0
                b->b_next->b_label.id = next_lbl++;
3559
0
            }
3560
9
            RETURN_IF_ERROR(
3561
9
                basicblock_addop(explicit_jump, JUMP_NO_INTERRUPT,
3562
9
                                 b->b_next->b_label.id, NO_LOCATION, NULL));
3563
9
            explicit_jump->b_cold = 1;
3564
9
            explicit_jump->b_next = b->b_next;
3565
9
            explicit_jump->b_predecessors = 1;
3566
9
            b->b_next = explicit_jump;
3567
3568
            /* set target */
3569
9
            cfg_instr *last = basicblock_last_instr(explicit_jump);
3570
9
            last->i_target = explicit_jump->b_next;
3571
9
        }
3572
12.6k
    }
3573
3574
2.90k
    assert(!entryblock->b_cold);  /* First block can't be cold */
3575
2.90k
    basicblock *cold_blocks = NULL;
3576
2.90k
    basicblock *cold_blocks_tail = NULL;
3577
3578
2.90k
    basicblock *b = entryblock;
3579
3.37k
    while(b->b_next) {
3580
3.37k
        assert(!b->b_cold);
3581
11.8k
        while (b->b_next && !b->b_next->b_cold) {
3582
8.43k
            b = b->b_next;
3583
8.43k
        }
3584
3.37k
        if (b->b_next == NULL) {
3585
            /* no more cold blocks */
3586
2.90k
            break;
3587
2.90k
        }
3588
3589
        /* b->b_next is the beginning of a cold streak */
3590
3.37k
        assert(!b->b_cold && b->b_next->b_cold);
3591
3592
472
        basicblock *b_end = b->b_next;
3593
1.28k
        while (b_end->b_next && b_end->b_next->b_cold) {
3594
815
            b_end = b_end->b_next;
3595
815
        }
3596
3597
        /* b_end is the end of the cold streak */
3598
472
        assert(b_end && b_end->b_cold);
3599
472
        assert(b_end->b_next == NULL || !b_end->b_next->b_cold);
3600
3601
472
        if (cold_blocks == NULL) {
3602
246
            cold_blocks = b->b_next;
3603
246
        }
3604
226
        else {
3605
226
            cold_blocks_tail->b_next = b->b_next;
3606
226
        }
3607
472
        cold_blocks_tail = b_end;
3608
472
        b->b_next = b_end->b_next;
3609
472
        b_end->b_next = NULL;
3610
472
    }
3611
2.90k
    assert(b != NULL && b->b_next == NULL);
3612
2.90k
    b->b_next = cold_blocks;
3613
3614
2.90k
    if (cold_blocks != NULL) {
3615
246
        RETURN_IF_ERROR(remove_redundant_nops_and_jumps(g));
3616
246
    }
3617
2.90k
    return SUCCESS;
3618
2.90k
}
3619
3620
static int
3621
convert_pseudo_conditional_jumps(cfg_builder *g)
3622
3.84k
{
3623
3.84k
    basicblock *entryblock = g->g_entryblock;
3624
17.4k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3625
145k
        for (int i = 0; i < b->b_iused; i++) {
3626
131k
            cfg_instr *instr = &b->b_instr[i];
3627
131k
            if (instr->i_opcode == JUMP_IF_FALSE || instr->i_opcode == JUMP_IF_TRUE) {
3628
523
                assert(i == b->b_iused - 1);
3629
523
                instr->i_opcode = instr->i_opcode == JUMP_IF_FALSE ?
3630
500
                                          POP_JUMP_IF_FALSE : POP_JUMP_IF_TRUE;
3631
523
                location loc = instr->i_loc;
3632
523
                basicblock *except = instr->i_except;
3633
523
                cfg_instr copy = {
3634
523
                            .i_opcode = COPY,
3635
523
                            .i_oparg = 1,
3636
523
                            .i_loc = loc,
3637
523
                            .i_target = NULL,
3638
523
                            .i_except = except,
3639
523
                };
3640
523
                RETURN_IF_ERROR(basicblock_insert_instruction(b, i++, &copy));
3641
523
                cfg_instr to_bool = {
3642
523
                            .i_opcode = TO_BOOL,
3643
523
                            .i_oparg = 0,
3644
523
                            .i_loc = loc,
3645
523
                            .i_target = NULL,
3646
523
                            .i_except = except,
3647
523
                };
3648
523
                RETURN_IF_ERROR(basicblock_insert_instruction(b, i++, &to_bool));
3649
523
            }
3650
131k
        }
3651
13.5k
    }
3652
3.84k
    return SUCCESS;
3653
3.84k
}
3654
3655
static int
3656
convert_pseudo_ops(cfg_builder *g)
3657
3.84k
{
3658
3.84k
    basicblock *entryblock = g->g_entryblock;
3659
17.4k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3660
147k
        for (int i = 0; i < b->b_iused; i++) {
3661
134k
            cfg_instr *instr = &b->b_instr[i];
3662
134k
            if (is_block_push(instr)) {
3663
657
                INSTR_SET_OP0(instr, NOP);
3664
657
            }
3665
133k
            else if (instr->i_opcode == LOAD_CLOSURE) {
3666
995
                assert(is_pseudo_target(LOAD_CLOSURE, LOAD_FAST));
3667
995
                instr->i_opcode = LOAD_FAST;
3668
995
            }
3669
132k
            else if (instr->i_opcode == STORE_FAST_MAYBE_NULL) {
3670
70
                assert(is_pseudo_target(STORE_FAST_MAYBE_NULL, STORE_FAST));
3671
70
                instr->i_opcode = STORE_FAST;
3672
70
            }
3673
134k
        }
3674
13.5k
    }
3675
3.84k
    return remove_redundant_nops_and_jumps(g);
3676
3.84k
}
3677
3678
static inline bool
3679
16.1k
is_exit_or_eval_check_without_lineno(basicblock *b) {
3680
16.1k
    if (basicblock_exits_scope(b) || basicblock_has_eval_break(b)) {
3681
9.87k
        return basicblock_has_no_lineno(b);
3682
9.87k
    }
3683
6.32k
    else {
3684
6.32k
        return false;
3685
6.32k
    }
3686
16.1k
}
3687
3688
3689
/* PEP 626 mandates that the f_lineno of a frame is correct
3690
 * after a frame terminates. It would be prohibitively expensive
3691
 * to continuously update the f_lineno field at runtime,
3692
 * so we make sure that all exiting instruction (raises and returns)
3693
 * have a valid line number, allowing us to compute f_lineno lazily.
3694
 * We can do this by duplicating the exit blocks without line number
3695
 * so that none have more than one predecessor. We can then safely
3696
 * copy the line number from the sole predecessor block.
3697
 */
3698
static int
3699
duplicate_exits_without_lineno(cfg_builder *g)
3700
7.69k
{
3701
7.69k
    int next_lbl = get_max_label(g->g_entryblock) + 1;
3702
3703
    /* Copy all exit blocks without line number that are targets of a jump.
3704
     */
3705
7.69k
    basicblock *entryblock = g->g_entryblock;
3706
34.8k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3707
27.1k
        cfg_instr *last = basicblock_last_instr(b);
3708
27.1k
        if (last == NULL) {
3709
5.65k
            continue;
3710
5.65k
        }
3711
21.4k
        if (is_jump(last)) {
3712
7.68k
            basicblock *target = next_nonempty_block(last->i_target);
3713
7.68k
            if (is_exit_or_eval_check_without_lineno(target) && target->b_predecessors > 1) {
3714
177
                basicblock *new_target = copy_basicblock(g, target);
3715
177
                if (new_target == NULL) {
3716
0
                    return ERROR;
3717
0
                }
3718
177
                new_target->b_instr[0].i_loc = last->i_loc;
3719
177
                last->i_target = new_target;
3720
177
                target->b_predecessors--;
3721
177
                new_target->b_predecessors = 1;
3722
177
                new_target->b_next = target->b_next;
3723
177
                new_target->b_label.id = next_lbl++;
3724
177
                target->b_next = new_target;
3725
177
            }
3726
7.68k
        }
3727
21.4k
    }
3728
3729
    /* Any remaining reachable exit blocks without line number can only be reached by
3730
     * fall through, and thus can only have a single predecessor */
3731
34.8k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3732
27.1k
        if (BB_HAS_FALLTHROUGH(b) && b->b_next && b->b_iused > 0) {
3733
8.51k
            if (is_exit_or_eval_check_without_lineno(b->b_next)) {
3734
282
                cfg_instr *last = basicblock_last_instr(b);
3735
282
                assert(last != NULL);
3736
282
                b->b_next->b_instr[0].i_loc = last->i_loc;
3737
282
            }
3738
8.51k
        }
3739
27.1k
    }
3740
7.69k
    return SUCCESS;
3741
7.69k
}
3742
3743
3744
/* If an instruction has no line number, but it's predecessor in the BB does,
3745
 * then copy the line number. If a successor block has no line number, and only
3746
 * one predecessor, then inherit the line number.
3747
 * This ensures that all exit blocks (with one predecessor) receive a line number.
3748
 * Also reduces the size of the line number table,
3749
 * but has no impact on the generated line number events.
3750
 */
3751
3752
static inline void
3753
maybe_propagate_location(basicblock *b, int i, location loc)
3754
282k
{
3755
282k
    assert(b->b_iused > i);
3756
282k
    if (b->b_instr[i].i_loc.lineno == NO_LOCATION.lineno) {
3757
14.8k
         b->b_instr[i].i_loc = loc;
3758
14.8k
    }
3759
282k
}
3760
3761
static void
3762
propagate_line_numbers(basicblock *entryblock)
3763
7.69k
{
3764
34.8k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3765
27.1k
        cfg_instr *last = basicblock_last_instr(b);
3766
27.1k
        if (last == NULL) {
3767
5.65k
            continue;
3768
5.65k
        }
3769
3770
21.4k
        location prev_location = NO_LOCATION;
3771
294k
        for (int i = 0; i < b->b_iused; i++) {
3772
272k
            maybe_propagate_location(b, i, prev_location);
3773
272k
            prev_location = b->b_instr[i].i_loc;
3774
272k
        }
3775
21.4k
        if (BB_HAS_FALLTHROUGH(b) && b->b_next->b_predecessors == 1) {
3776
6.32k
            if (b->b_next->b_iused > 0) {
3777
6.32k
                maybe_propagate_location(b->b_next, 0, prev_location);
3778
6.32k
            }
3779
6.32k
        }
3780
21.4k
        if (is_jump(last)) {
3781
7.68k
            basicblock *target = last->i_target;
3782
7.68k
            while (target->b_iused == 0 && target->b_predecessors == 1) {
3783
0
                target = target->b_next;
3784
0
            }
3785
7.68k
            if (target->b_predecessors == 1) {
3786
3.68k
                maybe_propagate_location(target, 0, prev_location);
3787
3.68k
            }
3788
7.68k
        }
3789
21.4k
    }
3790
7.69k
}
3791
3792
static int
3793
resolve_line_numbers(cfg_builder *g, int firstlineno)
3794
7.69k
{
3795
7.69k
    RETURN_IF_ERROR(duplicate_exits_without_lineno(g));
3796
7.69k
    propagate_line_numbers(g->g_entryblock);
3797
7.69k
    return SUCCESS;
3798
7.69k
}
3799
3800
int
3801
_PyCfg_OptimizeCodeUnit(cfg_builder *g, PyObject *consts, PyObject *const_cache,
3802
                        int nlocals, int nparams, int firstlineno)
3803
3.84k
{
3804
3.84k
    assert(cfg_builder_check(g));
3805
3.84k
    assert(g->g_entryblock->b_iused > 0);
3806
    /** Preprocessing **/
3807
    /* Map labels to targets and mark exception handlers */
3808
3.84k
    RETURN_IF_ERROR(translate_jump_labels_to_targets(g->g_entryblock));
3809
3.84k
    RETURN_IF_ERROR(mark_except_handlers(g->g_entryblock));
3810
3.84k
    RETURN_IF_ERROR(label_exception_targets(g->g_entryblock));
3811
3812
    /** Optimization **/
3813
3814
3.84k
    _Py_hashtable_t *consts_index = _Py_hashtable_new(
3815
3.84k
        _Py_hashtable_hash_ptr, _Py_hashtable_compare_direct);
3816
3.84k
    if (consts_index == NULL) {
3817
0
        PyErr_NoMemory();
3818
0
        return ERROR;
3819
0
    }
3820
3821
26.9k
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(consts); i++) {
3822
23.0k
        PyObject *item = PyList_GET_ITEM(consts, i);
3823
23.0k
        if (_Py_hashtable_get_entry(consts_index, (void *)item) != NULL) {
3824
0
            continue;
3825
0
        }
3826
23.0k
        if (_Py_hashtable_set(consts_index, (void *)item,
3827
23.0k
                              (void *)(uintptr_t)i) < 0) {
3828
0
            _Py_hashtable_destroy(consts_index);
3829
0
            PyErr_NoMemory();
3830
0
            return ERROR;
3831
0
        }
3832
23.0k
    }
3833
3834
3.84k
    int ret = optimize_cfg(g, consts, const_cache, consts_index, firstlineno);
3835
3836
3.84k
    _Py_hashtable_destroy(consts_index);
3837
3838
3.84k
    RETURN_IF_ERROR(ret);
3839
3840
3.84k
    RETURN_IF_ERROR(remove_unused_consts(g->g_entryblock, consts));
3841
3.84k
    RETURN_IF_ERROR(
3842
3.84k
        add_checks_for_loads_of_uninitialized_variables(
3843
3.84k
            g->g_entryblock, nlocals, nparams));
3844
3.84k
    RETURN_IF_ERROR(push_cold_blocks_to_end(g));
3845
3.84k
    RETURN_IF_ERROR(resolve_line_numbers(g, firstlineno));
3846
    // temporarily remove assert. See https://github.com/python/cpython/issues/125845
3847
    // assert(all_exits_have_lineno(g->g_entryblock));
3848
3.84k
    return SUCCESS;
3849
3.84k
}
3850
3851
static int *
3852
build_cellfixedoffsets(_PyCompile_CodeUnitMetadata *umd)
3853
3.84k
{
3854
3.84k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
3855
3.84k
    int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3856
3.84k
    int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
3857
3858
3.84k
    int noffsets = ncellvars + nfreevars;
3859
3.84k
    int *fixed = PyMem_New(int, noffsets);
3860
3.84k
    if (fixed == NULL) {
3861
0
        PyErr_NoMemory();
3862
0
        return NULL;
3863
0
    }
3864
5.33k
    for (int i = 0; i < noffsets; i++) {
3865
1.48k
        fixed[i] = nlocals + i;
3866
1.48k
    }
3867
3868
3.84k
    PyObject *varname, *cellindex;
3869
3.84k
    Py_ssize_t pos = 0;
3870
4.66k
    while (PyDict_Next(umd->u_cellvars, &pos, &varname, &cellindex)) {
3871
813
        PyObject *varindex;
3872
813
        if (PyDict_GetItemRef(umd->u_varnames, varname, &varindex) < 0) {
3873
0
            goto error;
3874
0
        }
3875
813
        if (varindex == NULL) {
3876
366
            continue;
3877
366
        }
3878
3879
447
        int argoffset = PyLong_AsInt(varindex);
3880
447
        Py_DECREF(varindex);
3881
447
        if (argoffset == -1 && PyErr_Occurred()) {
3882
0
            goto error;
3883
0
        }
3884
3885
447
        int oldindex = PyLong_AsInt(cellindex);
3886
447
        if (oldindex == -1 && PyErr_Occurred()) {
3887
0
            goto error;
3888
0
        }
3889
447
        fixed[oldindex] = argoffset;
3890
447
    }
3891
3.84k
    return fixed;
3892
3893
0
error:
3894
0
    PyMem_Free(fixed);
3895
0
    return NULL;
3896
3.84k
}
3897
3898
#define IS_GENERATOR(CF) \
3899
    ((CF) & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR))
3900
3901
static int
3902
insert_prefix_instructions(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock,
3903
                           int *fixed, int nfreevars)
3904
3.84k
{
3905
3.84k
    assert(umd->u_firstlineno > 0);
3906
3907
    /* Set up cells for any variable that escapes, to be put in a closure. */
3908
3.84k
    const int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3909
3.84k
    if (ncellvars) {
3910
        // umd->u_cellvars has the cells out of order so we sort them
3911
        // before adding the MAKE_CELL instructions.  Note that we
3912
        // adjust for arg cells, which come first.
3913
605
        const int nvars = ncellvars + (int)PyDict_GET_SIZE(umd->u_varnames);
3914
605
        int *sorted = PyMem_RawCalloc(nvars, sizeof(int));
3915
605
        if (sorted == NULL) {
3916
0
            PyErr_NoMemory();
3917
0
            return ERROR;
3918
0
        }
3919
1.41k
        for (int i = 0; i < ncellvars; i++) {
3920
813
            sorted[fixed[i]] = i + 1;
3921
813
        }
3922
1.79k
        for (int i = 0, ncellsused = 0; ncellsused < ncellvars; i++) {
3923
1.19k
            int oldindex = sorted[i] - 1;
3924
1.19k
            if (oldindex == -1) {
3925
381
                continue;
3926
381
            }
3927
813
            cfg_instr make_cell = {
3928
813
                .i_opcode = MAKE_CELL,
3929
                // This will get fixed in offset_derefs().
3930
813
                .i_oparg = oldindex,
3931
813
                .i_loc = NO_LOCATION,
3932
813
                .i_target = NULL,
3933
813
                .i_except = NULL,
3934
813
            };
3935
813
            if (basicblock_insert_instruction(entryblock, ncellsused, &make_cell) < 0) {
3936
0
                PyMem_RawFree(sorted);
3937
0
                return ERROR;
3938
0
            }
3939
813
            ncellsused += 1;
3940
813
        }
3941
605
        PyMem_RawFree(sorted);
3942
605
    }
3943
3944
3.84k
    if (nfreevars) {
3945
466
        cfg_instr copy_frees = {
3946
466
            .i_opcode = COPY_FREE_VARS,
3947
466
            .i_oparg = nfreevars,
3948
466
            .i_loc = NO_LOCATION,
3949
466
            .i_target = NULL,
3950
466
            .i_except = NULL,
3951
466
        };
3952
466
        RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 0, &copy_frees));
3953
466
    }
3954
3955
3.84k
    return SUCCESS;
3956
3.84k
}
3957
3958
static int
3959
fix_cell_offsets(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock, int *fixedmap)
3960
3.84k
{
3961
3.84k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
3962
3.84k
    int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3963
3.84k
    int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
3964
3.84k
    int noffsets = ncellvars + nfreevars;
3965
3966
    // First deal with duplicates (arg cells).
3967
3.84k
    int numdropped = 0;
3968
5.33k
    for (int i = 0; i < noffsets ; i++) {
3969
1.48k
        if (fixedmap[i] == i + nlocals) {
3970
1.03k
            fixedmap[i] -= numdropped;
3971
1.03k
        }
3972
447
        else {
3973
            // It was a duplicate (cell/arg).
3974
447
            numdropped += 1;
3975
447
        }
3976
1.48k
    }
3977
3978
    // Then update offsets, either relative to locals or by cell2arg.
3979
17.4k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3980
147k
        for (int i = 0; i < b->b_iused; i++) {
3981
134k
            cfg_instr *inst = &b->b_instr[i];
3982
            // This is called before extended args are generated.
3983
134k
            assert(inst->i_opcode != EXTENDED_ARG);
3984
134k
            int oldoffset = inst->i_oparg;
3985
134k
            switch(inst->i_opcode) {
3986
813
                case MAKE_CELL:
3987
1.80k
                case LOAD_CLOSURE:
3988
3.27k
                case LOAD_DEREF:
3989
3.65k
                case STORE_DEREF:
3990
3.65k
                case DELETE_DEREF:
3991
3.65k
                case LOAD_FROM_DICT_OR_DEREF:
3992
3.65k
                    assert(oldoffset >= 0);
3993
3.65k
                    assert(oldoffset < noffsets);
3994
3.65k
                    assert(fixedmap[oldoffset] >= 0);
3995
3.65k
                    inst->i_oparg = fixedmap[oldoffset];
3996
134k
            }
3997
134k
        }
3998
13.5k
    }
3999
4000
3.84k
    return numdropped;
4001
3.84k
}
4002
4003
static int
4004
prepare_localsplus(_PyCompile_CodeUnitMetadata *umd, cfg_builder *g)
4005
3.84k
{
4006
3.84k
    assert(PyDict_GET_SIZE(umd->u_varnames) < INT_MAX);
4007
3.84k
    assert(PyDict_GET_SIZE(umd->u_cellvars) < INT_MAX);
4008
3.84k
    assert(PyDict_GET_SIZE(umd->u_freevars) < INT_MAX);
4009
3.84k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
4010
3.84k
    int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
4011
3.84k
    int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
4012
3.84k
    assert(INT_MAX - nlocals - ncellvars > 0);
4013
3.84k
    assert(INT_MAX - nlocals - ncellvars - nfreevars > 0);
4014
3.84k
    int nlocalsplus = nlocals + ncellvars + nfreevars;
4015
3.84k
    int* cellfixedoffsets = build_cellfixedoffsets(umd);
4016
3.84k
    if (cellfixedoffsets == NULL) {
4017
0
        return ERROR;
4018
0
    }
4019
4020
    // This must be called before fix_cell_offsets().
4021
3.84k
    if (insert_prefix_instructions(umd, g->g_entryblock, cellfixedoffsets, nfreevars)) {
4022
0
        PyMem_Free(cellfixedoffsets);
4023
0
        return ERROR;
4024
0
    }
4025
4026
3.84k
    int numdropped = fix_cell_offsets(umd, g->g_entryblock, cellfixedoffsets);
4027
3.84k
    PyMem_Free(cellfixedoffsets);  // At this point we're done with it.
4028
3.84k
    cellfixedoffsets = NULL;
4029
3.84k
    if (numdropped < 0) {
4030
0
        return ERROR;
4031
0
    }
4032
4033
3.84k
    nlocalsplus -= numdropped;
4034
3.84k
    return nlocalsplus;
4035
3.84k
}
4036
4037
cfg_builder *
4038
_PyCfg_FromInstructionSequence(_PyInstructionSequence *seq)
4039
3.84k
{
4040
3.84k
    if (_PyInstructionSequence_ApplyLabelMap(seq) < 0) {
4041
0
        return NULL;
4042
0
    }
4043
3.84k
    cfg_builder *g = _PyCfgBuilder_New();
4044
3.84k
    if (g == NULL) {
4045
0
        return NULL;
4046
0
    }
4047
150k
    for (int i = 0; i < seq->s_used; i++) {
4048
146k
        seq->s_instrs[i].i_target = 0;
4049
146k
    }
4050
150k
    for (int i = 0; i < seq->s_used; i++) {
4051
146k
        _PyInstruction *instr = &seq->s_instrs[i];
4052
146k
        if (HAS_TARGET(instr->i_opcode)) {
4053
5.11k
            assert(instr->i_oparg >= 0 && instr->i_oparg < seq->s_used);
4054
5.11k
            seq->s_instrs[instr->i_oparg].i_target = 1;
4055
5.11k
        }
4056
146k
    }
4057
3.84k
    int offset = 0;
4058
150k
    for (int i = 0; i < seq->s_used; i++) {
4059
146k
        _PyInstruction *instr = &seq->s_instrs[i];
4060
146k
        if (instr->i_opcode == ANNOTATIONS_PLACEHOLDER) {
4061
700
            if (seq->s_annotations_code != NULL) {
4062
0
                assert(seq->s_annotations_code->s_labelmap_size == 0
4063
0
                    && seq->s_annotations_code->s_nested == NULL);
4064
0
                for (int j = 0; j < seq->s_annotations_code->s_used; j++) {
4065
0
                    _PyInstruction *ann_instr = &seq->s_annotations_code->s_instrs[j];
4066
0
                    assert(!HAS_TARGET(ann_instr->i_opcode));
4067
0
                    if (_PyCfgBuilder_Addop(g, ann_instr->i_opcode, ann_instr->i_oparg, ann_instr->i_loc) < 0) {
4068
0
                        goto error;
4069
0
                    }
4070
0
                }
4071
0
                offset += seq->s_annotations_code->s_used - 1;
4072
0
            }
4073
700
            else {
4074
700
                offset -= 1;
4075
700
            }
4076
700
            continue;
4077
700
        }
4078
145k
        if (instr->i_target) {
4079
4.03k
            jump_target_label lbl_ = {i + offset};
4080
4.03k
            if (_PyCfgBuilder_UseLabel(g, lbl_) < 0) {
4081
0
                goto error;
4082
0
            }
4083
4.03k
        }
4084
145k
        int opcode = instr->i_opcode;
4085
145k
        int oparg = instr->i_oparg;
4086
145k
        if (HAS_TARGET(opcode)) {
4087
5.11k
            oparg += offset;
4088
5.11k
        }
4089
145k
        if (_PyCfgBuilder_Addop(g, opcode, oparg, instr->i_loc) < 0) {
4090
0
            goto error;
4091
0
        }
4092
145k
    }
4093
3.84k
    if (_PyCfgBuilder_CheckSize(g) < 0) {
4094
0
        goto error;
4095
0
    }
4096
3.84k
    return g;
4097
0
error:
4098
0
    _PyCfgBuilder_Free(g);
4099
0
    return NULL;
4100
3.84k
}
4101
4102
int
4103
_PyCfg_ToInstructionSequence(cfg_builder *g, _PyInstructionSequence *seq)
4104
3.84k
{
4105
3.84k
    int lbl = 0;
4106
17.5k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
4107
13.6k
        b->b_label = (jump_target_label){lbl};
4108
13.6k
        lbl += 1;
4109
13.6k
    }
4110
17.5k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
4111
13.6k
        RETURN_IF_ERROR(_PyInstructionSequence_UseLabel(seq, b->b_label.id));
4112
147k
        for (int i = 0; i < b->b_iused; i++) {
4113
134k
            cfg_instr *instr = &b->b_instr[i];
4114
134k
            if (HAS_TARGET(instr->i_opcode)) {
4115
                /* Set oparg to the label id (it will later be mapped to an offset) */
4116
3.83k
                instr->i_oparg = instr->i_target->b_label.id;
4117
3.83k
            }
4118
134k
            RETURN_IF_ERROR(
4119
134k
                _PyInstructionSequence_Addop(
4120
134k
                    seq, instr->i_opcode, instr->i_oparg, instr->i_loc));
4121
4122
134k
            _PyExceptHandlerInfo *hi = &seq->s_instrs[seq->s_used-1].i_except_handler_info;
4123
134k
            if (instr->i_except != NULL) {
4124
10.0k
                hi->h_label = instr->i_except->b_label.id;
4125
10.0k
                hi->h_startdepth = instr->i_except->b_startdepth;
4126
10.0k
                hi->h_preserve_lasti = instr->i_except->b_preserve_lasti;
4127
10.0k
            }
4128
124k
            else {
4129
124k
                hi->h_label = -1;
4130
124k
            }
4131
134k
        }
4132
13.6k
    }
4133
3.84k
    if (_PyInstructionSequence_ApplyLabelMap(seq) < 0) {
4134
0
        return ERROR;
4135
0
    }
4136
3.84k
    return SUCCESS;
4137
3.84k
}
4138
4139
4140
int
4141
_PyCfg_OptimizedCfgToInstructionSequence(cfg_builder *g,
4142
                                     _PyCompile_CodeUnitMetadata *umd,
4143
                                     int *stackdepth, int *nlocalsplus,
4144
                                     _PyInstructionSequence *seq)
4145
3.84k
{
4146
3.84k
    RETURN_IF_ERROR(convert_pseudo_conditional_jumps(g));
4147
4148
3.84k
    *stackdepth = calculate_stackdepth(g);
4149
3.84k
    if (*stackdepth < 0) {
4150
0
        return ERROR;
4151
0
    }
4152
4153
3.84k
    *nlocalsplus = prepare_localsplus(umd, g);
4154
3.84k
    if (*nlocalsplus < 0) {
4155
0
        return ERROR;
4156
0
    }
4157
4158
3.84k
    RETURN_IF_ERROR(convert_pseudo_ops(g));
4159
4160
    /* Order of basic blocks must have been determined by now */
4161
4162
3.84k
    RETURN_IF_ERROR(normalize_jumps(g));
4163
3.84k
    assert(no_redundant_jumps(g));
4164
4165
    /* After this point the bytecode may only be modified in ways that
4166
     * preserve the borrowed references computed here.
4167
     *
4168
     * NOTE: keep the passes below in sync with _PyCompile_OptimizeCfg().
4169
     */
4170
3.84k
    RETURN_IF_ERROR(optimize_load_fast(g));
4171
4172
    /* Superinstructions are inserted after optimize_load_fast() so that a
4173
     * LOAD_FAST which can be borrowed is converted to LOAD_FAST_BORROW
4174
     * instead of being fused into a STORE_FAST_LOAD_FAST. Fusing adjacent
4175
     * instructions does not change which references are borrowed. */
4176
3.84k
    RETURN_IF_ERROR(insert_superinstructions(g));
4177
4178
    /* Can't modify the bytecode after computing jump offsets. */
4179
3.84k
    if (_PyCfg_ToInstructionSequence(g, seq) < 0) {
4180
0
        return ERROR;
4181
0
    }
4182
4183
3.84k
    return SUCCESS;
4184
3.84k
}
4185
4186
/* This is used by _PyCompile_Assemble to fill in the jump and exception
4187
 * targets in a synthetic CFG (which is not the output of the builtin compiler).
4188
 */
4189
int
4190
_PyCfg_JumpLabelsToTargets(cfg_builder *g)
4191
0
{
4192
0
    RETURN_IF_ERROR(translate_jump_labels_to_targets(g->g_entryblock));
4193
0
    RETURN_IF_ERROR(label_exception_targets(g->g_entryblock));
4194
0
    return SUCCESS;
4195
0
}
4196
4197
/* Exported API functions */
4198
4199
int
4200
PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
4201
0
{
4202
0
    stack_effects effs;
4203
0
    if (get_stack_effects(opcode, oparg, jump, &effs) < 0) {
4204
0
        return PY_INVALID_STACK_EFFECT;
4205
0
    }
4206
0
    return effs.net;
4207
0
}
4208
4209
int
4210
PyCompile_OpcodeStackEffect(int opcode, int oparg)
4211
11
{
4212
11
    stack_effects effs;
4213
11
    if (get_stack_effects(opcode, oparg, -1, &effs) < 0) {
4214
0
        return PY_INVALID_STACK_EFFECT;
4215
0
    }
4216
11
    return effs.net;
4217
11
}
4218
4219
/* Access to compiler optimizations for unit tests.
4220
4221
 * _PyCompile_OptimizeCfg takes an instruction list, constructs
4222
 * a CFG, optimizes it and converts back to an instruction list.
4223
 */
4224
4225
static PyObject *
4226
cfg_to_instruction_sequence(cfg_builder *g)
4227
0
{
4228
0
    _PyInstructionSequence *seq = (_PyInstructionSequence *)_PyInstructionSequence_New();
4229
0
    if (seq == NULL) {
4230
0
        return NULL;
4231
0
    }
4232
0
    if (_PyCfg_ToInstructionSequence(g, seq) < 0) {
4233
0
        PyInstructionSequence_Fini(seq);
4234
0
        return NULL;
4235
0
    }
4236
0
    return (PyObject*)seq;
4237
0
}
4238
4239
PyObject *
4240
_PyCompile_OptimizeCfg(PyObject *seq, PyObject *consts, int nlocals)
4241
0
{
4242
0
    if (!_PyInstructionSequence_Check(seq)) {
4243
0
        PyErr_SetString(PyExc_ValueError, "expected an instruction sequence");
4244
0
        return NULL;
4245
0
    }
4246
0
    if (!PyList_Check(consts)) {
4247
0
        PyErr_SetString(PyExc_TypeError, "consts must be a list");
4248
0
        return NULL;
4249
0
    }
4250
0
    PyObject *const_cache = PyDict_New();
4251
0
    if (const_cache == NULL) {
4252
0
        return NULL;
4253
0
    }
4254
4255
0
    PyObject *res = NULL;
4256
0
    cfg_builder *g = _PyCfg_FromInstructionSequence((_PyInstructionSequence*)seq);
4257
0
    if (g == NULL) {
4258
0
        goto error;
4259
0
    }
4260
0
    int nparams = 0, firstlineno = 1;
4261
0
    if (_PyCfg_OptimizeCodeUnit(g, consts, const_cache, nlocals,
4262
0
                                nparams, firstlineno) < 0) {
4263
0
        goto error;
4264
0
    }
4265
4266
0
    if (calculate_stackdepth(g) == ERROR) {
4267
0
        goto error;
4268
0
    }
4269
4270
    /* NOTE: keep in sync with _PyCfg_OptimizedCfgToInstructionSequence(). */
4271
0
    if (optimize_load_fast(g) != SUCCESS) {
4272
0
        goto error;
4273
0
    }
4274
4275
0
    if (insert_superinstructions(g) < 0) {
4276
0
        goto error;
4277
0
    }
4278
4279
0
    res = cfg_to_instruction_sequence(g);
4280
0
error:
4281
0
    Py_DECREF(const_cache);
4282
0
    _PyCfgBuilder_Free(g);
4283
0
    return res;
4284
0
}