How to convert Stack based instructions to Register based

1k Views Asked by At

This is what I have tested with the dis module in python -

>>> def f():
...   a = 1
...   b = 2
...   c = 3
...   a = b + c * a
...   return a + c
...
>>> dis.dis(f)
  2           0 LOAD_CONST               1 (1)
              2 STORE_FAST               0 (a)

  3           4 LOAD_CONST               2 (2)
              6 STORE_FAST               1 (b)

  4           8 LOAD_CONST               3 (3)
             10 STORE_FAST               2 (c)

  5          12 LOAD_FAST                1 (b)
             14 LOAD_FAST                2 (c)
             16 LOAD_FAST                0 (a)
             18 BINARY_MULTIPLY
             20 BINARY_ADD
             22 STORE_FAST               0 (a)

  6          24 LOAD_FAST                0 (a)
             26 LOAD_FAST                2 (c)
             28 BINARY_ADD
             30 RETURN_VALUE

Those are instructions for a stack-based virtual machine. Is there any way to convert the above stack-based instructions into register-based instructions provided I have access to unlimited number of registers.

I only know about one tool which does that, we know that JVM is stack based but Dalvik VM is register-based. When we write code in Java, the class files contain stack based instructions and the dx tool converts the stack based instructions to register based instructions so that it can run in the Dalvik VM. So most probably there could be an algorithm somewhere which I have missed.

Also can there be an edge can where the stack could dynamically grow and shrink(which would be decided in runtime) , in that case it would be impossible to convert stack based instructions to register based. However one tool does it.

Can someone point me to the correct direction. Or know any algorithm which can help in this.

0

There are 0 best solutions below