memorystackvirtual-machinenand2tetris

Confusion related to virtual machine in nand2tetris


So while doing a course on nand2tetris I got stuck in this question.credits: Courseracredits: Coursera

Basically this question is related to building a virtual machine. The virtual machine is quite similar to JVM.


Solution

  • There are 2 main parts to consider here:

    1. call foo 2 : this instruction tells vm to call funcion foo that takes 2 arguments ( which should be pushed on top of the stack before this call ).
      Calling any function means that you should take these steps as follow: push return address on top of stack (SP++), then push LCL, ARG, THIS,THAT ( SP+4). At this point SP should equal 310.
    2. function foo 4 : this is NOT the first instruction in function foo, but still it has an effect on SP as this means that functionfoo has 4 local variables. And these variables must be located somewhere. Where? On top of the stack. This means that before first 'real' instruction of foo gets executed, we must push 4 values onto the stack. What values? Well - according do vm specification it should be 0's, resulting in local variables being initiated to 0. This also means that we increase SP for every local variable ( SP + 4)

    This leads to conclusion that SP, after calling foo but before executing 1st instruction of this function will have value of 314.