Bytecode optimisation

Jeff Epler jepler at inetnebr.com
Tue May 18 11:07:44 EDT 1999


On 17 May 1999 23:13:16 GMT, Corran Webster
 <cwebster at math.tamu.edu> wrote:
>  * More complex optimisation is certainly possible, although a lot more 
>    work would be required.  I've made a first stab at block-level analysis
>    and it seems feasible.  In particular it would be nice to detect and 
>    shift loop invariant code.
>
>  * If type information could be guessed, then more might be able to be 
>    squeezed.  At the moment I can't simplify something like 0 * x, 
>    because x could be anything, and could call an arbitrary function to 
>    perform the operation.  If it was known that x was an integer, then we 
>    could safely replace it with 0.  Assert statements could be used for
>    this sort of thing.

How can you tell if code is loop invariant without knowing the types of
variables?  For instance:
	for i in range(5):
		j=j+a[0]*a[i]
depending on the type of "a", "a[0]" might change each time it is
calculated and not be equivalent to:
	t=a[0]
	for i in range(5):
		r=r+t*a[i]

I don't think you can do that in general without inferring types.

Perhaps you could let the user (coder) promise the optimizer that it can
treat a particular variable as a reference to
	. one of the builtin types "int", "string", "list", "tuple"
	. a numeric type, suitable for CSE elimination, loop hoisting,
	  and expression reorganization
	. an immutable type, suitable for CSE elimination and loop hoisting
	. a const function which always returns the same value for given
	  arguments
	. other things that I haven't thought of
then you'd write something like:
	def example(a):
		r=0
		for i in range(5):
			r=r+a[0]*a[i]
		return r
	example_opt = optimize(example, a=Immutable, range=ConstFunction)
this should provide enough information to turn the function into something
more like:
	def example_opt(a):
		# assert(immutable(a))
		r=0
		t=a[0]
		for i in (0,1,2,3,4):
			r=r+t*a[i]
		return r

Just some random thoughts..

Jeff
-- 
\/ http://www.freshmeat.net/                     Jeff Epler jepler at inetnebr.com
Q:	How do you stop an elephant from charging?
A:	Take away his credit cards.




More information about the Python-list mailing list