Odd incorrect code generated by GCC

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

Can anyone explain the code generated by the compiler for the relatively simple C statement? And how to correct it. I am using the default Studio 6 settings.

SPCR &= !(1<<SPE); // disable SPI
2c2: 8c b5 in r24, 0x2c ; 44
2c4: 1c bc out 0x2c, r1 ; 44
Should it not resemble this?
SPCR |= (1<<SPE); // enable the SPI
224: 8c b5 in r24, 0x2c ; 44
226: 80 64 ori r24, 0x40 ; 64
228: 8c bd out 0x2c, r24 ; 44

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Solved my problem. Replaced the &= with ^=
[/code] SPCR ^= (1<<SPE); // disable SPI
2c2: 9c b5 in r25, 0x2c ; 44
2c4: 80 e4 ldi r24, 0x40 ; 64
2c6: 89 27 eor r24, r25
2c8: 8c bd out 0x2c, r24 ; 44

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

How about

Quote:

SPCR &= ~(1<<SPE); // disable SPI

You can put lipstick on a pig, but it is still a pig.

I've never met a pig I didn't like, as long as you have some salt and pepper.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

CRB603 wrote:
Can anyone explain the code generated by the compiler for the relatively simple C statement?
The generated code is absolutely correct.

Your "SPCR &= !(1<<SPE);" is equivalent to "SPCR = 0;" and that is what the code does (r1 contains 0). The only "odd" thing is the unnecessary read, but that is the result of SPCR being volatile.

PS: You really need to take your C book and read about the difference between '!' and '~'.

Stefan Ernst

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Solved my problem. Replaced the &= with ^=

SPCR ^= (1<<SPE); // disable SPI

That will only disable the SPI if it was enabled to begin with. If it was disabled, it would enable the SPI.

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Steve,
You are correct, but at the point in question I know the state of the SPI.
Stefan,
Of course you are correct, what a silly mistake. Computers can always humble us.
Corky

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

CRB603 wrote:
Steve,
You are correct, but at the point in question I know the state of the SPI.
The compiler doesn't and there is no XORI instruction, but that's not the worst.
The worst is that no one else reading your code will be able to figure out why you used an xor.
Using an xor suggests that you do not know the state of the bit,
but you know that you want it to change.
If the code works, it might be deemed too fragile to touch.

"SCSI is NOT magic. There are *fundamental technical
reasons* why it is necessary to sacrifice a young
goat to your SCSI chain now and then." -- John Woods