blob: a49790a60f896ab747b8ca054b2704f2778d7c53 [file] [log] [blame]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001/* Peephole optimizations for bytecode compiler. */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002
3#include "Python.h"
4
5#include "Python-ast.h"
6#include "node.h"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00007#include "ast.h"
8#include "code.h"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009#include "symtable.h"
10#include "opcode.h"
11
12#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +000014#define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000015 || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +000016#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
18 || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +000019#define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000020#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
21#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
22#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
23#define ISBASICBLOCK(blocks, start, bytes) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000024 (blocks[start]==blocks[start+bytes-1])
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000025
Antoine Pitrou17b880a2011-03-11 17:27:02 +010026
27#define CONST_STACK_CREATE() { \
28 const_stack_size = 256; \
29 const_stack = PyMem_New(PyObject *, const_stack_size); \
30 load_const_stack = PyMem_New(Py_ssize_t, const_stack_size); \
31 if (!const_stack || !load_const_stack) { \
32 PyErr_NoMemory(); \
33 goto exitError; \
34 } \
35 }
36
37#define CONST_STACK_DELETE() do { \
38 if (const_stack) \
39 PyMem_Free(const_stack); \
40 if (load_const_stack) \
41 PyMem_Free(load_const_stack); \
42 } while(0)
43
44#define CONST_STACK_LEN() (const_stack_top + 1)
45
46#define CONST_STACK_PUSH_OP(i) do { \
47 PyObject *_x; \
48 assert(codestr[i] == LOAD_CONST); \
49 assert(PyList_GET_SIZE(consts) > GETARG(codestr, i)); \
50 _x = PyList_GET_ITEM(consts, GETARG(codestr, i)); \
51 if (++const_stack_top >= const_stack_size) { \
52 const_stack_size *= 2; \
53 PyMem_Resize(const_stack, PyObject *, const_stack_size); \
54 PyMem_Resize(load_const_stack, Py_ssize_t, const_stack_size); \
55 if (!const_stack || !load_const_stack) { \
56 PyErr_NoMemory(); \
57 goto exitError; \
58 } \
59 } \
60 load_const_stack[const_stack_top] = i; \
61 const_stack[const_stack_top] = _x; \
62 in_consts = 1; \
63 } while(0)
64
65#define CONST_STACK_RESET() do { \
66 const_stack_top = -1; \
67 } while(0)
68
Stefan Krah472d2802011-09-21 19:08:39 +020069#define CONST_STACK_TOP() \
Antoine Pitrou17b880a2011-03-11 17:27:02 +010070 const_stack[const_stack_top]
71
72#define CONST_STACK_LASTN(i) \
73 &const_stack[const_stack_top - i + 1]
74
75#define CONST_STACK_POP(i) do { \
76 assert(const_stack_top + 1 >= i); \
77 const_stack_top -= i; \
78 } while(0)
79
80#define CONST_STACK_OP_LASTN(i) \
81 ((const_stack_top >= i - 1) ? load_const_stack[const_stack_top - i + 1] : -1)
82
83
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000084/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 with LOAD_CONST (c1, c2, ... cn).
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000086 The consts table must still be in list form so that the
87 new constant (c1, c2, ... cn) can be appended.
88 Called with codestr pointing to the first LOAD_CONST.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 Bails out with no change if one or more of the LOAD_CONSTs is missing.
Antoine Pitroub7fbcd32010-01-16 18:37:38 +000090 Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in"
91 test; for BUILD_SET it assembles a frozenset rather than a tuple.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000092*/
93static int
Antoine Pitrou17b880a2011-03-11 17:27:02 +010094tuple_of_constants(unsigned char *codestr, Py_ssize_t n,
95 PyObject *consts, PyObject **objs)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 PyObject *newconst, *constant;
Antoine Pitrou17b880a2011-03-11 17:27:02 +010098 Py_ssize_t i, len_consts;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 /* Pre-conditions */
101 assert(PyList_CheckExact(consts));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 /* Buildup new tuple of constants */
104 newconst = PyTuple_New(n);
105 if (newconst == NULL)
106 return 0;
107 len_consts = PyList_GET_SIZE(consts);
108 for (i=0 ; i<n ; i++) {
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100109 constant = objs[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 Py_INCREF(constant);
111 PyTuple_SET_ITEM(newconst, i, constant);
112 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 /* If it's a BUILD_SET, use the PyTuple we just built to create a
115 PyFrozenSet, and use that as the constant instead: */
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100116 if (codestr[0] == BUILD_SET) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 PyObject *tuple = newconst;
118 newconst = PyFrozenSet_New(tuple);
119 Py_DECREF(tuple);
120 if (newconst == NULL)
121 return 0;
122 }
Antoine Pitroub7fbcd32010-01-16 18:37:38 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Append folded constant onto consts */
125 if (PyList_Append(consts, newconst)) {
126 Py_DECREF(newconst);
127 return 0;
128 }
129 Py_DECREF(newconst);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 /* Write NOPs over old LOAD_CONSTS and
132 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100133 codestr[0] = LOAD_CONST;
134 SETARG(codestr, 0, len_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 return 1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000136}
137
138/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 with LOAD_CONST binop(c1,c2)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000140 The consts table must still be in list form so that the
141 new constant can be appended.
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100142 Called with codestr pointing to the BINOP.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 Abandons the transformation if the folding fails (i.e. 1+'a').
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000144 If the new constant is a sequence, only folds when the size
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 is below a threshold value. That keeps pyc files from
146 becoming large in the presence of code like: (None,)*1000.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000147*/
148static int
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100149fold_binops_on_constants(unsigned char *codestr, PyObject *consts, PyObject **objs)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyObject *newconst, *v, *w;
152 Py_ssize_t len_consts, size;
153 int opcode;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 /* Pre-conditions */
156 assert(PyList_CheckExact(consts));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 /* Create new constant */
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100159 v = objs[0];
160 w = objs[1];
161 opcode = codestr[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 switch (opcode) {
163 case BINARY_POWER:
164 newconst = PyNumber_Power(v, w, Py_None);
165 break;
166 case BINARY_MULTIPLY:
167 newconst = PyNumber_Multiply(v, w);
168 break;
169 case BINARY_TRUE_DIVIDE:
170 newconst = PyNumber_TrueDivide(v, w);
171 break;
172 case BINARY_FLOOR_DIVIDE:
173 newconst = PyNumber_FloorDivide(v, w);
174 break;
175 case BINARY_MODULO:
176 newconst = PyNumber_Remainder(v, w);
177 break;
178 case BINARY_ADD:
179 newconst = PyNumber_Add(v, w);
180 break;
181 case BINARY_SUBTRACT:
182 newconst = PyNumber_Subtract(v, w);
183 break;
184 case BINARY_SUBSCR:
185 newconst = PyObject_GetItem(v, w);
186 break;
187 case BINARY_LSHIFT:
188 newconst = PyNumber_Lshift(v, w);
189 break;
190 case BINARY_RSHIFT:
191 newconst = PyNumber_Rshift(v, w);
192 break;
193 case BINARY_AND:
194 newconst = PyNumber_And(v, w);
195 break;
196 case BINARY_XOR:
197 newconst = PyNumber_Xor(v, w);
198 break;
199 case BINARY_OR:
200 newconst = PyNumber_Or(v, w);
201 break;
202 default:
203 /* Called with an unknown opcode */
204 PyErr_Format(PyExc_SystemError,
205 "unexpected binary operation %d on a constant",
206 opcode);
207 return 0;
208 }
209 if (newconst == NULL) {
Raymond Hettinger819a0642010-08-22 08:39:49 +0000210 if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
211 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 return 0;
213 }
214 size = PyObject_Size(newconst);
Raymond Hettinger819a0642010-08-22 08:39:49 +0000215 if (size == -1) {
216 if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
217 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyErr_Clear();
Raymond Hettinger819a0642010-08-22 08:39:49 +0000219 } else if (size > 20) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_DECREF(newconst);
221 return 0;
222 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 /* Append folded constant into consts table */
225 len_consts = PyList_GET_SIZE(consts);
226 if (PyList_Append(consts, newconst)) {
227 Py_DECREF(newconst);
228 return 0;
229 }
230 Py_DECREF(newconst);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100233 codestr[-2] = LOAD_CONST;
234 SETARG(codestr, -2, len_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return 1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236}
237
238static int
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100239fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts, PyObject *v)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000240{
Mark Dickinson7c9e8032011-03-23 17:59:37 +0000241 PyObject *newconst;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_ssize_t len_consts;
243 int opcode;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 /* Pre-conditions */
246 assert(PyList_CheckExact(consts));
247 assert(codestr[0] == LOAD_CONST);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Create new constant */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 opcode = codestr[3];
251 switch (opcode) {
252 case UNARY_NEGATIVE:
Mark Dickinson7c9e8032011-03-23 17:59:37 +0000253 newconst = PyNumber_Negative(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 break;
255 case UNARY_INVERT:
256 newconst = PyNumber_Invert(v);
257 break;
258 case UNARY_POSITIVE:
259 newconst = PyNumber_Positive(v);
260 break;
261 default:
262 /* Called with an unknown opcode */
263 PyErr_Format(PyExc_SystemError,
264 "unexpected unary operation %d on a constant",
265 opcode);
266 return 0;
267 }
268 if (newconst == NULL) {
Raymond Hettinger819a0642010-08-22 08:39:49 +0000269 if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
270 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 return 0;
272 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 /* Append folded constant into consts table */
275 len_consts = PyList_GET_SIZE(consts);
276 if (PyList_Append(consts, newconst)) {
277 Py_DECREF(newconst);
278 return 0;
279 }
280 Py_DECREF(newconst);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /* Write NOP LOAD_CONST newconst */
283 codestr[0] = NOP;
284 codestr[1] = LOAD_CONST;
285 SETARG(codestr, 1, len_consts);
286 return 1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000287}
288
289static unsigned int *
Christian Heimescc47b052008-03-25 14:56:36 +0000290markblocks(unsigned char *code, Py_ssize_t len)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
293 int i,j, opcode, blockcnt = 0;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (blocks == NULL) {
296 PyErr_NoMemory();
297 return NULL;
298 }
299 memset(blocks, 0, len*sizeof(int));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 /* Mark labels in the first pass */
302 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
303 opcode = code[i];
304 switch (opcode) {
305 case FOR_ITER:
306 case JUMP_FORWARD:
307 case JUMP_IF_FALSE_OR_POP:
308 case JUMP_IF_TRUE_OR_POP:
309 case POP_JUMP_IF_FALSE:
310 case POP_JUMP_IF_TRUE:
311 case JUMP_ABSOLUTE:
312 case CONTINUE_LOOP:
313 case SETUP_LOOP:
314 case SETUP_EXCEPT:
315 case SETUP_FINALLY:
316 case SETUP_WITH:
317 j = GETJUMPTGT(code, i);
318 blocks[j] = 1;
319 break;
320 }
321 }
322 /* Build block numbers in the second pass */
323 for (i=0 ; i<len ; i++) {
324 blockcnt += blocks[i]; /* increment blockcnt over labels */
325 blocks[i] = blockcnt;
326 }
327 return blocks;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000328}
329
330/* Perform basic peephole optimizations to components of a code object.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 The consts object should still be in list form to allow new constants
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000332 to be appended.
333
Guido van Rossum0240b922007-02-26 21:23:50 +0000334 To keep the optimizer simple, it bails out (does nothing) for code that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 has a length over 32,700, and does not calculate extended arguments.
Guido van Rossum0240b922007-02-26 21:23:50 +0000336 That allows us to avoid overflow and sign issues. Likewise, it bails when
337 the lineno table has complex encoding for gaps >= 255. EXTENDED_ARG can
338 appear before MAKE_FUNCTION; in this case both opcodes are skipped.
339 EXTENDED_ARG preceding any other opcode causes the optimizer to bail.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000340
341 Optimizations are restricted to simple transformations occuring within a
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 single basic block. All transformations keep the code size the same or
343 smaller. For those that reduce size, the gaps are initially filled with
344 NOPs. Later those NOPs are removed and the jump addresses retargeted in
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000345 a single pass. Line numbering is adjusted accordingly. */
346
347PyObject *
348PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
349 PyObject *lineno_obj)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 Py_ssize_t i, j, codelen;
352 int nops, h, adj;
353 int tgt, tgttgt, opcode;
354 unsigned char *codestr = NULL;
355 unsigned char *lineno;
356 int *addrmap = NULL;
357 int new_line, cum_orig_line, last_line, tabsiz;
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100358 PyObject **const_stack = NULL;
359 Py_ssize_t *load_const_stack = NULL;
360 Py_ssize_t const_stack_top = -1;
361 Py_ssize_t const_stack_size = 0;
362 int in_consts = 0; /* whether we are in a LOAD_CONST sequence */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 unsigned int *blocks = NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 /* Bail out if an exception is set */
366 if (PyErr_Occurred())
367 goto exitError;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* Bypass optimization when the lineno table is too complex */
370 assert(PyBytes_Check(lineno_obj));
371 lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj);
372 tabsiz = PyBytes_GET_SIZE(lineno_obj);
373 if (memchr(lineno, 255, tabsiz) != NULL)
374 goto exitUnchanged;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* Avoid situations where jump retargeting could overflow */
377 assert(PyBytes_Check(code));
378 codelen = PyBytes_GET_SIZE(code);
379 if (codelen > 32700)
380 goto exitUnchanged;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* Make a modifiable copy of the code string */
383 codestr = (unsigned char *)PyMem_Malloc(codelen);
Victor Stinnere0af3a82013-07-09 00:32:04 +0200384 if (codestr == NULL) {
385 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 goto exitError;
Victor Stinnere0af3a82013-07-09 00:32:04 +0200387 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 codestr = (unsigned char *)memcpy(codestr,
389 PyBytes_AS_STRING(code), codelen);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 /* Verify that RETURN_VALUE terminates the codestring. This allows
392 the various transformation patterns to look ahead several
393 instructions without additional checks to make sure they are not
394 looking beyond the end of the code string.
395 */
396 if (codestr[codelen-1] != RETURN_VALUE)
397 goto exitUnchanged;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* Mapping to new jump targets after NOPs are removed */
400 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Victor Stinnere0af3a82013-07-09 00:32:04 +0200401 if (addrmap == NULL) {
402 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 goto exitError;
Victor Stinnere0af3a82013-07-09 00:32:04 +0200404 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 blocks = markblocks(codestr, codelen);
407 if (blocks == NULL)
408 goto exitError;
409 assert(PyList_Check(consts));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000410
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100411 CONST_STACK_CREATE();
412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
414 reoptimize_current:
415 opcode = codestr[i];
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000416
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100417 if (!in_consts) {
418 CONST_STACK_RESET();
419 }
420 in_consts = 0;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 switch (opcode) {
423 /* Replace UNARY_NOT POP_JUMP_IF_FALSE
424 with POP_JUMP_IF_TRUE */
425 case UNARY_NOT:
426 if (codestr[i+1] != POP_JUMP_IF_FALSE
427 || !ISBASICBLOCK(blocks,i,4))
428 continue;
429 j = GETARG(codestr, i+1);
430 codestr[i] = POP_JUMP_IF_TRUE;
431 SETARG(codestr, i, j);
432 codestr[i+3] = NOP;
433 goto reoptimize_current;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* not a is b --> a is not b
436 not a in b --> a not in b
437 not a is not b --> a is b
438 not a not in b --> a in b
439 */
440 case COMPARE_OP:
441 j = GETARG(codestr, i);
442 if (j < 6 || j > 9 ||
443 codestr[i+3] != UNARY_NOT ||
444 !ISBASICBLOCK(blocks,i,4))
445 continue;
446 SETARG(codestr, i, (j^1));
447 codestr[i+3] = NOP;
448 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* Skip over LOAD_CONST trueconst
451 POP_JUMP_IF_FALSE xx. This improves
452 "while 1" performance. */
453 case LOAD_CONST:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100454 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 j = GETARG(codestr, i);
456 if (codestr[i+3] != POP_JUMP_IF_FALSE ||
457 !ISBASICBLOCK(blocks,i,6) ||
458 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
459 continue;
460 memset(codestr+i, NOP, 6);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100461 CONST_STACK_RESET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* Try to fold tuples of constants (includes a case for lists and sets
465 which are only used for "in" and "not in" tests).
466 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
467 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
468 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
469 case BUILD_TUPLE:
470 case BUILD_LIST:
471 case BUILD_SET:
472 j = GETARG(codestr, i);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100473 if (j == 0)
474 break;
475 h = CONST_STACK_OP_LASTN(j);
476 assert((h >= 0 || CONST_STACK_LEN() < j));
477 if (h >= 0 && j > 0 && j <= CONST_STACK_LEN() &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 ((opcode == BUILD_TUPLE &&
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100479 ISBASICBLOCK(blocks, h, i-h+3)) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 ((opcode == BUILD_LIST || opcode == BUILD_SET) &&
481 codestr[i+3]==COMPARE_OP &&
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100482 ISBASICBLOCK(blocks, h, i-h+6) &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 (GETARG(codestr,i+3)==6 ||
484 GETARG(codestr,i+3)==7))) &&
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100485 tuple_of_constants(&codestr[i], j, consts, CONST_STACK_LASTN(j))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 assert(codestr[i] == LOAD_CONST);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100487 memset(&codestr[h], NOP, i - h);
488 CONST_STACK_POP(j);
489 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 break;
491 }
492 if (codestr[i+3] != UNPACK_SEQUENCE ||
493 !ISBASICBLOCK(blocks,i,6) ||
Raymond Hettinger0661e912011-03-15 15:03:36 -0700494 j != GETARG(codestr, i+3) ||
495 opcode == BUILD_SET)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 continue;
497 if (j == 1) {
498 memset(codestr+i, NOP, 6);
499 } else if (j == 2) {
500 codestr[i] = ROT_TWO;
501 memset(codestr+i+1, NOP, 5);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100502 CONST_STACK_RESET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 } else if (j == 3) {
504 codestr[i] = ROT_THREE;
505 codestr[i+1] = ROT_TWO;
506 memset(codestr+i+2, NOP, 4);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100507 CONST_STACK_RESET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
509 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* Fold binary ops on constants.
512 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
513 case BINARY_POWER:
514 case BINARY_MULTIPLY:
515 case BINARY_TRUE_DIVIDE:
516 case BINARY_FLOOR_DIVIDE:
517 case BINARY_MODULO:
518 case BINARY_ADD:
519 case BINARY_SUBTRACT:
520 case BINARY_SUBSCR:
521 case BINARY_LSHIFT:
522 case BINARY_RSHIFT:
523 case BINARY_AND:
524 case BINARY_XOR:
525 case BINARY_OR:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100526 /* NOTE: LOAD_CONST is saved at `i-2` since it has an arg
527 while BINOP hasn't */
528 h = CONST_STACK_OP_LASTN(2);
529 assert((h >= 0 || CONST_STACK_LEN() < 2));
530 if (h >= 0 &&
531 ISBASICBLOCK(blocks, h, i-h+1) &&
532 fold_binops_on_constants(&codestr[i], consts, CONST_STACK_LASTN(2))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 i -= 2;
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100534 memset(&codestr[h], NOP, i - h);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 assert(codestr[i] == LOAD_CONST);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100536 CONST_STACK_POP(2);
537 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 }
539 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 /* Fold unary ops on constants.
542 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
543 case UNARY_NEGATIVE:
544 case UNARY_INVERT:
545 case UNARY_POSITIVE:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100546 h = CONST_STACK_OP_LASTN(1);
547 assert((h >= 0 || CONST_STACK_LEN() < 1));
548 if (h >= 0 &&
549 ISBASICBLOCK(blocks, h, i-h+1) &&
550 fold_unaryops_on_constants(&codestr[i-3], consts, CONST_STACK_TOP())) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 i -= 2;
552 assert(codestr[i] == LOAD_CONST);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100553 CONST_STACK_POP(1);
554 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 }
556 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* Simplify conditional jump to conditional jump where the
559 result of the first test implies the success of a similar
560 test or the failure of the opposite test.
561 Arises in code like:
562 "if a and b:"
563 "if a or b:"
564 "a and b or c"
565 "(a and b) and c"
566 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
567 --> x:JUMP_IF_FALSE_OR_POP z
568 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
569 --> x:POP_JUMP_IF_FALSE y+3
570 where y+3 is the instruction following the second test.
571 */
572 case JUMP_IF_FALSE_OR_POP:
573 case JUMP_IF_TRUE_OR_POP:
574 tgt = GETJUMPTGT(codestr, i);
575 j = codestr[tgt];
576 if (CONDITIONAL_JUMP(j)) {
577 /* NOTE: all possible jumps here are
578 absolute! */
579 if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
580 /* The second jump will be
581 taken iff the first is. */
582 tgttgt = GETJUMPTGT(codestr, tgt);
583 /* The current opcode inherits
584 its target's stack behaviour */
585 codestr[i] = j;
586 SETARG(codestr, i, tgttgt);
587 goto reoptimize_current;
588 } else {
589 /* The second jump is not taken
590 if the first is (so jump past
591 it), and all conditional
592 jumps pop their argument when
593 they're not taken (so change
594 the first jump to pop its
595 argument when it's taken). */
596 if (JUMPS_ON_TRUE(opcode))
597 codestr[i] = POP_JUMP_IF_TRUE;
598 else
599 codestr[i] = POP_JUMP_IF_FALSE;
600 SETARG(codestr, i, (tgt + 3));
601 goto reoptimize_current;
602 }
603 }
604 /* Intentional fallthrough */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 /* Replace jumps to unconditional jumps */
607 case POP_JUMP_IF_FALSE:
608 case POP_JUMP_IF_TRUE:
609 case FOR_ITER:
610 case JUMP_FORWARD:
611 case JUMP_ABSOLUTE:
612 case CONTINUE_LOOP:
613 case SETUP_LOOP:
614 case SETUP_EXCEPT:
615 case SETUP_FINALLY:
616 case SETUP_WITH:
617 tgt = GETJUMPTGT(codestr, i);
618 /* Replace JUMP_* to a RETURN into just a RETURN */
619 if (UNCONDITIONAL_JUMP(opcode) &&
620 codestr[tgt] == RETURN_VALUE) {
621 codestr[i] = RETURN_VALUE;
622 memset(codestr+i+1, NOP, 2);
623 continue;
624 }
625 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
626 continue;
627 tgttgt = GETJUMPTGT(codestr, tgt);
628 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
629 opcode = JUMP_ABSOLUTE;
630 if (!ABSOLUTE_JUMP(opcode))
631 tgttgt -= i + 3; /* Calc relative jump addr */
632 if (tgttgt < 0) /* No backward relative jumps */
633 continue;
634 codestr[i] = opcode;
635 SETARG(codestr, i, tgttgt);
636 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 case EXTENDED_ARG:
639 if (codestr[i+3] != MAKE_FUNCTION)
640 goto exitUnchanged;
641 /* don't visit MAKE_FUNCTION as GETARG will be wrong */
642 i += 3;
643 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
646 /* Remove unreachable JUMPs after RETURN */
647 case RETURN_VALUE:
648 if (i+4 >= codelen)
649 continue;
650 if (codestr[i+4] == RETURN_VALUE &&
651 ISBASICBLOCK(blocks,i,5))
652 memset(codestr+i+1, NOP, 4);
653 else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
654 ISBASICBLOCK(blocks,i,4))
655 memset(codestr+i+1, NOP, 3);
656 break;
657 }
658 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 /* Fixup linenotab */
661 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
662 addrmap[i] = i - nops;
663 if (codestr[i] == NOP)
664 nops++;
665 }
666 cum_orig_line = 0;
667 last_line = 0;
668 for (i=0 ; i < tabsiz ; i+=2) {
669 cum_orig_line += lineno[i];
670 new_line = addrmap[cum_orig_line];
671 assert (new_line - last_line < 255);
672 lineno[i] =((unsigned char)(new_line - last_line));
673 last_line = new_line;
674 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 /* Remove NOPs and fixup jump targets */
677 for (i=0, h=0 ; i<codelen ; ) {
678 opcode = codestr[i];
679 switch (opcode) {
680 case NOP:
681 i++;
682 continue;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 case JUMP_ABSOLUTE:
685 case CONTINUE_LOOP:
686 case POP_JUMP_IF_FALSE:
687 case POP_JUMP_IF_TRUE:
688 case JUMP_IF_FALSE_OR_POP:
689 case JUMP_IF_TRUE_OR_POP:
690 j = addrmap[GETARG(codestr, i)];
691 SETARG(codestr, i, j);
692 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 case FOR_ITER:
695 case JUMP_FORWARD:
696 case SETUP_LOOP:
697 case SETUP_EXCEPT:
698 case SETUP_FINALLY:
699 case SETUP_WITH:
700 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
701 SETARG(codestr, i, j);
702 break;
703 }
704 adj = CODESIZE(opcode);
705 while (adj--)
706 codestr[h++] = codestr[i++];
707 }
708 assert(h + nops == codelen);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 code = PyBytes_FromStringAndSize((char *)codestr, h);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100711 CONST_STACK_DELETE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyMem_Free(addrmap);
713 PyMem_Free(codestr);
714 PyMem_Free(blocks);
715 return code;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000716
Alexandre Vassalotti6f828182009-07-21 02:51:58 +0000717 exitError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 code = NULL;
Alexandre Vassalotti6f828182009-07-21 02:51:58 +0000719
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000720 exitUnchanged:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100721 CONST_STACK_DELETE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (blocks != NULL)
723 PyMem_Free(blocks);
724 if (addrmap != NULL)
725 PyMem_Free(addrmap);
726 if (codestr != NULL)
727 PyMem_Free(codestr);
728 Py_XINCREF(code);
729 return code;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000730}