blob: e6877bb3e6a5ba7527476c36403361e02f501873 [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);
384 if (codestr == NULL)
385 goto exitError;
386 codestr = (unsigned char *)memcpy(codestr,
387 PyBytes_AS_STRING(code), codelen);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 /* Verify that RETURN_VALUE terminates the codestring. This allows
390 the various transformation patterns to look ahead several
391 instructions without additional checks to make sure they are not
392 looking beyond the end of the code string.
393 */
394 if (codestr[codelen-1] != RETURN_VALUE)
395 goto exitUnchanged;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 /* Mapping to new jump targets after NOPs are removed */
398 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
399 if (addrmap == NULL)
400 goto exitError;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 blocks = markblocks(codestr, codelen);
403 if (blocks == NULL)
404 goto exitError;
405 assert(PyList_Check(consts));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000406
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100407 CONST_STACK_CREATE();
408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
410 reoptimize_current:
411 opcode = codestr[i];
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000412
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100413 if (!in_consts) {
414 CONST_STACK_RESET();
415 }
416 in_consts = 0;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 switch (opcode) {
419 /* Replace UNARY_NOT POP_JUMP_IF_FALSE
420 with POP_JUMP_IF_TRUE */
421 case UNARY_NOT:
422 if (codestr[i+1] != POP_JUMP_IF_FALSE
423 || !ISBASICBLOCK(blocks,i,4))
424 continue;
425 j = GETARG(codestr, i+1);
426 codestr[i] = POP_JUMP_IF_TRUE;
427 SETARG(codestr, i, j);
428 codestr[i+3] = NOP;
429 goto reoptimize_current;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 /* not a is b --> a is not b
432 not a in b --> a not in b
433 not a is not b --> a is b
434 not a not in b --> a in b
435 */
436 case COMPARE_OP:
437 j = GETARG(codestr, i);
438 if (j < 6 || j > 9 ||
439 codestr[i+3] != UNARY_NOT ||
440 !ISBASICBLOCK(blocks,i,4))
441 continue;
442 SETARG(codestr, i, (j^1));
443 codestr[i+3] = NOP;
444 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 /* Skip over LOAD_CONST trueconst
447 POP_JUMP_IF_FALSE xx. This improves
448 "while 1" performance. */
449 case LOAD_CONST:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100450 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 j = GETARG(codestr, i);
452 if (codestr[i+3] != POP_JUMP_IF_FALSE ||
453 !ISBASICBLOCK(blocks,i,6) ||
454 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
455 continue;
456 memset(codestr+i, NOP, 6);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100457 CONST_STACK_RESET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* Try to fold tuples of constants (includes a case for lists and sets
461 which are only used for "in" and "not in" tests).
462 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
463 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
464 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
465 case BUILD_TUPLE:
466 case BUILD_LIST:
467 case BUILD_SET:
468 j = GETARG(codestr, i);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100469 if (j == 0)
470 break;
471 h = CONST_STACK_OP_LASTN(j);
472 assert((h >= 0 || CONST_STACK_LEN() < j));
473 if (h >= 0 && j > 0 && j <= CONST_STACK_LEN() &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 ((opcode == BUILD_TUPLE &&
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100475 ISBASICBLOCK(blocks, h, i-h+3)) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 ((opcode == BUILD_LIST || opcode == BUILD_SET) &&
477 codestr[i+3]==COMPARE_OP &&
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100478 ISBASICBLOCK(blocks, h, i-h+6) &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 (GETARG(codestr,i+3)==6 ||
480 GETARG(codestr,i+3)==7))) &&
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100481 tuple_of_constants(&codestr[i], j, consts, CONST_STACK_LASTN(j))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 assert(codestr[i] == LOAD_CONST);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100483 memset(&codestr[h], NOP, i - h);
484 CONST_STACK_POP(j);
485 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 break;
487 }
488 if (codestr[i+3] != UNPACK_SEQUENCE ||
489 !ISBASICBLOCK(blocks,i,6) ||
Raymond Hettinger0661e912011-03-15 15:03:36 -0700490 j != GETARG(codestr, i+3) ||
491 opcode == BUILD_SET)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 continue;
493 if (j == 1) {
494 memset(codestr+i, NOP, 6);
495 } else if (j == 2) {
496 codestr[i] = ROT_TWO;
497 memset(codestr+i+1, NOP, 5);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100498 CONST_STACK_RESET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 } else if (j == 3) {
500 codestr[i] = ROT_THREE;
501 codestr[i+1] = ROT_TWO;
502 memset(codestr+i+2, NOP, 4);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100503 CONST_STACK_RESET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 }
505 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Fold binary ops on constants.
508 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
509 case BINARY_POWER:
510 case BINARY_MULTIPLY:
511 case BINARY_TRUE_DIVIDE:
512 case BINARY_FLOOR_DIVIDE:
513 case BINARY_MODULO:
514 case BINARY_ADD:
515 case BINARY_SUBTRACT:
516 case BINARY_SUBSCR:
517 case BINARY_LSHIFT:
518 case BINARY_RSHIFT:
519 case BINARY_AND:
520 case BINARY_XOR:
521 case BINARY_OR:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100522 /* NOTE: LOAD_CONST is saved at `i-2` since it has an arg
523 while BINOP hasn't */
524 h = CONST_STACK_OP_LASTN(2);
525 assert((h >= 0 || CONST_STACK_LEN() < 2));
526 if (h >= 0 &&
527 ISBASICBLOCK(blocks, h, i-h+1) &&
528 fold_binops_on_constants(&codestr[i], consts, CONST_STACK_LASTN(2))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 i -= 2;
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100530 memset(&codestr[h], NOP, i - h);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 assert(codestr[i] == LOAD_CONST);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100532 CONST_STACK_POP(2);
533 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 }
535 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Fold unary ops on constants.
538 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
539 case UNARY_NEGATIVE:
540 case UNARY_INVERT:
541 case UNARY_POSITIVE:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100542 h = CONST_STACK_OP_LASTN(1);
543 assert((h >= 0 || CONST_STACK_LEN() < 1));
544 if (h >= 0 &&
545 ISBASICBLOCK(blocks, h, i-h+1) &&
546 fold_unaryops_on_constants(&codestr[i-3], consts, CONST_STACK_TOP())) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 i -= 2;
548 assert(codestr[i] == LOAD_CONST);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100549 CONST_STACK_POP(1);
550 CONST_STACK_PUSH_OP(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 /* Simplify conditional jump to conditional jump where the
555 result of the first test implies the success of a similar
556 test or the failure of the opposite test.
557 Arises in code like:
558 "if a and b:"
559 "if a or b:"
560 "a and b or c"
561 "(a and b) and c"
562 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
563 --> x:JUMP_IF_FALSE_OR_POP z
564 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
565 --> x:POP_JUMP_IF_FALSE y+3
566 where y+3 is the instruction following the second test.
567 */
568 case JUMP_IF_FALSE_OR_POP:
569 case JUMP_IF_TRUE_OR_POP:
570 tgt = GETJUMPTGT(codestr, i);
571 j = codestr[tgt];
572 if (CONDITIONAL_JUMP(j)) {
573 /* NOTE: all possible jumps here are
574 absolute! */
575 if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
576 /* The second jump will be
577 taken iff the first is. */
578 tgttgt = GETJUMPTGT(codestr, tgt);
579 /* The current opcode inherits
580 its target's stack behaviour */
581 codestr[i] = j;
582 SETARG(codestr, i, tgttgt);
583 goto reoptimize_current;
584 } else {
585 /* The second jump is not taken
586 if the first is (so jump past
587 it), and all conditional
588 jumps pop their argument when
589 they're not taken (so change
590 the first jump to pop its
591 argument when it's taken). */
592 if (JUMPS_ON_TRUE(opcode))
593 codestr[i] = POP_JUMP_IF_TRUE;
594 else
595 codestr[i] = POP_JUMP_IF_FALSE;
596 SETARG(codestr, i, (tgt + 3));
597 goto reoptimize_current;
598 }
599 }
600 /* Intentional fallthrough */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* Replace jumps to unconditional jumps */
603 case POP_JUMP_IF_FALSE:
604 case POP_JUMP_IF_TRUE:
605 case FOR_ITER:
606 case JUMP_FORWARD:
607 case JUMP_ABSOLUTE:
608 case CONTINUE_LOOP:
609 case SETUP_LOOP:
610 case SETUP_EXCEPT:
611 case SETUP_FINALLY:
612 case SETUP_WITH:
613 tgt = GETJUMPTGT(codestr, i);
614 /* Replace JUMP_* to a RETURN into just a RETURN */
615 if (UNCONDITIONAL_JUMP(opcode) &&
616 codestr[tgt] == RETURN_VALUE) {
617 codestr[i] = RETURN_VALUE;
618 memset(codestr+i+1, NOP, 2);
619 continue;
620 }
621 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
622 continue;
623 tgttgt = GETJUMPTGT(codestr, tgt);
624 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
625 opcode = JUMP_ABSOLUTE;
626 if (!ABSOLUTE_JUMP(opcode))
627 tgttgt -= i + 3; /* Calc relative jump addr */
628 if (tgttgt < 0) /* No backward relative jumps */
629 continue;
630 codestr[i] = opcode;
631 SETARG(codestr, i, tgttgt);
632 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 case EXTENDED_ARG:
635 if (codestr[i+3] != MAKE_FUNCTION)
636 goto exitUnchanged;
637 /* don't visit MAKE_FUNCTION as GETARG will be wrong */
638 i += 3;
639 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
642 /* Remove unreachable JUMPs after RETURN */
643 case RETURN_VALUE:
644 if (i+4 >= codelen)
645 continue;
646 if (codestr[i+4] == RETURN_VALUE &&
647 ISBASICBLOCK(blocks,i,5))
648 memset(codestr+i+1, NOP, 4);
649 else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
650 ISBASICBLOCK(blocks,i,4))
651 memset(codestr+i+1, NOP, 3);
652 break;
653 }
654 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 /* Fixup linenotab */
657 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
658 addrmap[i] = i - nops;
659 if (codestr[i] == NOP)
660 nops++;
661 }
662 cum_orig_line = 0;
663 last_line = 0;
664 for (i=0 ; i < tabsiz ; i+=2) {
665 cum_orig_line += lineno[i];
666 new_line = addrmap[cum_orig_line];
667 assert (new_line - last_line < 255);
668 lineno[i] =((unsigned char)(new_line - last_line));
669 last_line = new_line;
670 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 /* Remove NOPs and fixup jump targets */
673 for (i=0, h=0 ; i<codelen ; ) {
674 opcode = codestr[i];
675 switch (opcode) {
676 case NOP:
677 i++;
678 continue;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 case JUMP_ABSOLUTE:
681 case CONTINUE_LOOP:
682 case POP_JUMP_IF_FALSE:
683 case POP_JUMP_IF_TRUE:
684 case JUMP_IF_FALSE_OR_POP:
685 case JUMP_IF_TRUE_OR_POP:
686 j = addrmap[GETARG(codestr, i)];
687 SETARG(codestr, i, j);
688 break;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 case FOR_ITER:
691 case JUMP_FORWARD:
692 case SETUP_LOOP:
693 case SETUP_EXCEPT:
694 case SETUP_FINALLY:
695 case SETUP_WITH:
696 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
697 SETARG(codestr, i, j);
698 break;
699 }
700 adj = CODESIZE(opcode);
701 while (adj--)
702 codestr[h++] = codestr[i++];
703 }
704 assert(h + nops == codelen);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 code = PyBytes_FromStringAndSize((char *)codestr, h);
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100707 CONST_STACK_DELETE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyMem_Free(addrmap);
709 PyMem_Free(codestr);
710 PyMem_Free(blocks);
711 return code;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000712
Alexandre Vassalotti6f828182009-07-21 02:51:58 +0000713 exitError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 code = NULL;
Alexandre Vassalotti6f828182009-07-21 02:51:58 +0000715
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000716 exitUnchanged:
Antoine Pitrou17b880a2011-03-11 17:27:02 +0100717 CONST_STACK_DELETE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (blocks != NULL)
719 PyMem_Free(blocks);
720 if (addrmap != NULL)
721 PyMem_Free(addrmap);
722 if (codestr != NULL)
723 PyMem_Free(codestr);
724 Py_XINCREF(code);
725 return code;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000726}