I'm working on an iPhone/iPad project, and I want to update the status register during some (not all) arithmetic operations. By default, Xcode uses 'Compile for Thumb' and I don't want to change it.
The following GCC inline assembly code works fine under ARM, but results in a compile error under Thumb: 'instruction not supported in Thumb16 mode - adds r6,r4,r5'. The problem lies in the status register update. (I'm also aware that movcs
and strcs
will need to be changed).
Does Thumb have an ADD instruction which sets Overflow (V) or Carry (C) in the CPSR? If not, are there Thumb-specific assembly level workarounds to test for overflows and carries?
uint32_t result, a, b;
int no_carry = 1;
...
__asm__
(
"ldr r4, %[xa] ;" // R4 = a
"ldr r5, %[xb] ;" // R5 = b
"adds r6, r4, r5 ;" // R6 = R4 + R5, set status
"movcs r4, #0 ;" // set overflow (if carry set)
"strcs r4, %[xc] ;" // store it (if carry set)
"str r6, %[xr] ;" // result = R6
: [xr] "=m" (result), [xc] "=m" (no_carry)
: [xa] "m" (a), [xb] "m" (b)
: "r4", "r5", "r6"
);
...
EDIT: Registers also need to be moved around to take advantage of the ARM ABI at Application Binary Interface (ABI) for the ARM Architecture.
According to the Thumb-16 Quick Reference Guide, the ADDS
instruction should be available. This appears to be a bug in the assembler (as was confirmed by @dwelch).
I found I could work around it by issuing instructions pre-encoded using assembler directives. For example:
__asm__
(
"ldr r0, %[xa] ;" // R0 = a
"ldr r1, %[xb] ;" // R1 = b
"adds r1, r1, r0 ;" // R1 = a + b
...
);
would be realized using:
__asm__
(
"ldr r0, %[xa] ;" // R0 = a
"ldr r1, %[xb] ;" // R1 = b
".inst.w 0x1809 ;" // Issue 'adds r1, r1, r0'
...
);
If I wanted adds r2, r2, r1
, the code should emit .inst.w 0x1852
, and so on.
EDIT: Code recently updated due to arm thumb2 ldr.w syntax? on the Binutils mailing list.