Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Lua bytecode for 'if' statments jump backwards?

Tags:

bytecode

lua

I'm writing some Lua code that can read the bytecode produces by the string.dump() function. I'm assuming (because it allows for a few optimizations and less coding) that all OP_JMP instructions increase the instruction pointer forwards when used for if statements. They could technically jump backwards because they use the sBx value (which can be negative). I'm only interested in the bytecode of if statements from the standard Lua 5.1 implementation.

I used chunkspy (awesome tool btw), to look at the bytecode for a few samples.

Here is a basic if statement:

a, b = 1, 2
if a == b then
  print '='
elseif a < b then
  print '<'
else
  print '>'
end

It produces four jumps, none of which are negative:

[08] jmp 4; to [13]
[12] jmp 11; to [24]
[16] jmp 4; to [21]
[20] jmp 3; to [24]

I tried looking for answers in the Lua source code, but it just ended up being confusing (I'm sure it's super elegant code if I spent the time getting to grips with it).

Does anyone know of a case for 'if' statements where lua's OP_JMP instruction has a negative value for sBx or know if they are always positive values?

like image 212
Ryan Avatar asked Oct 11 '12 03:10

Ryan


1 Answers

Short answer: IF statements can't produce negative JMPs (on any optimized compiler, langauage independent). Lua OP_JMP can be negative for loops and goto statements( http://lua-users.org/wiki/GotoStatement )

Long Answer: This is due to the fact that an backward JUMP will only be generated by any compiler if it needs to repeat certain code that it already translated (for, while loops..). If it steps upon a "new" IF-statement it will always put a conditional JMP and the resulting code/bytecode as the next instuctions.

On the other Hand a "strange" compiler can produce negative IF jumps. But that wont make sense. In order to have a negative IF JMP to a certain location, one must already have skipped that very location in the past (by a positive JMP), so it cant be optimized code in terms of execution speed.

like image 129
mschmoock Avatar answered Oct 03 '22 17:10

mschmoock