s instructions to your advantage.
Unlike x86, ARM lets you choose whether to set the condition codes on its instructions, by suffixing the instructions with
s. This is useful for do-while loops, where you can subtract, do some things, and keep that condition set until you want to branch or conditionally execute.
// Subtract from r0, set condition codes
subs r0, r0, #1
// idk, do something silly
ldr r1, [r0, r2]
add r1, r3, r1, lsl #2
str r1, [r0, r2]
// condition codes are still set from subs
// loop while r0 is not zero
This applies in a different way on Thumb-2.
In Thumb-2, most of the narrow instructions always set the condition codes*, while wide instructions give you the freedom of choice. However, the assembler won't warn you if it is using the wide instruction.
Take the following "Hello World" program:
mov r0, #1 // stdout
adr r1, .Lhello // "Hello, World!"
mov r2, #13 // string length
mov r7, #4 // sys_write
svc #0 // write(1, "Hello, World!", 13)
mov r7, #1 // sys_exit
svc #0 // exit(dontcare)
.ascii "Hello, World!"
This is very inefficient, as
mov Rd, #imm is a wide instruction:
0: f04f 0001 mov.w r0, #1
4: f20f 0110 addw r1, pc, #16 // adr r1, .Lhello
8: f04f 020d mov.w r2, #13
c: f04f 0704 mov.w r7, #4
10: df00 svc #0
12: f04f 0701 mov.w r7, #1
16: df00 svc #0
Instead, if you use
movs which sets the condition codes, you get a much smaller result:
0: 2001 movs r0, #1
2: f20f 010c addw r1, pc, #12 // adr r1, .Lhello
6: 220d movs r2, #13
8: 2704 movs r7, #4
a: df00 svc 0
c: 2701 movs r7, #1
e: df00 svc 0
Note: 2 bytes can be saved here by placing this code at an address that is not 4 byte aligned
*There is one exception. IT blocks.
IT Blocks will prevent condition codes from being set, even on narrow instructions (aside from ones like
tst where it is pointless not to).
If you are in a situation where you want to chain up to 4 instructions together without setting the condition codes, you can use
Note that this is only beneficial for two or more instructions, as IT blocks require an opcode themselves. For only one, it might just be better to use a wide instruction or to