0

I'm confused on what happens during POP. When POP LR happens does that change the PC to the location of LR, which would be sumi. If it does take it back to sumi wouldn't that just take the recursion even further?

C++:

int sumi(int n) {
  if(n == 0)
  return 0;
else
  return n+sumi(n-1);
}

assembly:

sumi:
CMP R2,#0 ; n is R2
BNE else

then:
MOV R0,#0 ; result in R0
BX LR

else:
PUSH LR 
PUSH R2
SUB R2,R2,#1 
BL sumi
POP R2
ADD R0,R2,R0
POP LR
BX LR
Null
  • 7,448
  • 17
  • 36
  • 48
stumped
  • 145
  • 2
  • 7

1 Answers1

1

The POP LR instruction just pops a value off the stack and puts that value in LR. But together with the next instruction, BX LR, it does pop a value from the stack and put that in PC. On other architectures that action would be called RET or RETURN.

For a single call to sumi (n==0) the stack is not used: the BX LR causes the return to the instruction after the call to sumi.

For a recursive call, the PUSH LR first pushes the LR value on the stack, then the recursive call happens, after which the LR value is restored and copied to the PC by POP LR; BX LR.

Note: if you don't know the role of the LR in ARM subroutine calls you will definitely have to study that!

Wouter van Ooijen
  • 48,407
  • 1
  • 63
  • 136