Skip to content

Commit af27259

Browse files
committed
py: Enable optimisation of multiplying 2 small ints in compiler.
1 parent 2839034 commit af27259

1 file changed

Lines changed: 12 additions & 12 deletions

File tree

py/compile.c

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -115,31 +115,31 @@ mp_parse_node_t fold_constants(mp_parse_node_t pn) {
115115
if (n == 3 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[2])) {
116116
machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
117117
machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[2]);
118-
machine_int_t res;
119118
if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_PLUS)) {
120-
res = arg0 + arg1;
119+
arg0 += arg1;
121120
} else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_MINUS)) {
122-
res = arg0 - arg1;
121+
arg0 -= arg1;
123122
} else {
124123
// shouldn't happen
125124
assert(0);
126-
res = 0;
127125
}
128-
if (MP_PARSE_FITS_SMALL_INT(res)) {
129-
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, res);
126+
if (MP_PARSE_FITS_SMALL_INT(arg0)) {
127+
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0);
130128
}
131129
}
132130
break;
133131

134132
case PN_term:
135133
if (n == 3 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[2])) {
136-
int arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
137-
int arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[2]);
134+
machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
135+
machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[2]);
138136
if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_STAR)) {
139-
#if MICROPY_EMIT_CPYTHON
140-
// can overflow; enabled only to compare with CPython
141-
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0 * arg1);
142-
#endif
137+
if (!mp_small_int_mul_overflow(arg0, arg1)) {
138+
arg0 *= arg1;
139+
if (MP_PARSE_FITS_SMALL_INT(arg0)) {
140+
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0);
141+
}
142+
}
143143
} else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_SLASH)) {
144144
; // pass
145145
} else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_PERCENT)) {

0 commit comments

Comments
 (0)