I’m learning subroutines in Arm assembly and I’m confused with an example. For ” bne Body ” doesn’t it need a cmp x, y before it? What’s it comparing?
@ Sum of the first "MAX" Fibonacci with subroutine
.text
.global _start
.equ MAX,10
_start: mov r1,#MAX
bl Fib
exit: swi 0x11 @ Terminate the program
@Subroutine to compute sum of n Fibonacci numbers
Fib: sub r1,r1,#2 @ Counter - 2
mov r2,#1
mov r3,#2
mov r0,#3
Body: add r4,r2,r3
add r0,r0,r4 @ Update Sum
mov r2,r3
mov r3,r4
Decr: subs r1,r1,#
bne Body @ If Count != 0, repeat loop
Done: mov pc,lr @ Return from subroutine
The ‘subs’ instruction sets flags, and the ‘bne’ is branching on those flags. Basically, it’s comparing r1 to 0 and branching if it’s not equal to 0. A compare is actually performed as a subtract operation – that’s how you compare 2 numbers in a CPU. Older CPUs didn’t even have compare opcodes, and many that do are really just synonyms for subtract (there might be minor differences in flags set, and also for clarity you should use a compare opcode if one exists).