aboutsummaryrefslogtreecommitdiff
path: root/py/bc.c
diff options
context:
space:
mode:
authorDamien George <damien.p.george@gmail.com>2019-09-16 22:12:59 +1000
committerDamien George <damien.p.george@gmail.com>2019-10-01 12:26:22 +1000
commitb5ebfadbd615de42c43851f27a062bacd9147996 (patch)
treee4602e96a0eaf9ee0c30913dbabfe9013dda617a /py/bc.c
parent81d04a0200e0d4038c011e4946bfae5707ef9d9c (diff)
py: Compress first part of bytecode prelude.
The start of the bytecode prelude contains 6 numbers telling the amount of stack needed for the Python values and exceptions, and the signature of the function. Prior to this patch these numbers were all encoded one after the other (2x variable unsigned integers, then 4x bytes), but using so many bytes is unnecessary. An entropy analysis of around 150,000 bytecode functions from the CPython standard library showed that the optimal Shannon coding would need about 7.1 bits on average to encode these 6 numbers, compared to the existing 48 bits. This patch attempts to get close to this optimal value by packing the 6 numbers into a single, varible-length unsigned integer via bit-wise interleaving. The interleaving scheme is chosen to minimise the average number of bytes needed, and at the same time keep the scheme simple enough so it can be implemented without too much overhead in code size or speed. The scheme requires about 10.5 bits on average to store the 6 numbers. As a result most functions which originally took 6 bytes to encode these 6 numbers now need only 1 byte (in 80% of cases).
Diffstat (limited to 'py/bc.c')
-rw-r--r--py/bc.c15
1 files changed, 8 insertions, 7 deletions
diff --git a/py/bc.c b/py/bc.c
index c32d5c415..7544ffc5f 100644
--- a/py/bc.c
+++ b/py/bc.c
@@ -124,13 +124,14 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw
code_state->frame = NULL;
#endif
- // get params
- size_t n_state = mp_decode_uint(&code_state->ip);
- code_state->ip = mp_decode_uint_skip(code_state->ip); // skip n_exc_stack
- size_t scope_flags = *code_state->ip++;
- size_t n_pos_args = *code_state->ip++;
- size_t n_kwonly_args = *code_state->ip++;
- size_t n_def_pos_args = *code_state->ip++;
+ // Get cached n_state (rather than decode it again)
+ size_t n_state = code_state->n_state;
+
+ // Decode prelude
+ size_t n_state_unused, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args;
+ MP_BC_PRELUDE_SIG_DECODE_INTO(code_state->ip, n_state_unused, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args);
+ (void)n_state_unused;
+ (void)n_exc_stack_unused;
code_state->sp = &code_state->state[0] - 1;
code_state->exc_sp_idx = 0;