@@ -6986,6 +6986,9 @@ normalize_basic_block(basicblock *bb);
69866986static int
69876987optimize_cfg (struct compiler * c , struct assembler * a , PyObject * consts );
69886988
6989+ static int
6990+ trim_unused_consts (struct compiler * c , struct assembler * a , PyObject * consts );
6991+
69896992/* Duplicates exit BBs, so that line numbers can be propagated to them */
69906993static int
69916994duplicate_exits_without_lineno (struct compiler * c );
@@ -7127,6 +7130,9 @@ assemble(struct compiler *c, int addNone)
71277130 if (duplicate_exits_without_lineno (c )) {
71287131 return NULL ;
71297132 }
7133+ if (trim_unused_consts (c , & a , consts )) {
7134+ goto error ;
7135+ }
71307136 propagate_line_numbers (& a );
71317137 guarantee_lineno_for_exits (& a , c -> u -> u_firstlineno );
71327138 /* Can't modify the bytecode after computing jump offsets. */
@@ -7809,6 +7815,33 @@ optimize_cfg(struct compiler *c, struct assembler *a, PyObject *consts)
78097815 return 0 ;
78107816}
78117817
7818+ // Remove trailing unused constants.
7819+ static int
7820+ trim_unused_consts (struct compiler * c , struct assembler * a , PyObject * consts )
7821+ {
7822+ assert (PyList_CheckExact (consts ));
7823+
7824+ // The first constant may be docstring; keep it always.
7825+ int max_const_index = 0 ;
7826+ for (basicblock * b = a -> a_entry ; b != NULL ; b = b -> b_next ) {
7827+ for (int i = 0 ; i < b -> b_iused ; i ++ ) {
7828+ if (b -> b_instr [i ].i_opcode == LOAD_CONST &&
7829+ b -> b_instr [i ].i_oparg > max_const_index ) {
7830+ max_const_index = b -> b_instr [i ].i_oparg ;
7831+ }
7832+ }
7833+ }
7834+ if (max_const_index + 1 < PyList_GET_SIZE (consts )) {
7835+ //fprintf(stderr, "removing trailing consts: max=%d, size=%d\n",
7836+ // max_const_index, (int)PyList_GET_SIZE(consts));
7837+ if (PyList_SetSlice (consts , max_const_index + 1 ,
7838+ PyList_GET_SIZE (consts ), NULL ) < 0 ) {
7839+ return 1 ;
7840+ }
7841+ }
7842+ return 0 ;
7843+ }
7844+
78127845static inline int
78137846is_exit_without_lineno (basicblock * b ) {
78147847 return b -> b_exit && b -> b_instr [0 ].i_lineno < 0 ;
0 commit comments