2
votes

How do i implement a Java function in Hack Assembly? I know that instructions to change variables is easily made, but how does HACK call a function? For Example:

function(int a, int b) {
if (a-b > 0)
return a;
else
return b;
}

My (i think wrong) result is :

@a
D=M
@b
D=D-M 
@JUMPMARK1
D;JGT
@Jumpmark2
0;JMP
(JUMPMARK1)
@a
D=M 
@function
M=D
(Jumpmark2)
@b
D=M
@function
M=D

So the issue is that i dont know where to store the result(return)..should i create a variable like i did in this example for the function and store it there?

1
Are you asking about implementing all the features of the Java language in general, or only about this specific Java function? If the latter, then your real question is how to write a signed max function in Hack, preferably using a conditional branch. If the former, then it's obviously way to broad. Or are you mainly asking how to pass and return function args / return values? (I don't actually know Hack at all so I can't answer, just assembly languages for real CPUs like x86, MIPS, and ARM. Some x86 calling conventions pass args on the stack, but good ones pass args in registers.)Peter Cordes

1 Answers

1
votes

In order to implement true function calls in Hack, you need to first implement a push-down stack. Once that is done it is relatively straightforward.

Then, to make function calls, you load D with the return address and push it. For single-parameter function calls you can pass the function parameter in D; for multiple-parameter calls you will also need to push these values onto the stack.

You then make an unconditional jump to the function. In the function, you do whatever you need to do (including popping any parameters from the stack). Finally, you pop the return address from the stack into A and unconditionally jump.

The return operation can be done in 4 instructions. The call operation requires 9 instructions.

If functions are guaranteed to be non-recursive, you can dispense with the stack and put the function parameters, including the return address, in a fixed block of memory associated with each function.