I'm trying to optimize my VMtranslator by reusing the same call if the functionName and nArgs are the same, but in the return the CPUEmulator gives me a A = -5 illigal operation error. That's my code:
if(isCalled(operator, segment, offset)){
sprintf(output, "@%s$retC.%i\nD=A\n@R15\nM=D\n"
"@%s$retFirst\n0;JMP\n(%s$retC.%i)\n",
segment, count, segment, segment, count);
count++;
}else {
sprintf(output, "@%s$retC.%i\nD=A\n@R15\nM=D\n"
"(%s$retFirst)\n@%s$ret.%i\n"
"D=A\n@SP\nM=M+1\nA=M-1\nM=D\n@SAVE_RET_%i\nD=A\n"
"@R13\nM=D\n@SAVE\n0;JMP\n(SAVE_RET_%i)\n@SP\n"
"D=M\n@5\nD=D-A\n@%li\nD=D-A\n@ARG\nM=D\n@%s\n0;JMP\n"
"(%s$ret.%i)\n@R15\nA=M\n0;JMP\n(%s$retC.%i)\n",
segment, count, segment,
segment, count, count, count,
strtol(offset, NULL, 10),
segment, segment, count, segment, count);
count++;
}
And this is my return code:
char *return_init(){
return "//RESTORE CODE\n(RESTORE)\n@5\nD=A\n@LCL\nA=M-D\nD=M\n@R14\nM=D\n"
"@SP\nAM=M-1\nD=M\n@ARG\nA=M\nM=D\n"
"D=A+1\n@SP\nM=D\n"
"@LCL\nD=M-1\n@R13\nAM=D\nD=M\n@THAT\nM=D\n"
"@R13\nAM=M-1\nD=M\n@THIS\nM=D\n"
"@R13\nAM=M-1\nD=M\n@ARG\nM=D\n"
"@R13\nAM=M-1\nD=M\n@LCL\nM=D\n"
"@R14\nA=M\n0;JMP\n";
}
How can I solve this error?
I have already tried to remove dead code and use subrutines for calls and returns (as you can see for the @SAVE and @RESTORE) but I need to trim down other 5000 lines.