Constant expression optimization

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Constant expression optimization

pocomane
In lua, some operators and statements are optimized out when acting on literals
{1}, while others are not {2}. I tryed both with lua-5.3 and lua5.4-beta.

Given the constant propagation in the new lua, I think that some effort on this
kind of optimization could be worth. Or is it too complex?

pocomane

{1} Example of optimized code:

a)
return true and true

0+ params, 2 slots, 1 upvalue, 0 locals, 0 constants, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADBOOL 0 1 0
3 [1] RETURN   0 2 1 ; 1 out
4 [1] RETURN   0 1 1 ; 0 out

b)
return 1 + 1

0+ params, 2 slots, 1 upvalue, 0 locals, 0 constants, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADI     0 2
3 [1] RETURN   0 2 1 ; 1 out
4 [1] RETURN   0 1 1 ; 0 out

c)
if 1 then return 1 end

0+ params, 2 slots, 1 upvalue, 0 locals, 0 constants, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADI     0 1
3 [1] RETURN   0 2 1 ; 1 out
4 [1] RETURN   0 1 1 ; 0 out

{2} Example of not-optimized code:

d)
return true == true

0+ params, 2 slots, 1 upvalue, 0 locals, 1 constant, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADBOOL 0 1 0
3 [1] EQK       0 0 1 ; true
4 [1] JMP       1 ; to 6
5 [1] LOADBOOL 0 0 1 ; to 6
6 [1] LOADBOOL 0 1 0
7 [1] RETURN   0 2 1 ; 1 out
8 [1] RETURN   0 1 1 ; 0 out

e)
if 1 then return 1 elseif 1 then return 2 end

0+ params, 2 slots, 1 upvalue, 0 locals, 0 constants, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADI     0 1
3 [1] RETURN   0 2 1 ; 1 out
4 [1] JMP       2 ; to 7
5 [1] LOADI     0 2
6 [1] RETURN   0 2 1 ; 1 out
7 [1] RETURN   0 1 1 ; 0 out

(Actually this is optimized too, it is just emitted some junk code)