Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ARM ADD with 2 or 3 operands?

Looking into the documentation of armkeil http://www.keil.com/support/man/docs/armasm/armasm_dom1361289861747.htm you always need 3 variables when you do an ADD function, for example:

"MOV r2,#4 \n\t"
"ADD r2,r2,#3 \n\t"

this has an outcome of 7 in register 2. But when I try the following:

"MOV r2,#4 \n\t"
"ADD r2,#3 \n\t"

The outcome is the same, what is the fundamental difference between those 2? Is it allowed to use the second one?

like image 713
J. Joly Avatar asked Oct 22 '25 14:10

J. Joly


1 Answers

ARM syntax allows omitting the middle operand (first source) when it's the same as the destination. (At least in GAS "Unified" syntax; originally ARM Thumb syntax only allowed it when the machine encoding actually had a separate destination, or something. GAS has different syntaxes; GCC normally puts it in .syntax unified mode IIRC, so that's the context for inline asm)

ADD r2,r2,#3 is exactly identical to ADD r2,#3 for assemblers that accept both. Keil's assembler may not, IDK.

Keil vs. GAS / GCC use different directives, but mostly the same syntax for instructions I think.


Some thumb instruction encodings only have room to encode 2 operands, so they are like dst += immediate not dst = src + immediate at the machine-code level. At the asm source level, Keil documents it as ADDS Rd, Rd, #imm (in the page you linked).

The other 16-bit encoding of adds only has a 3-bit immediate (0..7), but uses those bits to allow encoding a separate destination, adds Rd, Rn, #imm.

(Note that add instead of adds generally requires a 32-bit instruction, so don't do that unless you need to preserve flags.)

I mention this because your previous questions were about Cortex-M. GAS probably still accepts add r2, #3 when assembling in ARM mode. The first source is just implicitly the destination.

like image 57
Peter Cordes Avatar answered Oct 25 '25 23:10

Peter Cordes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!