Python virtual machine (CPython) converts bytecode to machine language?
I am a little confused about how the PVM gets the processor to execute bytecode instructions. I read somewhere on StackOverflow that it doesn't convert bytecode to machine code (alas, I can't find the stream now).
It already has tons of pre-compiled machine instructions hardcoded, what does it run / fetch one of them based on bytecode?
Thank.
source to share
This is a much higher level than machine language. There's a giant switch
operator looking at each opcode and deciding what to do based on the opcode. Here are some snippets:
switch (opcode) {
...
TARGET(LOAD_CONST) {
PyObject *value = GETITEM(consts, oparg);
Py_INCREF(value);
PUSH(value);
FAST_DISPATCH();
}
...
TARGET(UNARY_NEGATIVE) {
PyObject *value = TOP();
PyObject *res = PyNumber_Negative(value);
Py_DECREF(value);
SET_TOP(res);
if (res == NULL)
goto error;
DISPATCH();
}
...
TARGET(BINARY_MULTIPLY) {
PyObject *right = POP();
PyObject *left = TOP();
PyObject *res = PyNumber_Multiply(left, right);
Py_DECREF(left);
Py_DECREF(right);
SET_TOP(res);
if (res == NULL)
goto error;
DISPATCH();
}
Materials TARGET
and DISPATCH
are part of the optimization that does not go through regular mechanics switch
. Functions like PyNumber_Negative
and PyNumber_Multiply
are part of the Python C API, and they dispatch operations like negation and multiplication.
source to share