[Python-Dev] Re: Code Generation Idea Was: Bytecode idea (original) (raw)

Jeff Epler jepler@unpythonic.net
Thu, 27 Feb 2003 07:48:10 -0600


For my native-code translation system (which died an early death), I intended to introduce a new attribute which would indicate what (module) attributes could be considered constant. I think that for whatever reason I decided to call this solid. So for instance, you might write

import math
assert 'pi' in math.__solid__
__solid__ = ['sys', 'math', 'MYCONST', 'MyClass', 'myfun']

MYCONST = 22./7

class MyClass:
    __solid__ = ['mymethod']
    def mymethod(self): return MYCONST - math.pi
    mymethod = staticmethod(jit(mymethod))

def myfun():
    print MyClass.mymethod()
myfun = jit(myfun)

myfun()

This allows a whole range of optimizations. LOAD_GLOBAL optimizes to LOAD_CONST. LOAD_CONST + LOAD_ATTR optimizes to LOAD_CONST. Then more constant folding becomes possible.

In MyFun, the sequence LOAD_GLOBAL MyClass LOAD_ATTR mymethod CALL_FUNCTION can be reduced to LOAD_CONST MyClass.mymethod CALL_FUNCTION which could even allow MyClass.mymethod to be inlined

In MyClass.mymethod, the arithmetic reduces from LOAD_GLOBAL, LOAD_GLOBAL, LOAD_ATTR, BINARY_SUBTRACT to LOAD_CONST, LOAD_CONST, BINARY_SUBTRACT with compiletime-known types which can be turned into a single constant load.

In the most extreme case, the code (myfun + mymethod) could reduce to the sequence LOAD_CONST, PRINT_ITEM, PRINT_NEWLINE, RETURN_NONE avoiding all namespace lookups and function calls.

Jeff