汇编编程:如何将sumsquare方法结果传回栈?代码修改咨询
Great question! Let's walk through how to modify your sumsquare routine to return the result directly to the stack instead of using the RR register.
First, let's recap the original stack setup when calling sumsquare:
- Before
bsr sumsquare, your stack holds the parametersaandb(structure:[..., a, b]). - Inside
sumsquare, thelink 1instruction creates a stack frame with 1 local variable, making the parameters accessible at offsets-3(fora) and-2(forb) relative to the frame pointer.
Your goal is to replace the str RR instruction (which stores the result to the RR register) with an instruction that writes the result directly to the stack, overwriting the original parameters. Here's the solution:
Modified sumsquare Routine
sumsquare: link 1 // 1 local variable ldl -3 // a ldl -3 // a mul // a*a ldl -2 // b ldl -2 // b mul // b*b add // a*a + b*b → result is on top of stack // Replace str RR with this line: stl -3 // Store the result directly into the stack position of parameter 'a' unlink 1 ajs -1 // Remove the now-unneeded 'b' parameter from the stack ret
Key Changes Explained:
Replace
str RRwithstl -3:- The
stlinstruction stores the value on top of the stack to a stack location relative to the frame pointer. - Using
-3targets the original stack position of parametera, overwriting it with our computed result.
- The
Add
ajs -1beforeret:- After unlinking the stack frame, our stack still contains the original
bparameter. Theajs -1adjusts the stack pointer to remove this extra entry, leaving only our result on the stack when the routine returns.
- After unlinking the stack frame, our stack still contains the original
Simplified Caller Code
You can streamline the caller since we no longer need to delete parameters or load from RR:
ldc 5 // a ldc 12 // b bsr sumsquare stl 1 // Directly store the stack-top result into your variable ....
That's it! This setup makes sumsquare return the result directly to the stack, eliminating the need for the result register.
内容的提问来源于stack exchange,提问作者John Hm

