Skip to content
Advertisement

Interpreting basic ARM instructions

I have been a set few questions, one of them is:

Which of these ARM instructions clears register r5, so that all of it’s bits are set to ’0’?

and r5, r5, #0
eor r5, r5, r5
lsr r5, #32
sub r5, r5, r5

From my understanding sub r5, r5, r5 clears the register as it subtracts the number from itself. The and and eor ones clearly look wrong.

Does the lsr r5, #32 also clear the register? It shifts the r5 register by 32 bits, right? So, it makes sense for that instruction to clear the register too if it does.


Related to this, I also need to interpret this code:

What is the relationship between the contents of register r0 and register r1 when the following sequence of ARM instructions is executed?

    mov r0, #12
    mov r1, #1
start:
    cmp r0, #0
    ble end
    mul r1, r0, r1
    sub r0, r0, #1
    b start
end:

I am not entirely sure what the cmp r0, #0 does and if it changes the value of r0 in the end. I know that it compares the value.

So, from my understanding, after this code is run, mul r1, r0, r1 means that r1 is set to equal 12 as 1 * 12 = 12 (if the cmp r0, #0 doesn’t affect the value of r0, which I don’t know).

So, r1 is set to 12 – 1 = 11.

Can anyone clarify if I got the correct values for r0 (12) and r1 (11) after this code is run, and what exactly cmp r0, #0 and ble end does here and how it affects the register r0, if at all?

Advertisement

Answer

For the first part:

Which of these ARM instructions clears register r5, so that all of its bits are set to ’0’?

All of them!

and r5, r5, #0

That’s the equivalent of r5 = r5 & 0, ANDing all bits with zero will clear the register.

eor r5, r5, r5

This is r5 = r5 ^ r5, the “exclusive OR” operation. XORing with itself also results in zero, since 1 ^ 1 is 0 too.

lsr r5, #32

As you mentioned, shifting all 32 bits right will zero them all out. The ARM specification even says for LSR:

if the shift is 32, Rd is cleared, and the last bit shifted out remains in the C flag

sub r5, r5, r5

Again, r5 = r5 - r5 will zero it out.


The code from the second part is doing this (in C code):

int r0 = 12;
int r1 = 1;
while (r0 > 0)
    r1 *= r0--;

So, at the end of the loop, r1 will have the product of the numbers 12, 11, 10… down to 1. In other words, this is calculating the factorial of r0 and storing it on r1.

The cmp instruction is simply comparing r0 to the constant 0 and setting the flags, so that the ble (branch if less-or-equal) can act on it. The cmp instruction doesn’t modify its operands. Both instructions together can be read as:

if (r0 <= 0)
    goto end;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement