Why does AVR-gcc subtract pointers instead of adding?

Go To Last Post
2 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This is a very weird one for me.

 

The gcc compiler generates correct code, but it does it in an inexplicably weird way.

 

Say I have a pointer in memory, say 0x98fa, declare as a readonly array of pointers (so it's in flash).

 

I want to index this array, like char * something = motor_map[n]

 

I would expect the compiler to multiply n by the size of a pointer (e.g. 2) and then add the address of the array.

 

It actually *subtracts* the 2's complement negative value of the array pointer.

 

So it's effectively subtracting 0x6706 from the offset (?!). This causes an overflow, of course, then returns the correct result.

 

Why would it do this?

This topic has a solution.
Last Edited: Mon. Apr 15, 2019 - 01:57 PM
This reply has been marked as the solution. 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This is nothing to do with GCC specifically. It's to do with the AVR chipset designed by Atmel. The designers, in trying to pack as much opcode functionality as possible into 16 bits, realised that there was no need to have both ADDI and SUBI but that SUBI R,-n is the same as ADDI R,n. So there only is subtract immediate.

 

So when the GCC compiler, or any compiler, or any Asm program wants to add an offset to something it subtracts the negative offset.

 

First users of AVR find this "odd". After a while it becomes second nature.

 

In fact the AVR was a co-design collaboration between Atmel and the IAR compiler developers so the actual instruction set was never meant to be "exposed" anyway - it's only there to make a C/C++ compiler as easy to implement as possible and if, in the "hidden" generated code of the compiler it happens to so SUB -ve's then no one will ever see or care.

 

(except you did).

 

PS the AVR opcode manual is here:

 

http://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf

 

Look up "SUBI" and then try looking up the expected ADDI you might expect to be its partner.

Last Edited: Mon. Apr 15, 2019 - 11:39 AM